{% extends '@MauticCore/Default/content.html.twig' %}

{% block headerTitle %}{{ 'mautic.dealflow.update.title'|trans }}{% endblock %}

{% block actions %}{% endblock %}

{% block content %}
    {{ include('@DealFlow/_styles.html.twig') }}

    <style>
        .dealflow-update {
            max-width: 720px;
        }

        .dealflow-update__card {
            background: var(--layer-02);
            border: 1px solid var(--border-subtle-01);
            border-radius: 18px;
            margin-bottom: 20px;
            overflow: hidden;
            padding: 28px;
            transition: opacity .3s ease, border-color .3s ease;
        }

        .dealflow-update__card--success {
            border-color: var(--label-border-green, #a3d9a5);
        }

        .dealflow-update__card--warning {
            border-color: var(--label-border-yellow, #f0c674);
        }

        .dealflow-update__card--danger,
        .dealflow-update__card--error {
            border-color: var(--label-border-red, #e5a5a5);
        }

        .dealflow-update__card--loading {
            opacity: .5;
            pointer-events: none;
            position: relative;
        }

        .dealflow-update__eyebrow {
            color: var(--text-secondary);
            font-size: 12px;
            font-weight: 700;
            letter-spacing: .08em;
            margin-bottom: 8px;
            text-transform: uppercase;
        }

        .dealflow-update__title {
            color: var(--text-primary);
            font-size: 22px;
            font-weight: 700;
            letter-spacing: -.02em;
            line-height: 1.2;
            margin: 0 0 12px;
        }

        .dealflow-update__text {
            color: var(--text-secondary);
            font-size: 15px;
            line-height: 1.65;
            margin: 0 0 16px;
        }

        .dealflow-update__version {
            color: var(--text-primary);
            font-family: monospace;
            font-size: 16px;
            font-weight: 700;
        }

        .dealflow-update__changelog {
            background: var(--layer-01);
            border: 1px solid var(--border-subtle-01);
            border-radius: 12px;
            color: var(--text-secondary);
            font-size: 14px;
            line-height: 1.7;
            margin: 16px 0;
            padding: 16px 20px;
            white-space: pre-line;
        }

        .dealflow-update__actions {
            display: flex;
            gap: 12px;
            margin-top: 20px;
        }

        .dealflow-update__badge {
            border-radius: 999px;
            display: inline-flex;
            font-size: 12px;
            font-weight: 700;
            line-height: 1;
            padding: 6px 12px;
        }

        .dealflow-update__badge--green {
            background: var(--label-background-green);
            border: 1px solid var(--label-border-green);
            color: var(--label-color-green);
        }

        .dealflow-update__badge--yellow {
            background: var(--label-background-yellow);
            border: 1px solid var(--label-border-yellow);
            color: var(--label-color-yellow);
        }

        .dealflow-update__badge--red {
            background: var(--label-background-red);
            border: 1px solid var(--label-border-red);
            color: var(--label-color-red);
        }

        .dealflow-update__meta {
            color: var(--text-secondary);
            font-size: 13px;
            margin-top: 12px;
        }

        .dealflow-update__migration-warning {
            background: var(--label-background-yellow);
            border: 1px solid var(--label-border-yellow);
            border-radius: 12px;
            color: var(--label-color-yellow);
            font-size: 14px;
            font-weight: 600;
            margin-top: 16px;
            padding: 12px 16px;
        }

        .dealflow-update__spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid currentColor;
            border-right-color: transparent;
            border-radius: 50%;
            animation: dealflow-spin .6s linear infinite;
            vertical-align: middle;
            margin-right: 6px;
        }

        .dealflow-update__cli-box {
            background: var(--layer-01);
            border: 1px solid var(--border-subtle-01);
            border-radius: 12px;
            margin: 16px 0 0;
            padding: 20px;
        }

        .dealflow-update__cli-box code {
            background: rgba(0,0,0,0.06);
            border-radius: 4px;
            font-family: monospace;
            font-size: 13px;
            padding: 2px 6px;
        }

        .dealflow-update__cli-box pre {
            background: rgba(0,0,0,0.06);
            border-radius: 8px;
            font-size: 13px;
            line-height: 1.7;
            margin: 12px 0 0;
            overflow-x: auto;
            padding: 14px 16px;
        }

        @keyframes dealflow-spin {
            to { transform: rotate(360deg); }
        }

        .dealflow-update__confirmed-icon {
            color: var(--label-color-green, #2d7d2d);
            font-size: 18px;
            margin-right: 6px;
            vertical-align: middle;
        }
    </style>

    <div class="dealflow-update">

        {# Current version + check now card #}
        <div class="dealflow-update__card" id="df-version-card">
            <div class="dealflow-update__eyebrow">Current Installation</div>
            <h2 class="dealflow-update__title">
                Deal Flow <span class="dealflow-update__version">v{{ updateCheck.currentVersion }}</span>
            </h2>

            {% if updateCheck.fromCache %}
                <p class="dealflow-update__meta" id="df-cache-note">Last checked from cache.</p>
            {% endif %}

            <div class="dealflow-update__actions">
                <button type="button" class="btn btn-default" id="df-check-now-btn" onclick="dealflowCheckNow()">
                    <i class="ri-refresh-line"></i>
                    Check Now
                </button>
            </div>
        </div>

        {# Status card — shows update status from server-side render #}
        <div id="df-status-card">
            {% if updateCheck.error %}
                {# Error state #}
                <div class="dealflow-update__card dealflow-update__card--error">
                    <div class="dealflow-update__eyebrow">Update Check Error</div>
                    <p class="dealflow-update__text">{{ updateCheck.errorMessage }}</p>
                </div>
            {% elseif not updateCheck.eligible %}
                {# Updates expired #}
                <div class="dealflow-update__card dealflow-update__card--warning">
                    <div class="dealflow-update__eyebrow">Update Subscription</div>
                    <h3 class="dealflow-update__title">{{ 'mautic.dealflow.update.not_eligible'|trans }}</h3>
                    <p class="dealflow-update__text">
                        Your update subscription expired{% if updateCheck.updatesUntil %} on {{ updateCheck.updatesUntil }}{% endif %}.
                        {% if updateCheck.updateAvailable %}
                            Version {{ updateCheck.latestVersion }} is available but requires an active update subscription.
                        {% endif %}
                    </p>
                    <div class="dealflow-update__actions">
                        <a class="btn btn-warning" href="https://dealflowplugin.com" target="_blank" rel="noopener">
                            <i class="ri-external-link-line"></i>
                            Renew Updates
                        </a>
                    </div>
                </div>
            {% elseif updateCheck.updateAvailable %}
                {# Update available #}
                <div class="dealflow-update__card dealflow-update__card--danger">
                    <span class="dealflow-update__badge dealflow-update__badge--red">Update Available</span>
                    <h3 class="dealflow-update__title" style="margin-top: 12px;">
                        New version available: v{{ updateCheck.latestVersion }}
                    </h3>
                    <p class="dealflow-update__text">
                        You are running v{{ updateCheck.currentVersion }}.
                    </p>

                    {% if updateCheck.releasedAt %}
                        <p class="dealflow-update__meta">Released {{ updateCheck.releasedAt|date('F j, Y') }}</p>
                    {% endif %}

                    {% if updateCheck.changelog %}
                        <div class="dealflow-update__changelog">{{ updateCheck.changelog }}</div>
                    {% endif %}

                    {% if updateCheck.requiresMigration %}
                        <div class="dealflow-update__migration-warning">
                            <i class="ri-alert-line"></i>
                            This update includes database migrations. Take a database backup before running <code>bin/console mautic:plugins:reload</code>. <code>dealflow:update --rollback</code> restores files only and does not revert database migrations.
                        </div>
                    {% endif %}

                    {% if updateCheck.updatesUntil %}
                        <p class="dealflow-update__meta">Updates included through {{ updateCheck.updatesUntil }}</p>
                    {% endif %}

                    <div class="dealflow-update__cli-box">
                        <strong>To install this update, run these commands on your server:</strong>
                        <pre>bin/console dealflow:update --download
bin/console dealflow:update --apply
rm -rf var/cache/prod &amp;&amp; bin/console cache:warmup
# Restart PHP-FPM or your PHP runtime to clear OPcache</pre>
                        <p style="margin: 12px 0 0; font-size: 13px; color: var(--text-secondary);">
                            If the update causes issues, roll back with: <code>bin/console dealflow:update --rollback</code>
                        </p>
                    </div>
                </div>
            {% else %}
                {# Up to date #}
                <div class="dealflow-update__card dealflow-update__card--success">
                    <span class="dealflow-update__badge dealflow-update__badge--green">Up to date</span>
                    <h3 class="dealflow-update__title" style="margin-top: 12px;">{{ 'mautic.dealflow.update.up_to_date'|trans }}</h3>
                    {% if updateCheck.releasedAt %}
                        <p class="dealflow-update__meta">Released {{ updateCheck.releasedAt|date('F j, Y') }}</p>
                    {% endif %}
                    {% if updateCheck.updatesUntil %}
                        <p class="dealflow-update__meta">Updates included through {{ updateCheck.updatesUntil }}</p>
                    {% endif %}
                </div>
            {% endif %}
        </div>

        {# CLI reference card #}
        <div class="dealflow-update__card">
            <div class="dealflow-update__eyebrow">CLI Reference</div>
            <h3 class="dealflow-update__title" style="font-size: 16px;">Update via command line</h3>
            <p class="dealflow-update__text">
                Updates are managed exclusively from the server CLI. Downloads stage into an isolated
                directory before the swap, which avoids partial web-request upgrades and preserves
                atomic rollback capability.
            </p>
            <div class="dealflow-update__cli-box">
                <pre># Check for updates
bin/console dealflow:update --check

# Download update to an isolated staging directory
bin/console dealflow:update --download

# Apply staged update (atomic swap, creates backup)
bin/console dealflow:update --apply

# Roll back to previous version
bin/console dealflow:update --rollback</pre>
            </div>
        </div>

    </div>

    <script>
        function dealflowCheckNow() {
            var versionCard = document.getElementById('df-version-card');
            var statusCard = document.getElementById('df-status-card');
            var checkBtn = document.getElementById('df-check-now-btn');
            var cacheNote = document.getElementById('df-cache-note');

            // Set loading state
            versionCard.classList.add('dealflow-update__card--loading');
            checkBtn.disabled = true;
            checkBtn.innerHTML = '<span class="dealflow-update__spinner"></span> Checking\u2026';

            var xhr = new XMLHttpRequest();
            xhr.open('GET', '{{ path('mautic_dealflow_update_check', {'refresh': 1}) }}', true);
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

            xhr.onload = function() {
                versionCard.classList.remove('dealflow-update__card--loading');
                checkBtn.disabled = false;
                checkBtn.innerHTML = '<i class="ri-refresh-line"></i> Check Now';

                if (cacheNote) {
                    cacheNote.remove();
                }

                if (xhr.status !== 200) {
                    statusCard.innerHTML = renderError('Update check failed (HTTP ' + xhr.status + ')');
                    return;
                }

                try {
                    var data = JSON.parse(xhr.responseText);
                } catch (e) {
                    statusCard.innerHTML = renderError('Invalid response from server');
                    return;
                }

                if (data.error) {
                    statusCard.innerHTML = renderError(data.errorMessage || 'Unknown error');
                } else if (!data.eligible) {
                    statusCard.innerHTML = renderExpired(data);
                } else if (data.updateAvailable) {
                    statusCard.innerHTML = renderUpdateAvailable(data);
                } else {
                    statusCard.innerHTML = renderUpToDate(data);
                }
            };

            xhr.onerror = function() {
                versionCard.classList.remove('dealflow-update__card--loading');
                checkBtn.disabled = false;
                checkBtn.innerHTML = '<i class="ri-refresh-line"></i> Check Now';
                statusCard.innerHTML = renderError('Network error \u2014 could not reach the server');
            };

            xhr.send();
        }

        function renderError(message) {
            return '<div class="dealflow-update__card dealflow-update__card--error">'
                + '<div class="dealflow-update__eyebrow">Update Check Error</div>'
                + '<p class="dealflow-update__text">' + escapeHtml(message) + '</p>'
                + '</div>';
        }

        function renderExpired(data) {
            var html = '<div class="dealflow-update__card dealflow-update__card--warning">'
                + '<div class="dealflow-update__eyebrow">Update Subscription</div>'
                + '<h3 class="dealflow-update__title">Updates Expired</h3>'
                + '<p class="dealflow-update__text">'
                + 'Your update subscription expired';

            if (data.updatesUntil) {
                html += ' on ' + escapeHtml(data.updatesUntil);
            }
            html += '.';

            if (data.updateAvailable) {
                html += ' Version ' + escapeHtml(data.latestVersion) + ' is available but requires an active update subscription.';
            }

            html += '</p>'
                + '<div class="dealflow-update__actions">'
                + '<a class="btn btn-warning" href="https://dealflowplugin.com" target="_blank" rel="noopener">'
                + '<i class="ri-external-link-line"></i> Renew Updates</a>'
                + '</div></div>';

            return html;
        }

        function renderUpdateAvailable(data) {
            var html = '<div class="dealflow-update__card dealflow-update__card--danger">'
                + '<span class="dealflow-update__badge dealflow-update__badge--red">Update Available</span>'
                + '<h3 class="dealflow-update__title" style="margin-top:12px">'
                + 'New version available: v' + escapeHtml(data.latestVersion) + '</h3>'
                + '<p class="dealflow-update__text">You are running v' + escapeHtml(data.currentVersion) + '.</p>';

            if (data.releasedAt) {
                html += '<p class="dealflow-update__meta">Released ' + escapeHtml(formatReleaseDate(data.releasedAt)) + '</p>';
            }

            if (data.changelog) {
                html += '<div class="dealflow-update__changelog">' + escapeHtml(data.changelog) + '</div>';
            }

            if (data.requiresMigration) {
                html += '<div class="dealflow-update__migration-warning">'
                    + '<i class="ri-alert-line"></i> '
                    + 'This update includes database migrations. Take a database backup before running <code>bin/console mautic:plugins:reload</code>. <code>dealflow:update --rollback</code> restores files only and does not revert database migrations.'
                    + '</div>';
            }

            if (data.updatesUntil) {
                html += '<p class="dealflow-update__meta">Updates included through ' + escapeHtml(data.updatesUntil) + '</p>';
            }

            html += '<div class="dealflow-update__cli-box">'
                + '<strong>To install this update, run on your server:</strong>'
                + '<pre>bin/console dealflow:update --download\nbin/console dealflow:update --apply\nrm -rf var/cache/prod &amp;&amp; bin/console cache:warmup\n# Restart PHP-FPM or your PHP runtime to clear OPcache</pre>'
                + '</div>';

            html += '</div>';
            return html;
        }

        function renderUpToDate(data) {
            var html = '<div class="dealflow-update__card dealflow-update__card--success">'
                + '<span class="dealflow-update__badge dealflow-update__badge--green">'
                + '<i class="ri-check-line dealflow-update__confirmed-icon"></i> Confirmed up to date</span>'
                + '<h3 class="dealflow-update__title" style="margin-top:12px">You\u2019re running the latest version</h3>';

            if (data.releasedAt) {
                html += '<p class="dealflow-update__meta">Released ' + escapeHtml(formatReleaseDate(data.releasedAt)) + '</p>';
            }

            if (data.updatesUntil) {
                html += '<p class="dealflow-update__meta">Updates included through ' + escapeHtml(data.updatesUntil) + '</p>';
            }

            html += '</div>';
            return html;
        }

        function escapeHtml(str) {
            if (!str) return '';
            var div = document.createElement('div');
            div.appendChild(document.createTextNode(str));
            return div.innerHTML;
        }

        function formatReleaseDate(value) {
            if (!value) return '';
            var d = new Date(value);
            if (isNaN(d.getTime())) return '';
            return d.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
        }
    </script>
{% endblock %}
