<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

license_module_boot();

$playerRecord = find_player_or_abort((int) ($_GET['player_id'] ?? 0));
$tablesReady = player_license_tables_ready();
$license = $tablesReady ? get_player_license_by_player_id((int) $playerRecord['id']) : null;
$status = player_license_effective_status($license);
$passportImagePath = player_license_passport_image_path($playerRecord);
$clubWatermarkPath = !empty($playerRecord['club_logo']) ? (string) $playerRecord['club_logo'] : null;
$downloadFileName = strtolower(player_full_name($playerRecord) . '-' . $license['license_number']);
$downloadFileName = preg_replace('/[^a-z0-9]+/', '-', $downloadFileName) ?: 'player-licence';

if (!$tablesReady || $license === null) {
    abort_request(404, 'Licence not found', 'A printable licence is not available for this player yet.');
}

$logoPath = league_logo_path();
?>
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=0.4">
    <title><?php echo e(player_full_name($playerRecord)); ?> Licence - <?php echo e(league_short_name()); ?></title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@600;700&family=DM+Sans:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        body {
            margin: 0;
            min-height: 100vh;
            font-family: 'DM Sans', sans-serif;
            background: linear-gradient(135deg, #f4efe3 0%, #d9e9d7 55%, #f7fbf3 100%);
            color: #123524;
            display: grid;
            place-items: center;
            padding: 24px;
        }

        .license-shell {
            width: min(100%, 920px);
        }

        .license-actions {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            margin-bottom: 16px;
        }

        .license-button {
            border: 0;
            border-radius: 999px;
            padding: 12px 18px;
            font-weight: 700;
            cursor: pointer;
        }

        .license-button.primary {
            background: #123524;
            color: #f7fbf3;
        }

        .license-button.secondary {
            background: #f0e4b7;
            color: #123524;
        }

        .license-button[disabled] {
            opacity: 0.7;
            cursor: wait;
        }

        .license-card {
            position: relative;
            background: radial-gradient(circle at top right, rgba(225, 179, 54, 0.28), transparent 32%), #ffffff;
            border-radius: 28px;
            overflow: hidden;
            box-shadow: 0 28px 70px rgba(18, 53, 36, 0.18);
            border: 1px solid rgba(18, 53, 36, 0.08);
        }

        .license-banner {
            display: grid;
            grid-template-columns: 140px 1fr;
            gap: 20px;
            padding: 28px;
            background: linear-gradient(120deg, #123524 0%, #1f6b45 100%);
            color: #f7fbf3;
        }

        .license-banner img,
        .license-logo-placeholder {
            width: 112px;
            height: 112px;
            border-radius: 24px;
            background: rgba(255, 255, 255, 0.14);
            object-fit: cover;
            display: grid;
            place-items: center;
            font-family: 'Barlow Condensed', sans-serif;
            font-size: 2rem;
            letter-spacing: 0.08em;
        }

        .license-banner h1 {
            margin: 0;
            font-family: 'Barlow Condensed', sans-serif;
            font-size: clamp(2rem, 5vw, 3.3rem);
            letter-spacing: 0.04em;
            text-transform: uppercase;
        }

        .license-banner p {
            margin: 6px 0 0;
            opacity: 0.86;
        }

        .license-content {
            position: relative;
            padding: 28px;
        }

        .license-body {
            display: grid;
            grid-template-columns: 220px minmax(0, 1fr);
            gap: 22px;
            align-items: start;
        }

        .license-passport {
            position: relative;
            border: 1px solid rgba(18, 53, 36, 0.12);
            border-radius: 24px;
            background: linear-gradient(180deg, rgba(217, 233, 215, 0.18), rgba(247, 251, 243, 0.26));
            backdrop-filter: blur(1.5px);
            padding: 18px;
        }

        .license-passport-label {
            display: block;
            font-size: 0.78rem;
            font-weight: 700;
            letter-spacing: 0.08em;
            text-transform: uppercase;
            color: #5b6c5e;
            margin-bottom: 12px;
        }

        .license-passport-frame {
            position: relative;
            aspect-ratio: 4 / 5;
            overflow: visible;
            display: grid;
            place-items: center;
        }

        .license-passport-media {
            width: 100%;
            height: 100%;
            border-radius: 20px;
            overflow: hidden;
            background: rgba(18, 53, 36, 0.08);
            display: grid;
            place-items: center;
            position: relative;
            z-index: 1;
        }

        .license-passport-watermark {
            position: absolute;
            left: 50%;
            bottom: 0;
            width: 52%;
            height: 52%;
            object-fit: contain;
            opacity: 0.4;
            filter: none;
            transform: translate(-50%, 32%);
            pointer-events: none;
            z-index: 3;
        }

        .license-passport-frame img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            display: block;
        }

        .license-passport-media>img {
            position: relative;
            z-index: 2;
        }

        .license-passport-placeholder {
            position: relative;
            z-index: 2;
            display: grid;
            gap: 10px;
            justify-items: center;
            padding: 24px;
            color: #5b6c5e;
            text-align: center;
        }

        .license-passport-placeholder strong {
            font-size: 3rem;
            line-height: 1;
            color: #123524;
        }

        .license-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 16px;
        }

        .license-qr-panel {
            display: grid;
            gap: 12px;
            justify-items: center;
            text-align: center;
        }

        .license-qr-code {
            width: 144px;
            min-height: 144px;
            padding: 10px;
            border-radius: 20px;
            background: rgba(255, 255, 255, 0.6);
            border: 1px solid rgba(18, 53, 36, 0.1);
            display: grid;
            place-items: center;
        }

        .license-qr-code img,
        .license-qr-code canvas {
            display: block;
            max-width: 100%;
            height: auto;
        }

        .license-qr-help {
            color: #5b6c5e;
            font-size: 0.86rem;
            margin: 0;
        }

        .license-panel {
            border: 1px solid rgba(18, 53, 36, 0.1);
            border-radius: 20px;
            padding: 18px;
            background: rgba(247, 251, 243, 0.24);
            backdrop-filter: blur(1.5px);
        }

        .license-panel strong {
            display: block;
            font-size: 0.82rem;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            color: #5b6c5e;
            margin-bottom: 8px;
        }

        .license-panel span {
            font-size: 1.05rem;
            font-weight: 700;
        }

        .license-footer {
            display: flex;
            justify-content: space-between;
            gap: 16px;
            align-items: center;
            margin-top: 22px;
            padding-top: 18px;
            border-top: 1px solid rgba(18, 53, 36, 0.1);
        }

        .license-status {
            display: inline-flex;
            align-items: center;
            border-radius: 999px;
            padding: 10px 16px;
            background: #dceee1;
            color: #0c5a2b;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.08em;
        }

        @media print {
            body {
                background: #ffffff;
                padding: 0;
            }

            .license-actions {
                display: none;
            }

            .license-shell {
                width: 100%;
            }

            .license-card {
                box-shadow: none;
                border: 0;
                border-radius: 0;
            }
        }

        @media (max-width: 768px) {

            .license-banner,
            .license-body,
            .license-grid {
                grid-template-columns: 1fr;
            }

            .license-actions,
            .license-footer {
                flex-direction: column;
                align-items: stretch;
            }
        }
    </style>
</head>

<body>
    <div class="license-shell">
        <div class="license-actions">
            <button class="license-button secondary" type="button" onclick="window.history.back()">Back</button>
            <button class="license-button secondary" type="button" id="download-license-image">Download image</button>
            <button class="license-button primary" type="button" onclick="window.print()">Print licence</button>
        </div>

        <article class="license-card" id="license-card">
            <header class="license-banner">
                <?php if ($logoPath !== null): ?>
                    <img src="<?php echo e(base_url($logoPath)); ?>" alt="League logo">
                <?php else: ?>
                    <div class="license-logo-placeholder"><?php echo e(league_short_name()); ?></div>
                <?php endif; ?>
                <div>
                    <h1><?php echo e(league_short_name()); ?> Player Licence</h1>
                    <p><?php echo e(league_name()); ?></p>
                    <p><?php echo e($playerRecord['club_name']); ?></p>
                </div>
            </header>

            <div class="license-content">
                <div class="license-body">
                    <aside class="license-passport">
                        <span class="license-passport-label">Player passport</span>
                        <div class="license-passport-frame">
                            <?php if ($clubWatermarkPath !== null): ?>
                                <img class="license-passport-watermark" src="<?php echo e(base_url($clubWatermarkPath)); ?>" alt="<?php echo e($playerRecord['club_name']); ?> watermark">
                            <?php endif; ?>
                            <div class="license-passport-media">
                                <?php if ($passportImagePath !== null): ?>
                                    <img src="<?php echo e(base_url($passportImagePath)); ?>" alt="<?php echo e(player_full_name($playerRecord)); ?> passport photo">
                                <?php else: ?>
                                    <div class="license-passport-placeholder">
                                        <strong>•</strong>
                                        <div>No passport image uploaded</div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </aside>

                    <div class="license-grid">
                        <div class="license-panel">
                            <strong>Player</strong>
                            <span><?php echo e(player_full_name($playerRecord)); ?></span>
                        </div>
                        <div class="license-panel">
                            <strong>Registration Number</strong>
                            <span><?php echo e($playerRecord['registration_number']); ?></span>
                        </div>
                        <div class="license-panel">
                            <strong>Licence Number</strong>
                            <span><?php echo e($license['license_number']); ?></span>
                        </div>
                        <div class="license-panel">
                            <strong>Verification Code</strong>
                            <span><?php echo e($license['verification_code']); ?></span>
                        </div>
                        <div class="license-panel">
                            <strong>Issued At</strong>
                            <span><?php echo e($license['issued_at']); ?></span>
                        </div>
                        <div class="license-panel">
                            <strong>Expires At</strong>
                            <span><?php echo e($license['expires_at']); ?></span>
                        </div>
                        <div class="license-panel">
                            <strong>Current Club</strong>
                            <span><?php echo e($playerRecord['club_name']); ?></span>
                        </div>
                        <div class="license-panel license-qr-panel">
                            <strong>Scan For Verification</strong>
                            <div class="license-qr-code" id="license-qr-code"></div>
                            <p class="license-qr-help">Scan this QR in the JLFC verification dashboard to locate the player quickly.</p>
                        </div>
                    </div>
                </div>

                <div class="license-footer">
                    <div>
                        <div class="license-status"><?php echo e(player_license_status_label($status)); ?></div>
                        <p style="margin: 12px 0 0; color: #5b6c5e;">Officials can verify this licence on the JLFC licence dashboard before kickoff.</p>
                    </div>
                    <div style="text-align: right; color: #5b6c5e;">
                        <div>Issued by: <?php echo e($license['issued_by_name'] ?: 'JLFC Office'); ?></div>
                        <div>Club: <?php echo e($playerRecord['club_name']); ?></div>
                    </div>
                </div>
            </div>
        </article>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
    <script>
        (function() {
            var qrTarget = document.getElementById('license-qr-code');
            if (!qrTarget || typeof QRCode === 'undefined') {
                return;
            }

            new QRCode(qrTarget, {
                text: <?php echo json_encode((string) $license['verification_code']); ?>,
                width: 124,
                height: 124,
                colorDark: '#123524',
                colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.M,
            });
        }());

        (function() {
            var downloadButton = document.getElementById('download-license-image');
            var licenseCard = document.getElementById('license-card');
            var defaultLabel = downloadButton ? downloadButton.textContent : '';
            var downloadFileName = <?php echo json_encode($downloadFileName . '.png'); ?>;

            function setBusyState(isBusy) {
                if (!downloadButton) {
                    return;
                }

                downloadButton.disabled = isBusy;
                downloadButton.textContent = isBusy ? 'Preparing image...' : defaultLabel;
            }

            window.downloadLicenseCard = function() {
                if (!downloadButton || !licenseCard || typeof html2canvas === 'undefined') {
                    return Promise.resolve(false);
                }

                setBusyState(true);

                return html2canvas(licenseCard, {
                    backgroundColor: null,
                    scale: 2,
                    useCORS: true,
                    logging: false,
                }).then(function(canvas) {
                    var downloadLink = document.createElement('a');
                    downloadLink.href = canvas.toDataURL('image/png');
                    downloadLink.download = downloadFileName;
                    downloadLink.click();
                    return true;
                }).catch(function(error) {
                    console.error('Failed to export licence image.', error);
                    window.alert('Unable to download the licence image right now. Please try again.');
                    return false;
                }).finally(function() {
                    setBusyState(false);
                });
            };

            if (downloadButton) {
                downloadButton.addEventListener('click', function() {
                    void window.downloadLicenseCard();
                });
            }
        }());
    </script>
</body>

</html>