<?php
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';

checkRole(['student', 'parent']);

$userId   = (int)$_SESSION['user_id'];
$userRole = $_SESSION['user_role'];

function getAccessibleStudentIds(PDO $pdo, int $userId, string $role): array {
    if ($role === 'student') {
        $s = $pdo->prepare("SELECT id FROM students WHERE user_id=? LIMIT 1");
        $s->execute([$userId]);
        $row = $s->fetch();
        return $row ? [(int)$row['id']] : [];
    }
    $s = $pdo->prepare("SELECT student_id FROM parent_students WHERE user_id=?");
    $s->execute([$userId]);
    return array_column($s->fetchAll(), 'student_id');
}

$studentIds = getAccessibleStudentIds($pdo, $userId, $userRole);

$nbGrades   = 0;
$nbPayments = 0;
$totalPaid  = 0;
$recentGrades   = [];
$recentPayments = [];
$students   = [];

if (!empty($studentIds)) {
    $in = implode(',', array_fill(0, count($studentIds), '?'));

    $stmt = $pdo->prepare("SELECT s.*, c.name AS class_name, sc.name AS school_name
        FROM students s
        LEFT JOIN classes c ON s.class_id=c.id
        LEFT JOIN schools sc ON s.school_id=sc.id
        WHERE s.id IN ($in) ORDER BY s.last_name, s.first_name");
    $stmt->execute($studentIds);
    $students = $stmt->fetchAll();

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM grades WHERE student_id IN ($in)");
    $stmt->execute($studentIds);
    $nbGrades = (int)$stmt->fetchColumn();

    $stmt = $pdo->prepare("SELECT COUNT(*), COALESCE(SUM(amount),0) FROM payments WHERE student_id IN ($in)");
    $stmt->execute($studentIds);
    [$nbPayments, $totalPaid] = $stmt->fetch(\PDO::FETCH_NUM);

    $stmt = $pdo->prepare("SELECT * FROM v_student_grades WHERE student_id IN ($in) ORDER BY grade_date DESC LIMIT 5");
    $stmt->execute($studentIds);
    $recentGrades = $stmt->fetchAll();

    $stmt = $pdo->prepare("
        SELECT p.*, CONCAT(s.last_name,' ',s.first_name) AS student_name
        FROM payments p JOIN students s ON p.student_id=s.id
        WHERE p.student_id IN ($in)
        ORDER BY p.payment_date DESC LIMIT 5
    ");
    $stmt->execute($studentIds);
    $recentPayments = $stmt->fetchAll();
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mon espace - Nukunu Mofiala</title>
    <link rel="stylesheet" href="<?= BASE_URL ?>assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .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-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 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;
        }
        .quick-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 1.2rem;
            margin-bottom: 2.5rem;
        }
        .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;
        }
        .dash-grid-2 {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        @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/portal_sidebar.php'; ?>
    <div class="main-content">
        <div class="header-bar">
            <h1><i class="fas fa-tachometer-alt"></i> Tableau de bord</h1>
            <div class="user-info">
                <span><i class="fas fa-user-circle"></i> <?= e($_SESSION['user_name']) ?></span>
            </div>
        </div>
        <?= showFlash() ?>

        <?php if (empty($studentIds)): ?>
        <div class="card" style="text-align:center;padding:3rem;color:#718096;">
            <i class="fas fa-user-slash" style="font-size:3rem;margin-bottom:1rem;display:block;"></i>
            <p>Aucun profil élève n'est lié à votre compte.</p>
            <p style="margin-top:.5rem;">Contactez l'administration pour faire le lien.</p>
        </div>
        <?php else: ?>

        <!-- Profil(s) élève(s) -->
        <?php foreach ($students as $st): ?>
        <div class="card" style="display:flex;align-items:center;gap:1.5rem;padding:1.25rem 1.5rem;margin-bottom:1rem;">
            <div class="sidebar-user-avatar" style="width:56px;height:56px;font-size:1.5rem;flex-shrink:0;">
                <?= strtoupper(mb_substr($st['first_name'], 0, 1)) ?>
            </div>
            <div>
                <div style="font-size:1.1rem;font-weight:700;color:#2d3748;"><?= e($st['last_name'].' '.$st['first_name']) ?></div>
                <div style="color:#718096;font-size:.9rem;">
                    <?= e($st['class_name'] ?? 'Aucune classe') ?> &bull; <?= e($st['school_name'] ?? '') ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>

        <!-- Stats -->
        <div class="dash-stats">
            <div class="dash-stat">
                <div class="dash-stat-icon" style="background:linear-gradient(135deg,#667eea,#764ba2);">
                    <i class="fas fa-star-half-alt"></i>
                </div>
                <div class="dash-stat-info">
                    <h3><?= $nbGrades ?></h3>
                    <p>Notes</p>
                </div>
            </div>
            <div class="dash-stat">
                <div class="dash-stat-icon" style="background:linear-gradient(135deg,#48bb78,#38a169);">
                    <i class="fas fa-money-bill-wave"></i>
                </div>
                <div class="dash-stat-info">
                    <h3><?= $nbPayments ?></h3>
                    <p>Paiements</p>
                </div>
            </div>
            <div class="dash-stat">
                <div class="dash-stat-icon" style="background:linear-gradient(135deg,#ed8936,#dd6b20);">
                    <i class="fas fa-coins"></i>
                </div>
                <div class="dash-stat-info">
                    <h3><?= formatAmount($totalPaid) ?></h3>
                    <p>Total versé</p>
                </div>
            </div>
        </div>

        <!-- Actions rapides portail -->
        <div class="quick-grid">
            <a href="<?= BASE_URL ?>portal/grades.php" class="quick-card">
                <div class="quick-card-icon" style="background:linear-gradient(135deg,#667eea,#764ba2);">
                    <i class="fas fa-star-half-alt"></i>
                </div>
                <span class="quick-card-label">Consulter les notes</span>
                <span class="quick-card-desc">Voir le détail des notes</span>
            </a>
            <a href="<?= BASE_URL ?>portal/payments.php" class="quick-card">
                <div class="quick-card-icon" style="background:linear-gradient(135deg,#48bb78,#38a169);">
                    <i class="fas fa-money-bill-wave"></i>
                </div>
                <span class="quick-card-label">Paiements</span>
                <span class="quick-card-desc">Historique des paiements</span>
            </a>
            <a href="<?= BASE_URL ?>portal/profile.php" class="quick-card">
                <div class="quick-card-icon" style="background:linear-gradient(135deg,#9f7aea,#805ad5);">
                    <i class="fas fa-user-circle"></i>
                </div>
                <span class="quick-card-label">Mon profil</span>
                <span class="quick-card-desc">Modifier mes informations</span>
            </a>
            <?php if ($userRole === 'parent'): ?>
            <a href="<?= BASE_URL ?>portal/children.php" class="quick-card">
                <div class="quick-card-icon" style="background:linear-gradient(135deg,#ed8936,#dd6b20);">
                    <i class="fas fa-users"></i>
                </div>
                <span class="quick-card-label">Mes enfants</span>
                <span class="quick-card-desc">Gérer les profils liés</span>
            </a>
            <?php endif; ?>
        </div>

        <!-- Tableaux récents -->
        <div class="dash-grid-2">
            <div class="card">
                <div class="card-header">
                    <span class="card-title"><i class="fas fa-star-half-alt"></i> Dernières notes</span>
                    <a href="<?= BASE_URL ?>portal/grades.php" class="btn-action btn-view">Voir tout</a>
                </div>
                <div class="data-table-wrapper">
                <table class="data-table">
                    <thead><tr><?php if ($userRole==='parent'): ?><th>Élève</th><?php endif; ?><th>Matière</th><th>Note</th><th>Période</th></tr></thead>
                    <tbody>
                    <?php foreach ($recentGrades as $g):
                        $scoreColor = ($g['score']/$g['score_max']*20) >= 10 ? '#22543d' : '#c53030';
                    ?>
                    <tr>
                        <?php if ($userRole==='parent'): ?><td><?= e($g['student_name']) ?></td><?php endif; ?>
                        <td><?= e($g['subject_name']) ?></td>
                        <td><strong style="color:<?= $scoreColor ?>"><?= e($g['score']) ?>/<?= e($g['score_max']) ?></strong></td>
                        <td><?= e($g['period_name']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($recentGrades)): ?>
                    <tr><td colspan="<?= $userRole === 'parent' ? 4 : 3 ?>" style="text-align:center;color:#999;">Aucune note</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <span class="card-title"><i class="fas fa-money-bill-wave"></i> Derniers paiements</span>
                    <a href="<?= BASE_URL ?>portal/payments.php" class="btn-action btn-view">Voir tout</a>
                </div>
                <div class="data-table-wrapper">
                <table class="data-table">
                    <thead><tr><?php if ($userRole==='parent'): ?><th>Élève</th><?php endif; ?><th>Montant</th><th>Date</th><th>Méthode</th></tr></thead>
                    <tbody>
                    <?php foreach ($recentPayments as $p): ?>
                    <tr>
                        <?php if ($userRole==='parent'): ?><td><?= e($p['student_name']) ?></td><?php endif; ?>
                        <td><strong><?= formatAmount($p['amount']) ?></strong></td>
                        <td><?= formatDate($p['payment_date']) ?></td>
                        <td><?= e($p['method']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($recentPayments)): ?>
                    <tr><td colspan="<?= $userRole === 'parent' ? 4 : 3 ?>" style="text-align:center;color:#999;">Aucun paiement</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>
</body>
</html>
