<?php

declare(strict_types=1);

require_once __DIR__ . '/app/core/auth.php';
require_once __DIR__ . '/app/core/csrf.php';
require_once __DIR__ . '/app/core/permissions.php';
require_once __DIR__ . '/app/modules/fixtures/helpers.php';

require_login();
require_permission('view_dashboard');

$pageTitle = 'Dashboard';
$user = current_user();
$canManageMatchPreparation = 'can_manage_match_preparation';
$fixturePreparationNotifications = 'fixture_preparation_notifications';

$metrics = [
    [
        'label' => 'Clubs',
        'value' => 0,
        'icon' => 'bi-shield-check',
        'query' => 'SELECT COUNT(*) FROM clubs',
    ],
    [
        'label' => 'Players',
        'value' => 0,
        'icon' => 'bi-people',
        'query' => 'SELECT COUNT(*) FROM players',
    ],
    [
        'label' => 'Fixtures',
        'value' => 0,
        'icon' => 'bi-calendar-event',
        'query' => 'SELECT COUNT(*) FROM fixtures',
    ],
    [
        'label' => 'News Posts',
        'value' => 0,
        'icon' => 'bi-newspaper',
        'query' => 'SELECT COUNT(*) FROM news_posts',
    ],
    [
        'label' => 'Users',
        'value' => 0,
        'icon' => 'bi-people-fill',
        'query' => 'SELECT COUNT(*) FROM users',
        'permission' => 'manage_users',
    ],
    [
        'label' => 'Roles',
        'value' => 0,
        'icon' => 'bi-shield-lock-fill',
        'query' => 'SELECT COUNT(*) FROM roles',
        'permission' => 'manage_roles',
    ],
    [
        'label' => 'Seasons',
        'value' => 0,
        'icon' => 'bi-calendar-range-fill',
        'query' => 'SELECT COUNT(*) FROM seasons',
        'permission' => 'manage_seasons',
    ],
    [
        'label' => 'Competitions',
        'value' => 0,
        'icon' => 'bi-trophy-fill',
        'query' => 'SELECT COUNT(*) FROM competitions',
        'permission' => 'manage_competitions',
    ],
    [
        'label' => 'Approved Clubs',
        'value' => 0,
        'icon' => 'bi-shield-fill-check',
        'query' => 'SELECT COUNT(*) FROM clubs WHERE license_status = "approved"',
        'permission' => 'manage_clubs',
    ],
    [
        'label' => 'Club Staff',
        'value' => 0,
        'icon' => 'bi-person-badge-fill',
        'query' => 'SELECT COUNT(*) FROM club_staff',
        'permission' => 'manage_club_staff',
    ],
    [
        'label' => 'Approved Players',
        'value' => 0,
        'icon' => 'bi-person-check-fill',
        'query' => 'SELECT COUNT(*) FROM players WHERE eligibility_status = "eligible"',
        'permission' => 'manage_players',
    ],
    [
        'label' => 'Venues',
        'value' => 0,
        'icon' => 'bi-building-fill-check',
        'query' => 'SELECT COUNT(*) FROM venues',
        'permission' => 'manage_venues',
    ],
    [
        'label' => 'Referees',
        'value' => 0,
        'icon' => 'bi-whistle',
        'query' => 'SELECT COUNT(*) FROM referees',
        'permission' => 'manage_referees',
    ],
    [
        'label' => 'Verified Results',
        'value' => 0,
        'icon' => 'bi-clipboard-check-fill',
        'query' => 'SELECT COUNT(*) FROM match_results WHERE result_status = "verified"',
        'permission' => 'submit_results',
    ],
    [
        'label' => 'Table Entries',
        'value' => 0,
        'icon' => 'bi-table',
        'query' => 'SELECT COUNT(*) FROM league_table',
        'permission' => 'manage_table',
    ],
    [
        'label' => 'Match Events',
        'value' => 0,
        'icon' => 'bi-list-ol',
        'query' => 'SELECT COUNT(*) FROM match_events',
        'permission' => 'manage_statistics',
    ],
    [
        'label' => 'Active Suspensions',
        'value' => 0,
        'icon' => 'bi-shield-exclamation',
        'query' => 'SELECT COUNT(*) FROM suspensions WHERE status = "active"',
        'permission' => 'manage_discipline',
    ],
    [
        'label' => 'Open Protests',
        'value' => 0,
        'icon' => 'bi-megaphone-fill',
        'query' => 'SELECT COUNT(*) FROM protests WHERE status IN ("submitted", "under_review")',
        'permission' => 'manage_protests',
    ],
    [
        'label' => 'Outstanding Payments',
        'value' => 0,
        'icon' => 'bi-cash-coin',
        'query' => 'SELECT COUNT(*) FROM club_payments WHERE payment_status <> "paid"',
        'permission' => 'manage_finance',
    ],
    [
        'label' => 'Awards Issued',
        'value' => 0,
        'icon' => 'bi-trophy',
        'query' => 'SELECT COUNT(*) FROM awards',
        'permission' => 'manage_awards',
    ],
    [
        'label' => 'Published News',
        'value' => 0,
        'icon' => 'bi-newspaper',
        'query' => 'SELECT COUNT(*) FROM news_posts WHERE status = "published"',
        'permission' => 'manage_media',
    ],
    [
        'label' => 'Gallery Items',
        'value' => 0,
        'icon' => 'bi-images',
        'query' => 'SELECT COUNT(*) FROM media_gallery',
        'permission' => 'manage_media',
    ],
    [
        'label' => 'Open Transfers',
        'value' => 0,
        'icon' => 'bi-arrow-left-right',
        'query' => 'SELECT COUNT(*) FROM transfers WHERE current_stage NOT IN ("completed", "rejected", "cancelled")',
        'permission' => 'manage_transfers',
    ],
];

if (is_super_admin()) {
    $metrics[] = [
        'label' => 'Site Visits Today',
        'value' => 0,
        'icon' => 'bi-activity',
        'query' => 'SELECT COUNT(*) FROM site_visits WHERE DATE(visited_at) = CURDATE()',
    ];
}

foreach ($metrics as &$metric) {
    if (isset($metric['permission']) && !can($metric['permission'])) {
        continue;
    }

    try {
        $metric['value'] = (int) db_fetch_value($metric['query']);
    } catch (Throwable) {
        $metric['value'] = 0;
    }
}
unset($metric);

$securityChecks = [
    ['label' => 'Secure session boot', 'status' => session_status() === PHP_SESSION_ACTIVE],
    ['label' => 'CSRF token ready', 'status' => csrf_token() !== ''],
    ['label' => 'Database configured', 'status' => config('database.database') === 'silkhea2_jlfc'],
    ['label' => 'RBAC loaded', 'status' => is_super_admin() || can('view_dashboard')],
];

$coachPreparationAlerts = [];
if ($canManageMatchPreparation() && user_club_id() !== null) {
    try {
        $coachPreparationAlerts = $fixturePreparationNotifications((int) user_club_id());
    } catch (Throwable) {
        $coachPreparationAlerts = [];
    }
}

require __DIR__ . '/app/includes/header.php';
require __DIR__ . '/app/includes/sidebar.php';
require __DIR__ . '/app/includes/topbar.php';
require __DIR__ . '/app/includes/flash.php';
?>
<section class="hero-banner mb-4">
    <div>
        <p class="eyebrow mb-2">League operations command centre</p>
        <h2>Welcome back, <?php echo e(explode(' ', $user['full_name'])[0] ?? 'Admin'); ?>.</h2>
    </div>
    <div class="hero-banner-meta">
        <span class="hero-pill"><i class="bi bi-flag"></i> <?php echo e(league_short_name()); ?></span>
        <span class="hero-pill"><i class="bi bi-building"></i> <?php echo e(organization_name()); ?></span>
        <?php if (can('manage_fixtures')): ?>
            <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/fixtures/export-pdf.php')); ?>"><i class="bi bi-file-earmark-pdf"></i> Download fixtures PDF</a>
        <?php endif; ?>
    </div>
</section>

<section class="row g-4 mb-4">
    <?php foreach ($metrics as $metric): ?>
        <?php if (isset($metric['permission']) && !can($metric['permission'])) {
            continue;
        } ?>
        <div class="col-12 col-sm-6 col-xl-3">
            <article class="metric-card h-100">
                <div class="metric-icon"><i class="bi <?php echo e($metric['icon']); ?>"></i></div>
                <span class="metric-label"><?php echo e($metric['label']); ?></span>
                <strong class="metric-value"><?php echo e((string) $metric['value']); ?></strong>
                <small class="text-muted">Live league data snapshot</small>
            </article>
        </div>
    <?php endforeach; ?>
</section>

<section class="row g-4">
    <div class="col-12 col-xl-8">
        <article class="panel-card h-100">
            <div class="panel-card-header">

                <article class="panel-card h-100">
                    <div class="panel-card-header">
                        <div>
                            <p class="eyebrow mb-1">QA signals</p>
                            <h3 class="h5 mb-0">System checks</h3>
                        </div>
                    </div>
                    <ul class="status-list mb-0">
                        <?php foreach ($securityChecks as $check): ?>
                            <li>
                                <span><?php echo e($check['label']); ?></span>
                                <span class="badge <?php echo $check['status'] ? 'badge-soft-success' : 'badge-soft-danger'; ?>">
                                    <?php echo $check['status'] ? 'Pass' : 'Review'; ?>
                                </span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </article>
            </div>
</section>

<?php if ($coachPreparationAlerts !== []): ?>
    <section class="panel-card mb-4">
        <div class="panel-card-header mb-3">
            <div>
                <p class="eyebrow mb-1">Coach alerts</p>
                <h3 class="h5 mb-0">Formation windows and upcoming fixtures</h3>
            </div>
            <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/modules/fixtures/preparation.php')); ?>">Open match prep</a>
        </div>
        <div class="row g-3">
            <?php foreach ($coachPreparationAlerts as $fixture): ?>
                <?php $windowState = $fixture['window_state'] ?? ['available' => false, 'message' => '']; ?>
                <div class="col-12 col-lg-6">
                    <div class="feature-tile align-items-start">
                        <i class="bi <?php echo ($windowState['available'] ?? false) ? 'bi-bell-fill' : 'bi-alarm'; ?>"></i>
                        <div>
                            <h4><?php echo e($fixture['home_club_name']); ?> vs <?php echo e($fixture['away_club_name']); ?></h4>
                            <p class="mb-2"><?php echo e($fixture['competition_name']); ?> &middot; <?php echo e(($fixture['match_date'] ?? 'TBD') . ' ' . ($fixture['match_time'] ?? '')); ?></p>
                            <p class="text-muted mb-2"><?php echo e((string) ($windowState['message'] ?? '')); ?></p>
                            <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/modules/fixtures/preparation.php?id=' . (int) $fixture['id'])); ?>">
                                <?php echo ($windowState['available'] ?? false) ? 'Set formation' : 'Review prep'; ?>
                            </a>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </section>
<?php endif; ?>

<?php if (can('manage_users') || can('manage_roles') || can('manage_seasons') || can('manage_competitions') || can('manage_clubs') || can('manage_club_staff') || can('manage_players') || can('manage_venues') || can('manage_referees') || can('manage_fixtures') || can('submit_results') || can('manage_table') || can('manage_statistics') || can('manage_discipline') || can('manage_protests') || can('manage_finance') || can('manage_awards') || can('manage_media') || can('manage_transfers') || can('view_reports') || can('manage_settings')): ?>
    <section class="panel-card mt-4">
        <div class="panel-card-header mb-3">
            <div>
                <p class="eyebrow mb-1">Admin shortcuts</p>
                <h3 class="h5 mb-0">Current management modules</h3>
            </div>
        </div>
        <div class="d-flex flex-wrap gap-2">
            <?php if (can('manage_users')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/users/index.php')); ?>"><i class="bi bi-people-fill"></i> Manage users</a>
            <?php endif; ?>
            <?php if (can('manage_roles')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/roles/index.php')); ?>"><i class="bi bi-shield-lock-fill"></i> Manage roles</a>
            <?php endif; ?>
            <?php if (can('manage_seasons')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/seasons/index.php')); ?>"><i class="bi bi-calendar-range-fill"></i> Manage seasons</a>
            <?php endif; ?>
            <?php if (can('manage_competitions')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/competitions/index.php')); ?>"><i class="bi bi-trophy-fill"></i> Manage competitions</a>
            <?php endif; ?>
            <?php if (can('manage_clubs')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/clubs/index.php')); ?>"><i class="bi bi-shield-fill-check"></i> Manage clubs</a>
            <?php endif; ?>
            <?php if (can('manage_club_staff')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/staff/index.php')); ?>"><i class="bi bi-person-badge-fill"></i> Manage club staff</a>
            <?php endif; ?>
            <?php if (can('manage_players')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/players/index.php')); ?>"><i class="bi bi-people-fill"></i> Manage players</a>
            <?php endif; ?>
            <?php if (can('manage_venues')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/venues/index.php')); ?>"><i class="bi bi-building-fill-check"></i> Manage venues</a>
            <?php endif; ?>
            <?php if (can('manage_referees')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/referees/index.php')); ?>"><i class="bi bi-whistle"></i> Manage referees</a>
            <?php endif; ?>
            <?php if (can('manage_fixtures')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/fixtures/index.php')); ?>"><i class="bi bi-calendar-event-fill"></i> Manage fixtures</a>
            <?php endif; ?>
            <?php if ($canManageMatchPreparation()): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/fixtures/preparation.php')); ?>"><i class="bi bi-diagram-3-fill"></i> Match prep</a>
            <?php endif; ?>
            <?php if (can('submit_results')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/matches/index.php')); ?>"><i class="bi bi-clipboard-data-fill"></i> Manage match results</a>
            <?php endif; ?>
            <?php if (can('manage_table')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/table/index.php')); ?>"><i class="bi bi-table"></i> Manage league table</a>
            <?php endif; ?>
            <?php if (can('manage_statistics')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/statistics/index.php')); ?>"><i class="bi bi-graph-up-arrow"></i> Manage statistics</a>
            <?php endif; ?>
            <?php if (can('manage_discipline')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/discipline/index.php')); ?>"><i class="bi bi-shield-exclamation"></i> Manage discipline</a>
            <?php endif; ?>
            <?php if (can('manage_protests')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/protests/index.php')); ?>"><i class="bi bi-megaphone-fill"></i> Manage protests</a>
            <?php endif; ?>
            <?php if (can('manage_finance')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/finance/index.php')); ?>"><i class="bi bi-cash-coin"></i> Manage finance</a>
            <?php endif; ?>
            <?php if (can('manage_awards')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/awards/index.php')); ?>"><i class="bi bi-trophy"></i> Manage awards</a>
            <?php endif; ?>
            <?php if (can('manage_media')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/media/index.php')); ?>"><i class="bi bi-camera-reels"></i> Manage media</a>
            <?php endif; ?>
            <?php if (can('manage_transfers')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/transfers/index.php')); ?>"><i class="bi bi-arrow-left-right"></i> Manage transfers</a>
            <?php endif; ?>
            <?php if (can('view_reports')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/reports/index.php')); ?>"><i class="bi bi-file-earmark-bar-graph"></i> View reports</a>
            <?php endif; ?>
            <?php if (is_super_admin()): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/analytics/index.php')); ?>"><i class="bi bi-activity"></i> Site analytics</a>
            <?php endif; ?>
            <?php if (can('manage_settings')): ?>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/settings/index.php')); ?>"><i class="bi bi-sliders"></i> Manage settings</a>
            <?php endif; ?>
        </div>
    </section>
<?php endif; ?>
<?php require __DIR__ . '/app/includes/footer.php'; ?>