<?php
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';
header('Content-Type: text/html; charset=utf-8');

$schoolFilter = currentSchoolId();

// ── Statistiques ──────────────────────────────────────────────────────────────
if ($schoolFilter) {
    $statsStmt = $pdo->prepare("
        SELECT
            (SELECT COUNT(*) FROM students  WHERE school_id = :s1) AS students,
            (SELECT COUNT(*) FROM teachers  WHERE school_id = :s2) AS teachers,
            (SELECT COUNT(*) FROM classes) AS classes,
            (SELECT COALESCE(SUM(amount),0) FROM payments WHERE school_id = :s4) AS payments
    ");
    $statsStmt->execute([':s1' => $schoolFilter, ':s2' => $schoolFilter, ':s4' => $schoolFilter]);
    $stats = $statsStmt->fetch();
    $stats['schools'] = 1;
    $snStmt = $pdo->prepare("SELECT name, logo FROM schools WHERE id=?");
    $snStmt->execute([$schoolFilter]);
    $sRow = $snStmt->fetch();
    $stats['school_name'] = $sRow['name'] ?: '';
    $stats['school_logo'] = $sRow['logo'] ?? null;
} else {
    $stats = $pdo->query("
        SELECT
            (SELECT COUNT(*) FROM schools)  AS schools,
            (SELECT COUNT(*) FROM students) AS students,
            (SELECT COUNT(*) FROM teachers) AS teachers,
            (SELECT COUNT(*) FROM classes)  AS classes,
            (SELECT COALESCE(SUM(amount),0) FROM payments) AS payments
    ")->fetch();
    $stats['school_name'] = 'Toutes les écoles';
    $stats['school_logo'] = null;
}

$role = $_SESSION['user_role'];
$isSuper  = $role === 'super_admin';
$isAdmin  = $role === 'school_admin';
$isTeacher= $role === 'teacher';
$isAcct   = $role === 'accountant';

// ── Définition des groupes et boutons ─────────────────────────────────────────
$groups = [];

// Pédagogie
$pedagogie = ['icon'=>'book-open','label'=>'Pédagogie'];
$pedagogie['items'] = [];
if (!$isAcct) {
    $pedagogie['items'][] = ['page'=>'grades.php',          'icon'=>'pen-alt','label'=>'Saisie notes','desc'=>'Noter les élèves'];
    $pedagogie['items'][] = ['page'=>'grade_verification.php','icon'=>'check-double','label'=>'Vérification','desc'=>'Vérifier les notes'];
    $pedagogie['items'][] = ['page'=>'bulletin.php',        'icon'=>'file-alt','label'=>'Bulletins','desc'=>'Générer les bulletins'];
    $pedagogie['items'][] = ['page'=>'duplicata.php',       'icon'=>'copy','label'=>'Duplicata','desc'=>'Duplicata bulletins'];
    $pedagogie['items'][] = ['page'=>'class_stats.php',     'icon'=>'chart-bar','label'=>'Stats classe','desc'=>'Statistiques par classe'];
}
if ($isSuper || $isAdmin) {
    $pedagogie['items'][] = ['page'=>'attestation.php',     'icon'=>'certificate','label'=>'Attestation','desc'=>'Attestation scolaire'];
    $pedagogie['items'][] = ['page'=>'promotion.php',       'icon'=>'arrows-alt','label'=>'Reclassement','desc'=>'Promouvoir des élèves'];
}
$groups[] = $pedagogie;

// Établissement
$etablissement = ['icon'=>'school','label'=>'Établissement'];
$etablissement['items'] = [];
if ($isSuper) {
    $etablissement['items'][] = ['page'=>'schools.php',     'icon'=>'school','label'=>'Écoles','desc'=>'Gérer les écoles'];
}
if ($isSuper || $isAdmin) {
    $etablissement['items'][] = ['page'=>'directors.php',   'icon'=>'user-tie','label'=>'Directeurs','desc'=>'Gérer les directeurs'];
}
if (!$isAcct) {
    $etablissement['items'][] = ['page'=>'classes.php',     'icon'=>'users','label'=>'Classes','desc'=>'Gérer les classes'];
}
$etablissement['items'][] = ['page'=>'students.php',        'icon'=>'user-graduate','label'=>'Élèves','desc'=>'Gérer les élèves'];
if ($isSuper || $isAdmin) {
    $etablissement['items'][] = ['page'=>'teachers.php',    'icon'=>'chalkboard-teacher','label'=>'Enseignants','desc'=>'Gérer les enseignants'];
    $etablissement['items'][] = ['page'=>'id_cards.php',    'icon'=>'id-card','label'=>'Cartes identité','desc'=>'Cartes d\'identité'];
}
$groups[] = $etablissement;

// Finance
if ($isSuper || $isAdmin || $isAcct) {
    $finance = ['icon'=>'money-bill-wave','label'=>'Finance'];
    $finance['items'] = [];
    if (!$isAcct) {
        $finance['items'][] = ['page'=>'payments.php',      'icon'=>'list','label'=>'Paiements','desc'=>'Enregistrer paiements'];
    }
    if ($isSuper || $isAcct) {
        $finance['items'][] = ['page'=>'receipts.php',      'icon'=>'receipt','label'=>'Reçus','desc'=>'Générer des reçus'];
    }
    $finance['items'][] = ['page'=>'expenses.php',          'icon'=>'shopping-cart','label'=>'Dépenses','desc'=>'Gérer dépenses'];
    $finance['items'][] = ['page'=>'payment_history.php',   'icon'=>'history','label'=>'Historique','desc'=>'Historique paiements'];
    $finance['items'][] = ['page'=>'fees.php',              'icon'=>'graduation-cap','label'=>'Scolarité','desc'=>'Frais de scolarité'];
    $finance['items'][] = ['page'=>'recettes.php',          'icon'=>'chart-line','label'=>'Recettes','desc'=>'Rapport recettes'];
    $groups[] = $finance;
}

// Administration
if ($isSuper || $isAdmin) {
    $adminGroup = ['icon'=>'shield-alt','label'=>'Administration'];
    $adminGroup['items'] = [];
    $adminGroup['items'][] = ['page'=>'users.php',          'icon'=>'user-shield','label'=>'Utilisateurs','desc'=>'Gérer utilisateurs'];
    if ($isSuper) {
        $adminGroup['items'][] = ['page'=>'user_photos.php','icon'=>'camera','label'=>'Photos passeport','desc'=>'Photos utilisateurs'];
    }
    if ($isSuper) {
        $adminGroup['items'][] = ['page'=>'permissions.php','icon'=>'shield-alt','label'=>'Droits & Rôles','desc'=>'Permissions'];
        $adminGroup['items'][] = ['page'=>'academic_years.php','icon'=>'calendar','label'=>'Années scolaires','desc'=>'Gérer années'];
        $adminGroup['items'][] = ['page'=>'grading_periods.php','icon'=>'calendar-alt','label'=>'Périodes saisie','desc'=>'Périodes de notes'];
    }
    if ($isSuper) {
        $adminGroup['items'][] = ['page'=>'report_templates.php','icon'=>'cog','label'=>'Modèles bulletins','desc'=>'Configurer bulletins'];
    }
    if ($isSuper) {
        $adminGroup['items'][] = ['page'=>'settings.php',   'icon'=>'cogs','label'=>'Paramètres','desc'=>'Configuration'];
    }
    $groups[] = $adminGroup;
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tableau de bord - Nukunu Mofiala</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* ── Quick Action Cards ────────────────────────────────────────────── */
        .quick-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
            gap: 1.2rem;
            margin-bottom: 2.5rem;
        }

        .group-section {
            margin-bottom: 2.5rem;
        }

        .group-header {
            display: flex;
            align-items: center;
            gap: .6rem;
            margin-bottom: 1.2rem;
            padding-bottom: .6rem;
            border-bottom: 2px solid #e2e8f0;
        }

        .group-header i {
            font-size: 1.2rem;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
            color: white;
        }

        .group-header h2 {
            font-size: 1.05rem;
            font-weight: 700;
            color: #2d3748;
            margin: 0;
            text-transform: uppercase;
            letter-spacing: .03em;
        }

        .quick-card {
            background: white;
            border-radius: 14px;
            padding: 1.4rem 1.2rem;
            text-decoration: none;
            color: #2d3748;
            border: 1px solid #eef2f6;
            transition: all .25s cubic-bezier(.4,0,.2,1);
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            gap: .5rem;
            position: relative;
            overflow: hidden;
        }

        .quick-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: #667eea;
            opacity: 0;
            transition: opacity .25s;
        }

        .quick-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 12px 30px rgba(0,0,0,.1);
            border-color: transparent;
        }

        .quick-card:hover::before {
            opacity: 1;
        }

        .quick-card-icon {
            font-size: 1.6rem;
            width: 44px;
            height: 44px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 12px;
            color: white;
            flex-shrink: 0;
        }

        .quick-card-label {
            font-weight: 600;
            font-size: .95rem;
            line-height: 1.3;
            margin-top: .2rem;
        }

        .quick-card-desc {
            font-size: .78rem;
            color: #718096;
            line-height: 1.3;
        }

        /* ── En-tête du dashboard ──────────────────────────────────────────── */
        .dash-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            flex-wrap: wrap;
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .dash-welcome h1 {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1a202c;
            margin: 0 0 .25rem;
        }

        .dash-welcome p {
            color: #718096;
            font-size: .95rem;
            margin: 0;
        }

        .dash-school-badge {
            display: flex;
            align-items: center;
            gap: .6rem;
            background: white;
            padding: .5rem 1.2rem .5rem .8rem;
            border-radius: 40px;
            border: 1px solid #e2e8f0;
            font-size: .85rem;
            font-weight: 500;
            color: #4a5568;
            box-shadow: 0 1px 4px rgba(0,0,0,.04);
        }

        .dash-school-badge i {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: .9rem;
        }

        /* ── Stats compactes ────────────────────────────────────────────────── */
        .dash-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 1rem;
            margin-bottom: 2.5rem;
        }

        .dash-stat {
            background: white;
            border-radius: 12px;
            padding: 1rem 1.2rem;
            display: flex;
            align-items: center;
            gap: 1rem;
            border: 1px solid #eef2f6;
        }

        .dash-stat-icon {
            width: 42px;
            height: 42px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
            color: white;
            flex-shrink: 0;
        }

        .dash-stat-info h3 {
            font-size: 1.2rem;
            font-weight: 700;
            color: #1a202c;
            margin: 0;
            line-height: 1.2;
        }

        .dash-stat-info p {
            font-size: .78rem;
            color: #718096;
            margin: 0;
            text-transform: uppercase;
            letter-spacing: .03em;
        }

        /* ── Grille 2 colonnes sous-section ─────────────────────────────────── */
        .dash-grid-2 {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .dash-avatar {
            width: 52px; height: 52px;
            border-radius: 50%;
            object-fit: cover;
            flex-shrink: 0;
            border: 2px solid #e2e8f0;
            background: linear-gradient(135deg,#667eea,#764ba2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 1.2rem;
            color: white;
        }

        @media (max-width: 900px) {
            .dash-grid-2 { grid-template-columns: 1fr; }
        }

        @media (max-width: 700px) {
            .quick-grid { grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); }
        }
    </style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-tachometer-alt"></i> Tableau de bord'; include '../includes/topbar.php'; ?>

        <?= showFlash() ?>

        <!-- En-tête -->
        <div class="dash-header">
            <div class="dash-welcome" style="display:flex;align-items:center;gap:1rem;">
                <?= userPhotoImg($_SESSION['user_photo'] ?? null, $_SESSION['user_name'] ?? 'U', 'dash-avatar') ?>
                <div>
                    <h1>Bonjour, <?= e(explode(' ', $_SESSION['user_name'])[0]) ?> 👋</h1>
                    <p>Bienvenue sur votre tableau de bord — accédez rapidement à tous les modules.</p>
                </div>
            </div>
            <div class="dash-school-badge">
                <?php if (!empty($stats['school_logo'])): ?>
                <img src="<?= BASE_URL ?>uploads/logos/<?= rawurlencode($stats['school_logo']) ?>" alt="Logo" style="width:32px;height:32px;object-fit:contain;border-radius:6px;background:white;padding:2px;">
                <?php else: ?>
                <i class="fas fa-school"></i>
                <?php endif; ?>
                <span><?= e($stats['school_name']) ?></span>
            </div>
        </div>

        <!-- Statistiques -->
        <div class="dash-stats">
            <?php if (!$schoolFilter): ?>
            <div class="dash-stat">
                <div class="dash-stat-icon" style="background:linear-gradient(135deg,#667eea,#764ba2);">
                    <i class="fas fa-school"></i>
                </div>
                <div class="dash-stat-info">
                    <h3><?= (int)$stats['schools'] ?></h3>
                    <p>Écoles</p>
                </div>
            </div>
            <?php endif; ?>
            <div class="dash-stat">
                <div class="dash-stat-icon" style="background:linear-gradient(135deg,#48bb78,#38a169);">
                    <i class="fas fa-user-graduate"></i>
                </div>
                <div class="dash-stat-info">
                    <h3><?= (int)$stats['students'] ?></h3>
                    <p>Élèves</p>
                </div>
            </div>
            <div class="dash-stat">
                <div class="dash-stat-icon" style="background:linear-gradient(135deg,#ed8936,#dd6b20);">
                    <i class="fas fa-chalkboard-teacher"></i>
                </div>
                <div class="dash-stat-info">
                    <h3><?= (int)$stats['teachers'] ?></h3>
                    <p>Enseignants</p>
                </div>
            </div>
            <div class="dash-stat">
                <div class="dash-stat-icon" style="background:linear-gradient(135deg,#9f7aea,#805ad5);">
                    <i class="fas fa-users"></i>
                </div>
                <div class="dash-stat-info">
                    <h3><?= (int)$stats['classes'] ?></h3>
                    <p>Classes</p>
                </div>
            </div>
            <?php if (!$isTeacher && !$isAcct): ?>
            <div class="dash-stat">
                <div class="dash-stat-icon" style="background:linear-gradient(135deg,#38b2ac,#319795);">
                    <i class="fas fa-money-bill-wave"></i>
                </div>
                <div class="dash-stat-info">
                    <h3><?= formatAmount($stats['payments']) ?></h3>
                    <p>Recettes</p>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Groupes d'actions rapides -->
        <?php foreach ($groups as $group): ?>
        <div class="group-section">
            <div class="group-header">
                <i class="fas fa-<?= $group['icon'] ?>" style="background:linear-gradient(135deg,#667eea,#764ba2);"></i>
                <h2><?= $group['label'] ?></h2>
            </div>
            <div class="quick-grid">
                <?php foreach ($group['items'] as $item): ?>
                <a href="<?= $item['page'] ?>" class="quick-card">
                    <div class="quick-card-icon" style="background:linear-gradient(135deg,#667eea,#764ba2);">
                        <i class="fas fa-<?= $item['icon'] ?>"></i>
                    </div>
                    <span class="quick-card-label"><?= $item['label'] ?></span>
                    <span class="quick-card-desc"><?= $item['desc'] ?></span>
                </a>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endforeach; ?>

    </div>
</div>
</body>
</html>
