{% 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;
        }

        @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">
        {# Permissions warning #}
        {% if not isWritable %}
            <div class="dealflow-update__card dealflow-update__card--warning" id="df-permissions-warning">
                <div class="dealflow-update__eyebrow">Permissions Required</div>
                <h3 class="dealflow-update__title" style="font-size: 16px;">Auto-updates are disabled</h3>
                <p class="dealflow-update__text">
                    The plugin directory is not writable by the web server. To enable one-click updates, run this command on your server:
                </p>
                <pre style="background: rgba(0,0,0,0.05); padding: 12px 16px; border-radius: 8px; font-size: 13px; margin: 12px 0 0; overflow-x: auto;"><code>chown -R www-data:www-data {{ pluginDir | default('/var/www/mautic/docroot/plugins/DealFlowBundle') }} {{ pluginsDir | default('/var/www/mautic/docroot/plugins') }}</code></pre>
            </div>
        {% endif %}

        {# 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://mauticdealflow.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.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. After installing, run <code>bin/console mautic:plugins:reload</code> to apply schema changes.
                        </div>
                    {% endif %}

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

                    <div class="dealflow-update__actions">
                        <form id="df-install-form" method="post" action="{{ path('mautic_dealflow_update_perform') }}">
                            <input type="hidden" name="_token" value="{{ csrf_token('dealflow_update_install') }}">
                            <input type="hidden" name="download_url" value="{{ updateCheck.downloadUrl }}">
                            <input type="hidden" name="sha256" value="{{ updateCheck.sha256 }}">
                            <button type="button" class="btn btn-danger" onclick="dealflowShowModal('install')">
                                <i class="ri-download-2-line"></i>
                                Download &amp; Install
                            </button>
                        </form>
                    </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.updatesUntil %}
                        <p class="dealflow-update__meta">Updates included through {{ updateCheck.updatesUntil }}</p>
                    {% endif %}
                </div>
            {% endif %}
        </div>

        {# Rollback section — only visible if a backup exists #}
        {% if hasBackup %}
            <div class="dealflow-update__card" id="df-rollback-card">
                <div class="dealflow-update__eyebrow">Recovery</div>
                <h3 class="dealflow-update__title">{{ 'mautic.dealflow.update.rollback'|trans }}</h3>
                <p class="dealflow-update__text">
                    If the last update caused issues, you can roll back to the previous version.
                    This restores the most recent backup created during an update.
                </p>
                <div class="dealflow-update__actions">
                    <form id="df-rollback-form" method="post" action="{{ path('mautic_dealflow_update_rollback') }}">
                        <input type="hidden" name="_token" value="{{ csrf_token('dealflow_update_rollback') }}">
                        <button type="button" class="btn btn-danger" onclick="dealflowShowModal('rollback')">
                            <i class="ri-arrow-go-back-line"></i>
                            Rollback to Previous Version
                        </button>
                    </form>
                </div>
            </div>
        {% endif %}
        {# Confirmation modal #}
        <div id="df-confirm-modal" style="display:none; position:fixed; inset:0; z-index:9999; background:rgba(0,0,0,0.45); align-items:center; justify-content:center;">
            <div style="background:var(--layer-01, #fff); border-radius:16px; max-width:440px; width:90%; padding:32px; box-shadow:0 8px 32px rgba(0,0,0,0.2);">
                <h3 id="df-modal-title" style="margin:0 0 12px; font-size:18px; font-weight:700;"></h3>
                <p id="df-modal-body" style="margin:0 0 24px; color:var(--text-secondary, #555); font-size:14px; line-height:1.6;"></p>
                <div style="display:flex; gap:12px; justify-content:flex-end;">
                    <button type="button" class="btn btn-default" onclick="dealflowCloseModal()" style="min-width:90px;">Cancel</button>
                    <button type="button" class="btn btn-danger" id="df-modal-proceed" style="min-width:90px;">Proceed</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        var dfModalFormId = null;

        function dealflowShowModal(action) {
            var modal = document.getElementById('df-confirm-modal');
            var title = document.getElementById('df-modal-title');
            var body = document.getElementById('df-modal-body');
            var proceedBtn = document.getElementById('df-modal-proceed');

            if (action === 'install') {
                title.textContent = 'Install Update';
                body.textContent = 'This will download and install the latest version of Deal Flow. A backup of the current version will be created automatically.';
                dfModalFormId = 'df-install-form';
            } else {
                title.textContent = 'Rollback to Previous Version';
                body.textContent = 'This will replace the current plugin files with the backup from the previous version. Only use this if the last update caused issues.';
                dfModalFormId = 'df-rollback-form';
            }

            modal.style.display = 'flex';

            proceedBtn.onclick = function () {
                modal.style.display = 'none';
                var form = document.getElementById(dfModalFormId);
                if (form) form.submit();
            };

            // Close on backdrop click
            modal.onclick = function (e) {
                if (e.target === modal) dealflowCloseModal();
            };

            // Close on Escape
            document.addEventListener('keydown', dealflowEscHandler);
        }

        function dealflowCloseModal() {
            document.getElementById('df-confirm-modal').style.display = 'none';
            document.removeEventListener('keydown', dealflowEscHandler);
        }

        function dealflowEscHandler(e) {
            if (e.key === 'Escape') dealflowCloseModal();
        }

        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 — 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://mauticdealflow.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.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. After installing, run <code>bin/console mautic:plugins:reload</code> to apply schema changes.'
                    + '</div>';
            }

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

            if (data.downloadUrl && data.sha256 && data.installUrl && data.csrfToken) {
                html += '<div class="dealflow-update__actions">'
                    + '<form id="df-install-form" method="post" action="' + escapeHtml(data.installUrl) + '">'
                    + '<input type="hidden" name="_token" value="' + escapeHtml(data.csrfToken) + '">'
                    + '<input type="hidden" name="download_url" value="' + escapeHtml(data.downloadUrl) + '">'
                    + '<input type="hidden" name="sha256" value="' + escapeHtml(data.sha256) + '">'
                    + '<button type="button" class="btn btn-danger" onclick="dealflowShowModal(\'install\')">'
                    + '<i class="ri-download-2-line"></i> Download &amp; Install</button>'
                    + '</form></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.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;
        }
    </script>
{% endblock %}
