@extends('admin.layouts.app')

@section('title', $title)

@section('content')
    @php
        $checkedAtDisplay = $lastCheckedAt ? $lastCheckedAt->copy()->timezone(config('app.timezone'))->toDayDateTimeString() : 'Never';
        $statusState = $status['status'] ?? 'ok';
        $supportExpiresAt = $status['support_expires_at'] ?? null;
        $supportDate = null;
        if ($supportExpiresAt) {
            try {
                $supportDate = \Carbon\Carbon::parse($supportExpiresAt)->toFormattedDateString();
            } catch (\Exception $exception) {
                $supportDate = null;
            }
        }
        $releaseDate = null;
        if (!empty($status['released_at'])) {
            try {
                $releaseDate = \Carbon\Carbon::parse($status['released_at'])->toFormattedDateString();
            } catch (\Exception $exception) {
                $releaseDate = null;
            }
        }
        $latestReleaseDate = null;
        if (!empty($status['latest_released_at'])) {
            try {
                $latestReleaseDate = \Carbon\Carbon::parse($status['latest_released_at'])->toFormattedDateString();
            } catch (\Exception $exception) {
                $latestReleaseDate = null;
            }
        }
        $accessibleReleaseDate = null;
        if (!empty($status['available_released_at'])) {
            try {
                $accessibleReleaseDate = \Carbon\Carbon::parse($status['available_released_at'])->toFormattedDateString();
            } catch (\Exception $exception) {
                $accessibleReleaseDate = null;
            }
        }
    @endphp
    <div class="row">
        <div class="col-lg-8">
            <div class="bgc-white bd bdrs-3 p-20 mB-20">
                <h3 class="mt-0">Update Status</h3>
                <p class="text-muted">Current version: <strong>{{ $status['current_version'] ?? config('app.version') }}</strong></p>
                <div class="d-flex justify-content-between align-items-center flex-wrap">
                    <div>
                        <span class="text-muted">Last checked:</span>
                        <span class="font-weight-bold">{{ $checkedAtDisplay }}</span>
                        @if ($lastCheckedAt)
                            <span class="badge {{ $wasSuccessful ? 'bg-success' : 'bg-danger' }} ms-2">{{ $wasSuccessful ? 'Successful' : 'Failed' }}</span>
                        @endif
                    </div>
                    <form method="post" action="{{ route('ch-admin.ch_update_post') }}">
                        @csrf
                        <button type="submit" class="btn btn-primary text-white">Check for updates</button>
                    </form>
                </div>

                <hr>

                @if (!($status['license_key_present'] ?? false))
                    <div class="alert alert-warning">
                        Add your license key in <a href="{{ route('ch-admin.settings.show', ['update']) }}" class="alert-link">Settings → Update</a> to enable automatic update checks.
                    </div>
                @elseif ($statusState === 'error')
                    <div class="alert alert-danger">
                        <strong>Unable to contact the update service.</strong>
                        <div>{{ $status['message'] ?? 'Please try again later.' }}</div>
                    </div>
                @elseif ($statusState === 'missing-license')
                    <div class="alert alert-warning">
                        Add your license key in <a href="{{ route('ch-admin.settings.show', ['update']) }}" class="alert-link">Settings → Update</a> to enable automatic update checks.
                    </div>
                @elseif ($status['update_available'] ?? false)
                    <div class="alert alert-info">
                        <strong>Update available:</strong> Version {{ $status['version'] }} ({{ ucfirst($status['type'] ?? 'major') }} update) {{ $releaseDate ? 'was released on ' . $releaseDate : 'is now available' }}.
                    </div>

                    <dl class="row">
                        <dt class="col-sm-4">Release version</dt>
                        <dd class="col-sm-8">{{ $status['version'] }}</dd>

                        <dt class="col-sm-4">Update type</dt>
                        <dd class="col-sm-8">{{ ucfirst($status['type'] ?? 'major') }}</dd>

                        <dt class="col-sm-4">Released at</dt>
                        <dd class="col-sm-8">{{ $releaseDate ?? '—' }}</dd>

                        <dt class="col-sm-4">Support status</dt>
                        <dd class="col-sm-8">
                            @if ($status['support_active'] ?? false)
                                Active{{ $supportDate ? ' until ' . $supportDate : '' }}
                            @else
                                <span class="text-danger">Expired{{ $supportDate ? ' on ' . $supportDate : '' }}</span>
                            @endif
                        </dd>
                    </dl>

                    @if (!empty($status['checksum']))
                        <div class="mt-3">
                            <strong>Checksum ({{ strtoupper($status['checksum_algorithm'] ?? 'sha256') }}):</strong>
                            <pre class="bg-light p-2">{{ $status['checksum'] }}</pre>
                        </div>
                    @endif

                    @if (!empty($status['message']))
                        <div class="alert alert-warning mt-3">{{ $status['message'] }}</div>
                    @endif

                    @if (($status['support_active'] ?? false) && !empty($status['download_url']))
                        <form method="post" action="{{ route('ch-admin.ch_update_apply') }}" class="mt-4" id="apply-update-form">
                            @csrf
                            <div class="alert alert-warning">
                                <strong>Backup required:</strong> Create a complete backup of your ChargePanda files and database before running the automatic updater.
                            </div>
                            <div class="form-check mb-3">
                                <input class="form-check-input" type="checkbox" value="1" id="confirm-backup" name="confirmed_backup" required>
                                <label class="form-check-label" for="confirm-backup">
                                    I have backed up my files and database.
                                </label>
                            </div>
                            <button type="submit" class="btn btn-danger text-white" data-default-text="Apply update automatically">Apply update automatically</button>
                            <div class="alert alert-info mt-3 d-none" id="apply-update-progress" role="status">
                                <div class="d-flex align-items-center">
                                    <span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                                    <span>Applying update. Do not close or navigate away from this page until the process completes.</span>
                                </div>
                            </div>
                        </form>
                    @elseif ($status['support_active'] ?? false)
                        <div class="alert alert-info mt-4">
                            The update is available, but the download package is not yet accessible. Please try again shortly.
                        </div>
                    @endif

                    @if (!empty($status['changelog']))
                        <div class="mt-4">
                            <h4>Changelog</h4>
                            <div class="border rounded p-3 bg-light" style="white-space: pre-wrap;">{!! nl2br(e($status['changelog'])) !!}</div>
                        </div>
                    @endif

                    @if (!($status['support_active'] ?? false))
                        <div class="mt-3">
                            <h5>Latest release</h5>
                            <p class="mb-1">Latest overall: <strong>{{ $status['latest_version'] ?? '—' }}</strong> @if ($latestReleaseDate)(released {{ $latestReleaseDate }})@endif</p>
                            <p class="mb-0">Accessible with current support: <strong>{{ $status['available_version'] ?? '—' }}</strong>@if ($accessibleReleaseDate) (released {{ $accessibleReleaseDate }})@endif</p>
                        </div>
                    @endif
                @else
                    <div class="alert alert-success">
                        You are running the latest available version of ChargePanda.
                    </div>
                @endif
            </div>
        </div>

        <div class="col-lg-4">
            <div class="bgc-white bd bdrs-3 p-20 mB-20">
                <h4 class="mt-0">Backup Reminder</h4>
                <p class="mb-2">Before starting the update process:</p>
                <ul class="list-unstyled m-0">
                    <li class="mb-2">Download a copy of your ChargePanda files.</li>
                    <li>Export a backup of your database.</li>
                </ul>
                <p class="mt-3 mb-0 text-muted">The updater will replace application files and run database migrations automatically once you confirm the backup above.</p>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const form = document.getElementById('apply-update-form');
            if (!form) {
                return;
            }

            const submitButton = form.querySelector('button[type="submit"]');
            const progressMessage = document.getElementById('apply-update-progress');

            form.addEventListener('submit', function () {
                if (submitButton) {
                    const spinnerMarkup = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>' +
                        'Applying update...';
                    submitButton.disabled = true;
                    submitButton.innerHTML = spinnerMarkup;
                }

                if (progressMessage) {
                    progressMessage.classList.remove('d-none');
                }
            });
        });
    </script>
@endpush
