<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

license_verification_module_boot();

$pageTitle = 'Licence Verification';
$tablesReady = player_license_tables_ready();
$fixtures = $tablesReady ? license_verification_fixture_options() : [];
$selectedFixtureId = (int) ($_GET['fixture_id'] ?? ($fixtures[0]['id'] ?? 0));
$selectedFixture = $selectedFixtureId > 0 ? get_fixture_by_id($selectedFixtureId) : null;
$fixturePlayers = ($tablesReady && $selectedFixture !== null) ? player_license_fixture_players($selectedFixtureId) : [];
$verificationOpen = $selectedFixture !== null ? fixture_license_verification_is_open($selectedFixture) : false;

require dirname(__DIR__, 2) . '/includes/header.php';
require dirname(__DIR__, 2) . '/includes/sidebar.php';
require dirname(__DIR__, 2) . '/includes/topbar.php';
require dirname(__DIR__, 2) . '/includes/flash.php';
?>
<section class="panel-card mb-4">
    <div class="panel-card-header mb-3">
        <div>
            <p class="eyebrow mb-1">Match-day control</p>
            <h2 class="h4 mb-0">Player licence verification dashboard</h2>
        </div>
    </div>

    <?php if (!$tablesReady): ?>
        <div class="alert alert-warning mb-0">Player licence verification is temporarily unavailable.</div>
    <?php elseif ($fixtures === []): ?>
        <p class="text-muted mb-0">No scheduled fixtures are currently available for licence verification.</p>
    <?php else: ?>
        <form class="row g-3 align-items-end" method="get">
            <div class="col-md-8">
                <label class="form-label" for="fixture_id">Fixture</label>
                <select class="form-select" id="fixture_id" name="fixture_id" onchange="this.form.submit()">
                    <?php foreach ($fixtures as $fixtureOption): ?>
                        <option value="<?php echo e((string) $fixtureOption['id']); ?>" <?php echo (int) $fixtureOption['id'] === $selectedFixtureId ? 'selected' : ''; ?>>
                            <?php echo e($fixtureOption['home_club_name'] . ' vs ' . $fixtureOption['away_club_name'] . ' - ' . format_match_date_time($fixtureOption['match_date'] ?? null, $fixtureOption['match_time'] ?? null, 'Date TBC', 'Time TBC')); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <div class="feature-tile"><i class="bi bi-info-circle"></i>
                    <div>
                        <h4>Window</h4>
                        <p><?php echo $verificationOpen ? 'Open before kickoff' : 'Closed'; ?></p>
                    </div>
                </div>
            </div>
        </form>
    <?php endif; ?>
</section>

<?php if ($tablesReady && $selectedFixture !== null): ?>
    <section class="panel-card mb-4">
        <div class="row g-3">
            <div class="col-md-4">
                <div class="feature-tile"><i class="bi bi-trophy"></i>
                    <div>
                        <h4>Competition</h4>
                        <p><?php echo e($selectedFixture['competition_name']); ?></p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="feature-tile"><i class="bi bi-calendar-event"></i>
                    <div>
                        <h4>Kickoff</h4>
                        <p><?php echo e(format_match_date_time($selectedFixture['match_date'] ?? null, $selectedFixture['match_time'] ?? null, 'Date TBC', 'Time TBC')); ?></p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="feature-tile"><i class="bi bi-geo-alt"></i>
                    <div>
                        <h4>Venue</h4>
                        <p><?php echo e($selectedFixture['venue_name'] ?: 'Venue not assigned'); ?></p>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <section class="panel-card mb-4">
        <div class="panel-card-header mb-3">
            <div>
                <p class="eyebrow mb-1">Scanner</p>
                <h3 class="h5 mb-0">Scan licence QR</h3>
            </div>
        </div>

        <div class="row g-3">
            <div class="col-lg-5">
                <div class="license-scanner-panel">
                    <div id="license-scanner-reader" class="license-scanner-reader">Camera preview will appear here.</div>
                    <div class="d-flex flex-wrap gap-2 mt-3">
                        <button class="btn btn-jlfc" type="button" id="license-scanner-start">Start scanner</button>
                        <button class="btn btn-outline-secondary" type="button" id="license-scanner-stop" disabled>Stop scanner</button>
                    </div>
                </div>
            </div>
            <div class="col-lg-7">
                <label class="form-label" for="license-scanner-input">Scanned or manual verification code</label>
                <div class="input-group mb-3">
                    <input class="form-control" id="license-scanner-input" type="text" placeholder="Scan QR or type verification code">
                    <button class="btn btn-outline-jlfc" type="button" id="license-scanner-find">Find player</button>
                </div>
                <div class="alert alert-info mb-0" id="license-scanner-status">
                    Scan a licence QR code for the selected fixture, or enter the verification code manually.
                </div>
            </div>
        </div>
    </section>

    <section class="panel-card mb-4">
        <div class="panel-card-header mb-3">
            <div>
                <p class="eyebrow mb-1">Eligibility check</p>
                <h3 class="h5 mb-0"><?php echo e($selectedFixture['home_club_name'] . ' vs ' . $selectedFixture['away_club_name']); ?></h3>
            </div>
        </div>

        <?php if ($fixturePlayers === []): ?>
            <p class="text-muted mb-0">No eligible or suspended players were found for this fixture.</p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                        <tr>
                            <th>Player</th>
                            <th>Club</th>
                            <th>Registration</th>
                            <th>Eligibility</th>
                            <th>Licence</th>
                            <th>Verified</th>
                            <th class="text-end">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($fixturePlayers as $fixturePlayer): ?>
                            <?php
                            $licenseForRow = $fixturePlayer['license_id'] === null
                                ? null
                                : [
                                    'id' => $fixturePlayer['license_id'],
                                    'status' => $fixturePlayer['license_status'],
                                    'expires_at' => $fixturePlayer['expires_at'],
                                ];
                            $licenseStatus = player_license_effective_status($licenseForRow);
                            $isVerifiable = player_license_is_verifiable($licenseForRow);
                            ?>
                            <tr class="license-match-row"
                                data-verification-code="<?php echo e((string) ($fixturePlayer['verification_code'] ?? '')); ?>"
                                data-player-name="<?php echo e(trim($fixturePlayer['first_name'] . ' ' . $fixturePlayer['last_name'])); ?>"
                                data-club-name="<?php echo e($fixturePlayer['club_name']); ?>"
                                data-license-status="<?php echo e($licenseStatus); ?>">
                                <td><?php echo e(trim($fixturePlayer['first_name'] . ' ' . $fixturePlayer['last_name'])); ?></td>
                                <td><?php echo e($fixturePlayer['club_name']); ?></td>
                                <td><?php echo e($fixturePlayer['registration_number']); ?></td>
                                <td><span class="badge <?php echo e(player_badge_class($fixturePlayer['eligibility_status'])); ?>"><?php echo e(ucfirst($fixturePlayer['eligibility_status'])); ?></span></td>
                                <td>
                                    <div><?php echo e($fixturePlayer['license_number'] ?: 'Not issued'); ?></div>
                                    <small class="text-muted"><span class="badge <?php echo e(player_license_badge_class($licenseStatus)); ?>"><?php echo e(player_license_status_label($licenseStatus)); ?></span></small>
                                </td>
                                <td>
                                    <?php if (!empty($fixturePlayer['verified_at'])): ?>
                                        <span class="badge bg-success-subtle text-success-emphasis">Verified</span>
                                        <div class="small text-muted mt-1"><?php echo e(($fixturePlayer['verified_by_name'] ?: 'Unknown') . ' - ' . $fixturePlayer['verified_at']); ?></div>
                                    <?php else: ?>
                                        <span class="badge bg-light text-dark">Pending</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-end">
                                    <?php if (!empty($fixturePlayer['verified_at'])): ?>
                                        <form class="d-inline" method="post" action="<?php echo e(base_url('app/modules/licenses/actions.php')); ?>">
                                            <?php echo csrf_input(); ?>
                                            <input type="hidden" name="action" value="clear_verification">
                                            <input type="hidden" name="fixture_id" value="<?php echo e((string) $selectedFixtureId); ?>">
                                            <input type="hidden" name="player_id" value="<?php echo e((string) $fixturePlayer['player_id']); ?>">
                                            <button class="btn btn-outline-secondary btn-sm" type="submit">Clear</button>
                                        </form>
                                    <?php elseif ($verificationOpen && $isVerifiable): ?>
                                        <form class="d-inline" method="post" action="<?php echo e(base_url('app/modules/licenses/actions.php')); ?>">
                                            <?php echo csrf_input(); ?>
                                            <input type="hidden" name="action" value="verify_license">
                                            <input type="hidden" name="fixture_id" value="<?php echo e((string) $selectedFixtureId); ?>">
                                            <input type="hidden" name="player_id" value="<?php echo e((string) $fixturePlayer['player_id']); ?>">
                                            <button class="btn btn-jlfc btn-sm" type="submit" data-license-verify-button="1">Verify</button>
                                        </form>
                                    <?php else: ?>
                                        <span class="text-muted small">Verification unavailable</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </section>
<?php endif; ?>
<?php if ($tablesReady && $selectedFixture !== null && $fixturePlayers !== []): ?>
    <script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
    <script>
        (function() {
            var startButton = document.getElementById('license-scanner-start');
            var stopButton = document.getElementById('license-scanner-stop');
            var statusBox = document.getElementById('license-scanner-status');
            var input = document.getElementById('license-scanner-input');
            var findButton = document.getElementById('license-scanner-find');
            var rows = Array.prototype.slice.call(document.querySelectorAll('.license-match-row'));
            var scanner = null;
            var scannerActive = false;

            function setStatus(message, tone) {
                if (!statusBox) {
                    return;
                }

                statusBox.className = 'alert mb-0';
                statusBox.classList.add(tone || 'alert-info');
                statusBox.textContent = message;
            }

            function clearHighlights() {
                rows.forEach(function(row) {
                    row.classList.remove('table-success', 'license-scanner-hit');
                });
            }

            function findRowByCode(code) {
                var normalizedCode = (code || '').trim().toUpperCase();
                if (!normalizedCode) {
                    return null;
                }

                return rows.find(function(row) {
                    return ((row.getAttribute('data-verification-code') || '').trim().toUpperCase() === normalizedCode);
                }) || null;
            }

            function focusMatchedRow(row, code) {
                clearHighlights();

                if (!row) {
                    setStatus('No player in the selected fixture matches code ' + code + '. Change fixture or scan another licence.', 'alert-warning');
                    return;
                }

                row.classList.add('table-success', 'license-scanner-hit');
                row.scrollIntoView({
                    behavior: 'smooth',
                    block: 'center'
                });

                var playerName = row.getAttribute('data-player-name') || 'Player';
                var clubName = row.getAttribute('data-club-name') || 'Unknown club';
                var licenseStatus = row.getAttribute('data-license-status') || 'unknown';
                var verifyButton = row.querySelector('[data-license-verify-button]');
                var actionText = verifyButton ? 'Use the Verify button on the highlighted row.' : 'This row cannot be verified in the current fixture state.';

                setStatus(playerName + ' from ' + clubName + ' matched code ' + code + '. Licence status: ' + licenseStatus + '. ' + actionText, row.querySelector('.bg-success-subtle') ? 'alert-success' : 'alert-info');
            }

            function handleCode(code) {
                var normalizedCode = (code || '').trim().toUpperCase();
                input.value = normalizedCode;
                focusMatchedRow(findRowByCode(normalizedCode), normalizedCode);
            }

            async function stopScanner() {
                if (!scanner || !scannerActive) {
                    return;
                }

                try {
                    await scanner.stop();
                    await scanner.clear();
                } catch (error) {
                    console.warn(error);
                }

                scannerActive = false;
                startButton.disabled = false;
                stopButton.disabled = true;
                setStatus('Scanner stopped. You can scan again or enter a code manually.', 'alert-info');
            }

            async function startScanner() {
                if (typeof Html5Qrcode === 'undefined') {
                    setStatus('QR scanner library could not load. Use manual code entry instead.', 'alert-warning');
                    return;
                }

                if (!scanner) {
                    scanner = new Html5Qrcode('license-scanner-reader');
                }

                startButton.disabled = true;
                stopButton.disabled = false;

                try {
                    await scanner.start({
                            facingMode: 'environment'
                        }, {
                            fps: 10,
                            qrbox: {
                                width: 220,
                                height: 220
                            }
                        },
                        function(decodedText) {
                            handleCode(decodedText);
                            stopScanner();
                        },
                        function() {}
                    );

                    scannerActive = true;
                    setStatus('Scanner is live. Point the camera at the licence QR code.', 'alert-info');
                } catch (error) {
                    startButton.disabled = false;
                    stopButton.disabled = true;
                    setStatus('Camera access failed. Use manual code entry instead.', 'alert-warning');
                }
            }

            startButton.addEventListener('click', startScanner);
            stopButton.addEventListener('click', function() {
                stopScanner();
            });
            findButton.addEventListener('click', function() {
                handleCode(input.value);
            });
            input.addEventListener('keydown', function(event) {
                if (event.key === 'Enter') {
                    event.preventDefault();
                    handleCode(input.value);
                }
            });
            window.addEventListener('beforeunload', function() {
                stopScanner();
            });
        }());
    </script>
<?php endif; ?>
<?php require dirname(__DIR__, 2) . '/includes/footer.php'; ?>