@extends('admin.layouts.master')
@section('title', __('System Updater'))
@section('content')
<style>
/* Full-viewport overlay: above sidebar and all UI so nothing is clickable until update finishes or user exits */
.updater-overlay {
    position: fixed;
    inset: 0;
    z-index: 2147483647;
    display: flex;
    align-items: center;
    justify-content: center;
    pointer-events: auto;
    cursor: wait;
}
.updater-overlay-backdrop {
    position: absolute;
    inset: 0;
    background: rgba(0,0,0,0.6);
    pointer-events: auto;
    cursor: wait;
}
.updater-modal {
    position: relative;
    z-index: 1;
    background: #fff;
    padding: 2rem;
    border-radius: 8px;
    min-width: 320px;
    max-width: 90%;
    box-shadow: 0 4px 20px rgba(0,0,0,0.2);
    pointer-events: auto;
}
.updater-progress-bar { height: 8px; background: #e9ecef; border-radius: 4px; overflow: hidden; }
.updater-progress-fill { height: 100%; background: #0d6efd; transition: width 0.3s; }
.updater-status, .updater-error { font-size: 0.9rem; }
</style>
<div class="container-fluid">
    <div class="row">
        <div class="col-lg-12">
            <h3 class="section-title">{{ __('System Updater') }}</h3>
            <div class="bg-white redious-border p-20 p-sm-30 pt-sm-30">

                @if(isset($is_old) && $is_old)
                <div class="alert alert-warning">
                    <strong><i class="bx bx-info-circle"></i> {{ __('Important notes') }}:</strong>
                    <ul class="mb-0 mt-1">
                        <li>{{ __('Please back up your database and script files before upgrading.') }}</li>
                        @if(!empty($enable_oneclick_updater))
                        <li>{{ __("If you don't need this 1-click update, you can disable it in .env by adding") }} <code>CMS_ENABLE_SYSTEM_UPDATER=false</code></li>
                        @endif
                        <li>{{ __('It will override core application files when you run the update.') }}</li>
                    </ul>
                </div>
                @endif

                @if(empty($license_activated))
                <div class="alert alert-warning">
                    <strong>{{ __("You haven't activated your license yet!") }}</strong><br>
                    {{ __('We are required to activate your license before doing upgrade. Please go to settings page to activate your license.') }}
                    <a href="{{ route('admin.system.settings') }}" class="alert-link">{{ __('Settings') }}</a>
                </div>
                @endif

                @if(!empty($rate_limit_message))
                <div class="alert alert-warning">
                    <i class="bx bx-time-five"></i>
                    {{ is_string($rate_limit_message) ? $rate_limit_message : __('Update check is temporarily limited. Please try again in a minute.') }}
                </div>
                @endif

                @if(!empty($from_cache))
                <div class="alert alert-secondary small">
                    {{ __('Showing cached result. Next check in a minute.') }}
                </div>
                @endif

                <div class="alert fade show d-none alert_div" role="alert">
                    <strong></strong> <span></span>
                </div>

                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">{{ __('Current system status') }}</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <p class="mb-1 text-muted small">{{ __('Your current version') }}</p>
                                <p class="mb-0 font-weight-bold">{{ $version_code ?? $current_version ?? __('N/A') }}</p>
                            </div>
                            <div class="col-md-6">
                                <p class="mb-1 text-muted small">{{ __('Latest version') }}</p>
                                <p class="mb-0 font-weight-bold">{{ $next_version_code ?? $next_version ?? $version_code ?? __('N/A') }}</p>
                                @if(!empty($release_date))
                                <p class="mb-0 small text-muted">{{ __('Released on') }} {{ $release_date }}</p>
                                @endif
                            </div>
                        </div>
                        @if(isset($is_old) && $is_old)
                        <p class="mb-0 mt-3 text-primary"><i class="bx bx-info-circle"></i> {{ __('A new update is available.') }}</p>
                        @else
                        <p class="mb-0 mt-3 text-success"><i class="bx bx-check-circle"></i> {{ __('You are on the latest version.') }}</p>
                        @endif
                    </div>
                </div>

                @if(!empty($changelog_plain) || !empty($changelog))
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">{{ __('Latest changelog') }} @if(!empty($release_date))({{ $release_date }})@endif</h5>
                    </div>
                    <div class="card-body">
                        @if(isset($is_old) && $is_old && ($next_version_code ?? $next_version))
                        <p class="text-primary mb-2">
                            {{ __('A new version') }} ({{ $next_version_code ?? $next_version }} {{ __('released on') }} {{ $release_date ?? '' }}) {{ __('is available to update!') }}
                        </p>
                        @endif
                        @if($next_version_code ?? $next_version)
                        <p class="text-muted small">{{ __('Version') }} {{ $next_version_code ?? $next_version }}</p>
                        @endif
                        <div class="changelog-content bg-light p-3 rounded" style="white-space: pre-wrap;">{!! !empty($changelog_plain) ? e($changelog_plain) : ($changelog ?? '') !!}</div>
                    </div>
                </div>
                @endif

                @if(isset($is_old) && $is_old && !empty($enable_oneclick_updater))
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">{{ __('OneClick System Updater') }}</h5>
                    </div>
                    <div class="card-body">
                        <button type="button" class="btn btn-primary text-white" id="license_updater_one_click"
                                data-url="{{ route('download.system.update') }}"
                                data-update-id="{{ $update_id ?? '' }}"
                                data-version="{{ $next_version ?? '' }}"
                                title="{{ __('Download and install the latest update') }}">
                            <i class="bx bx-download" aria-hidden="true"></i>
                            <span>{{ __('Download & Install Update') }}</span>
                        </button>
                        <button type="button" class="btn btn-secondary disable_btn d-none" id="preloader">
                            <span>{{ __('Please wait...') }}</span>
                        </button>
                    </div>
                </div>
                @elseif(isset($is_old) && $is_old && empty($enable_oneclick_updater))
                <div class="alert alert-secondary mb-4">
                    <i class="bx bx-info-circle"></i>
                    {{ __('1-click update is disabled. Use the Manual System Updater below to update.') }}
                </div>
                @endif

                @if(isset($is_old) && $is_old)
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">{{ __('Manual System Updater') }}</h5>
                    </div>
                    <div class="card-body">
                        <p class="text-muted">{{ __("Having trouble with the One-Click System Updater? No worries! Check out the manual updater below - it's easy, just follow the steps!") }}</p>
                        <div class="alert alert-dismissible fade show d-none mb-4" id="manual_step_result" role="alert">
                            <strong class="manual-step-result-title"></strong>
                            <span class="manual-step-result-message"></span>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <tbody>
                                    <tr>
                                        <td width="40">1</td>
                                        <td>{{ __('Download update files') }}</td>
                                        <td width="100">
                                            <button type="button" class="btn btn-success btn-sm manual-step" data-step="1" data-update-id="{{ $update_id ?? '' }}" data-version="{{ $next_version ?? '' }}">{{ __('Run') }}</button>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>2</td>
                                        <td>{{ __('Update system files') }}</td>
                                        <td><button type="button" class="btn btn-success btn-sm manual-step" data-step="2" data-version="{{ $next_version ?? '' }}" disabled>{{ __('Run') }}</button></td>
                                    </tr>
                                    <tr>
                                        <td>3</td>
                                        <td>{{ __('Update databases') }}</td>
                                        <td><button type="button" class="btn btn-success btn-sm manual-step" data-step="3" data-version="{{ $next_version ?? '' }}" disabled>{{ __('Run') }}</button></td>
                                    </tr>
                                    <tr>
                                        <td>4</td>
                                        <td>{{ __('Publish core assets') }}</td>
                                        <td><button type="button" class="btn btn-success btn-sm manual-step" data-step="4" data-version="{{ $next_version ?? '' }}" disabled>{{ __('Run') }}</button></td>
                                    </tr>
                                    <tr>
                                        <td>5</td>
                                        <td>{{ __('Publish packages assets') }}</td>
                                        <td><button type="button" class="btn btn-success btn-sm manual-step" data-step="5" data-version="{{ $next_version ?? '' }}" disabled>{{ __('Run') }}</button></td>
                                    </tr>
                                    <tr>
                                        <td>6</td>
                                        <td>{{ __('Clean up system update files') }}</td>
                                        <td><button type="button" class="btn btn-success btn-sm manual-step" data-step="6" data-version="{{ $next_version ?? '' }}" disabled>{{ __('Run') }}</button></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                @endif
            </div>
        </div>
    </div>
</div>

<div id="updater_overlay" class="updater-overlay d-none" aria-hidden="true">
    <div class="updater-overlay-backdrop"></div>
    <div class="updater-modal">
        <div class="updater-progress-percent" id="updater_progress_percent">0%</div>
        <div class="updater-progress-bar mt-2">
            <div class="updater-progress-fill" id="updater_progress_fill" style="width: 0%"></div>
        </div>
        <div class="updater-status mt-3" id="updater_status">{{ __('Downloading update files...') }}</div>
        <div class="updater-error text-danger d-none mt-3" id="updater_error"></div>
        <div class="updater-actions mt-4">
            <button type="button" class="btn btn-primary updater-exit-btn d-none" id="updater_exit_btn">{{ __('Click Here To Exit') }}</button>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
(function() {
    var downloadBtn = document.getElementById('license_updater_one_click');
    var preloader = document.getElementById('preloader');
    var alertDiv = document.querySelector('.alert_div');
    var csrf = document.querySelector('meta[name="csrf-token"]');
    var tokenEl = document.querySelector('input[name="_token"]');
    var token = (csrf && csrf.getAttribute('content')) || (tokenEl && tokenEl.value) || '';

    var overlay = document.getElementById('updater_overlay');
    var progressEl = document.getElementById('updater_progress_percent');
    var progressFill = document.getElementById('updater_progress_fill');
    var statusEl = document.getElementById('updater_status');
    var errorEl = document.getElementById('updater_error');
    var exitBtn = document.getElementById('updater_exit_btn');
    var progressInterval = null;

    function showAlert(type, message) {
        if (!alertDiv) return;
        alertDiv.className = 'alert alert-' + type + ' fade show';
        alertDiv.querySelector('span').textContent = message;
        alertDiv.classList.remove('d-none');
    }

    var manualResultEl = document.getElementById('manual_step_result');
    function showManualResult(type, message) {
        if (!manualResultEl) return;
        var titleEl = manualResultEl.querySelector('.manual-step-result-title');
        var msgEl = manualResultEl.querySelector('.manual-step-result-message');
        manualResultEl.className = 'alert alert-' + type + ' alert-dismissible fade show mb-4';
        if (titleEl) titleEl.textContent = (type === 'success' ? '{{ __("Success") }}: ' : '{{ __("Error") }}: ');
        if (msgEl) msgEl.textContent = message || '';
        manualResultEl.classList.remove('d-none');
        manualResultEl.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }

    function hideOverlay() {
        if (overlay) overlay.classList.add('d-none');
        if (progressInterval) { clearInterval(progressInterval); progressInterval = null; }
        if (downloadBtn) downloadBtn.classList.remove('d-none');
        if (downloadBtn) downloadBtn.disabled = false;
        if (preloader) preloader.classList.add('d-none');
    }

    function setOverlayProgress(percent, status, showError, errorMsg) {
        if (progressEl) progressEl.textContent = percent + '%';
        if (progressFill) progressFill.style.width = percent + '%';
        if (statusEl) statusEl.textContent = status;
        if (errorEl) {
            if (showError && errorMsg) {
                errorEl.textContent = errorMsg;
                errorEl.classList.remove('d-none');
            } else {
                errorEl.textContent = '';
                errorEl.classList.add('d-none');
            }
        }
        if (exitBtn) exitBtn.classList.toggle('d-none', !showError);
    }

    function doUpdate(url, versionId, version) {
        if (!versionId) {
            showAlert('danger', '{{ __("Update ID is missing.") }}');
            return;
        }
        if (downloadBtn) downloadBtn.classList.add('d-none');
        if (overlay) {
            overlay.classList.remove('d-none');
            overlay.setAttribute('aria-hidden', 'false');
        }
        setOverlayProgress(5, '{{ __("Downloading update files...") }}', false);

        var p = 5;
        if (progressFill) progressFill.style.width = p + '%';
        progressInterval = setInterval(function() {
            if (p < 85) {
                p += Math.min(10, 85 - p);
                if (progressEl) progressEl.textContent = p + '%';
                if (progressFill) progressFill.style.width = p + '%';
            }
        }, 600);

        var formData = new FormData();
        formData.append('_token', token);
        formData.append('version_id', versionId);
        if (version) formData.append('version', version);
        fetch(url, {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
            body: formData
        }).then(function(r) { return r.json(); }).then(function(res) {
            if (progressInterval) { clearInterval(progressInterval); progressInterval = null; }
            if (res.class === 'success') {
                setOverlayProgress(100, '{{ __("Update complete! Reloading...") }}', false);
                setTimeout(function() { window.location.reload(); }, 1200);
            } else {
                setOverlayProgress(100, '{{ __("Update failed.") }}', true, res.message || '');
                if (exitBtn) exitBtn.addEventListener('click', function onExit() {
                    exitBtn.removeEventListener('click', onExit);
                    hideOverlay();
                }, { once: true });
            }
        }).catch(function() {
            if (progressInterval) { clearInterval(progressInterval); progressInterval = null; }
            setOverlayProgress(100, '{{ __("Update failed.") }}', true, '{{ __("Request failed.") }}');
            if (exitBtn) exitBtn.addEventListener('click', function onExit() {
                exitBtn.removeEventListener('click', onExit);
                hideOverlay();
            }, { once: true });
        });
    }

    if (downloadBtn) {
        downloadBtn.addEventListener('click', function() {
            doUpdate(this.getAttribute('data-url'), this.getAttribute('data-update-id'), this.getAttribute('data-version'));
        });
    }

    document.querySelectorAll('.manual-step').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var step = this.getAttribute('data-step');
            var versionId = this.getAttribute('data-update-id');
            var version = this.getAttribute('data-version');
            if (step === '1' && (!versionId || versionId === '')) {
                showManualResult('danger', '{{ __("Update ID is required for step 1. Check for update first.") }}');
                return;
            }
            if (btn.classList.contains('manual-step-done')) return;
            var formData = new FormData();
            formData.append('_token', token);
            formData.append('step', step);
            if (versionId) formData.append('version_id', versionId);
            if (version) formData.append('version', version);
            var origHtml = this.innerHTML;
            this.disabled = true;
            this.innerHTML = '...';
            fetch('{{ route("admin.updater.manual.step") }}', {
                method: 'POST',
                headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
                body: formData
            }).then(function(r) { return r.json(); }).then(function(res) {
                if (res.class === 'success') {
                    btn.classList.remove('btn-success');
                    btn.classList.add('btn-outline-success', 'manual-step-done');
                    btn.disabled = true;
                    btn.innerHTML = '<i class="bx bx-check-circle"></i> {{ __("Done") }}';
                    var nextStep = parseInt(step, 10) + 1;
                    var nextBtn = document.querySelector('.manual-step[data-step="' + nextStep + '"]');
                    if (nextBtn && !nextBtn.classList.contains('manual-step-done')) {
                        nextBtn.disabled = false;
                    }
                } else {
                    btn.disabled = false;
                    btn.innerHTML = origHtml;
                }
                showManualResult(res.class === 'success' ? 'success' : 'danger', res.message || '');
                if (res.class === 'success' && step === '6') setTimeout(function() { window.location.reload(); }, 1000);
            }).catch(function() {
                btn.disabled = false;
                btn.innerHTML = origHtml;
                showManualResult('danger', '{{ __("Request failed.") }}');
            });
        });
    });
})();
});
</script>
@endsection
