<?php
/**
 * Portail — Vue parent : mes enfants et leurs données
 */
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';

checkRole(['parent']);

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

// Récupérer les enfants du parent
$stmt = $pdo->prepare("
    SELECT s.*, c.name AS class_name, sc.name AS school_name
    FROM parent_students ps
    JOIN students s ON ps.student_id=s.id
    LEFT JOIN classes c ON s.class_id=c.id
    LEFT JOIN schools sc ON s.school_id=sc.id
    WHERE ps.user_id=?
    ORDER BY s.last_name, s.first_name
");
$stmt->execute([$userId]);
$children = $stmt->fetchAll();
$childIds = array_column($children, 'id');

// Enfant sélectionné
$selectedId = isset($_GET['student_id']) ? (int)$_GET['student_id'] : ($childIds[0] ?? 0);
if ($selectedId && !in_array($selectedId, $childIds)) {
    flashMessage('error', 'Accès non autorisé.'); header('Location: dashboard.php'); exit;
}

// Données de l'enfant sélectionné
$selectedChild = null;
$childGrades   = [];
$childPayments = [];
$bulletinData  = [];
$generalAvg    = null;
$periods       = [];
$filterPeriod  = isset($_GET['period_id']) ? (int)$_GET['period_id'] : 0;

if ($selectedId) {
    foreach ($children as $ch) {
        if ($ch['id'] == $selectedId) { $selectedChild = $ch; break; }
    }

    // Périodes disponibles
    $stmt = $pdo->prepare("SELECT DISTINCT ap.* FROM academic_periods ap
        JOIN grades g ON ap.trimestre=g.trimestre AND ap.academic_year=g.academic_year AND ap.school_id=COALESCE(g.school_id,0) WHERE g.student_id=?
        ORDER BY ap.academic_year DESC, ap.trimestre");
    $stmt->execute([$selectedId]);
    $periods = $stmt->fetchAll();
    if (!$filterPeriod && !empty($periods)) $filterPeriod = (int)$periods[0]['id'];

    // Notes via vue
    if ($filterPeriod) {
        $stmt = $pdo->prepare("SELECT * FROM v_student_grades WHERE student_id=? AND period_id=? ORDER BY subject_name");
        $stmt->execute([$selectedId, $filterPeriod]);
        $childGrades = $stmt->fetchAll();

        // Bulletin via vue
        $stmt = $pdo->prepare("SELECT subject_name, subject_coefficient AS coefficient, AVG(score/score_max*20) AS avg_score
            FROM v_student_grades WHERE student_id=? AND period_id=?
            GROUP BY subject_name, subject_coefficient ORDER BY subject_name");
        $stmt->execute([$selectedId, $filterPeriod]);
        $bulletinData = $stmt->fetchAll();

        if (!empty($bulletinData)) {
            $stmt = $pdo->prepare("SELECT weighted_average FROM v_student_period_averages WHERE student_id=? AND period_id=?");
            $stmt->execute([$selectedId, $filterPeriod]); $bRow = $stmt->fetch();
            $generalAvg = $bRow ? round((float)$bRow['weighted_average'], 2) : 0;
        }
    }

    // Paiements
    $stmt = $pdo->prepare("SELECT * FROM payments WHERE student_id=? ORDER BY payment_date DESC");
    $stmt->execute([$selectedId]);
    $childPayments = $stmt->fetchAll();
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mes enfants - 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>
        .child-tab { display:inline-flex;align-items:center;gap:.5rem;padding:.6rem 1.2rem;border-radius:8px;text-decoration:none;color:#4a5568;background:#f7fafc;border:2px solid #e2e8f0;font-weight:500;transition:all .2s; }
        .child-tab:hover, .child-tab.active { background:#667eea;color:white;border-color:#667eea; }
        @media print { .sidebar,.header-bar,.child-selector,.no-print{display:none!important;} .main-content{margin-left:0!important;} }
    </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-child"></i> Mes enfants</h1>
            <?php if ($selectedId && $filterPeriod): ?>
            <button onclick="window.print()" class="btn-action btn-view no-print">
                <i class="fas fa-print"></i> Imprimer bulletin
            </button>
            <?php endif; ?>
        </div>
        <?= showFlash() ?>

        <?php if (empty($children)): ?>
        <div class="card" style="text-align:center;padding:3rem;color:#718096;">
            <i class="fas fa-child" style="font-size:3rem;margin-bottom:1rem;display:block;opacity:.4;"></i>
            <p>Aucun enfant lié à votre compte.</p>
            <p style="margin-top:.5rem;">Contactez l'administration pour associer un enfant à votre compte.</p>
        </div>
        <?php else: ?>

        <!-- Sélecteur d'enfants -->
        <div class="child-selector" style="display:flex;gap:.75rem;flex-wrap:wrap;margin-bottom:1.5rem;">
            <?php foreach ($children as $ch): ?>
            <a href="?student_id=<?= $ch['id'] ?>" class="child-tab <?= $selectedId == $ch['id'] ? 'active' : '' ?>">
                <div style="width:28px;height:28px;border-radius:50%;background:<?= $selectedId == $ch['id'] ? 'rgba(255,255,255,.3)' : '#e2e8f0' ?>;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:.85rem;">
                    <?= strtoupper(mb_substr($ch['first_name'], 0, 1)) ?>
                </div>
                <div>
                    <div style="font-size:.95rem;"><?= e($ch['last_name'].' '.$ch['first_name']) ?></div>
                    <div style="font-size:.75rem;opacity:.7;"><?= e($ch['class_name'] ?? '-') ?></div>
                </div>
            </a>
            <?php endforeach; ?>
        </div>

        <?php if ($selectedChild): ?>
        <!-- Fiche enfant -->
        <div class="card" style="display:flex;align-items:center;gap:1.5rem;padding:1.25rem 1.5rem;margin-bottom:1.5rem;">
            <div class="sidebar-user-avatar" style="width:56px;height:56px;font-size:1.6rem;flex-shrink:0;">
                <?= strtoupper(mb_substr($selectedChild['first_name'], 0, 1)) ?>
            </div>
            <div style="flex:1;">
                <div style="font-size:1.15rem;font-weight:700;color:#2d3748;"><?= e($selectedChild['last_name'].' '.$selectedChild['first_name']) ?></div>
                <div style="color:#718096;font-size:.9rem;margin-top:.2rem;">
                    <i class="fas fa-users"></i> <?= e($selectedChild['class_name'] ?? '-') ?>
                    &nbsp;&bull;&nbsp;
                    <i class="fas fa-school"></i> <?= e($selectedChild['school_name'] ?? '-') ?>
                    <?php if ($selectedChild['birth_date']): ?>
                    &nbsp;&bull;&nbsp;
                    <i class="fas fa-birthday-cake"></i> <?= formatDate($selectedChild['birth_date']) ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Onglet notes + paiements -->
        <div class="tab-nav" style="margin-bottom:1rem;">
            <a href="?student_id=<?= $selectedId ?>&tab=grades<?= $filterPeriod ? '&period_id='.$filterPeriod : '' ?>" class="tab-btn <?= ($_GET['tab'] ?? 'grades') !== 'payments' ? 'active' : '' ?>">
                <i class="fas fa-star-half-alt"></i> Notes
            </a>
            <a href="?student_id=<?= $selectedId ?>&tab=payments" class="tab-btn <?= ($_GET['tab'] ?? '') === 'payments' ? 'active' : '' ?>">
                <i class="fas fa-money-bill-wave"></i> Paiements
            </a>
        </div>

        <?php if (($_GET['tab'] ?? 'grades') !== 'payments'): ?>
        <!-- Notes -->
        <?php if (!empty($periods)): ?>
        <div class="card no-print" style="margin-bottom:1rem;">
            <form method="GET" style="display:flex;gap:1rem;align-items:flex-end;">
                <input type="hidden" name="student_id" value="<?= $selectedId ?>">
                <input type="hidden" name="tab" value="grades">
                <div class="form-group" style="margin:0;min-width:220px;">
                    <label>Période</label>
                    <select name="period_id" onchange="this.form.submit()">
                        <?php foreach ($periods as $p): ?>
                        <option value="<?= $p['id'] ?>" <?= $filterPeriod == $p['id'] ? 'selected' : '' ?>><?= e($p['name'].($p['academic_year'] ? ' '.$p['academic_year'] : '')) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </form>
        </div>

        <?php if (!empty($bulletinData)): ?>
        <div class="card" style="border-left:4px solid #667eea;margin-bottom:1.5rem;">
            <div class="card-header">
                <span class="card-title"><i class="fas fa-file-alt"></i> Bulletin — <?= e($periods[array_search($filterPeriod, array_column($periods,'id'))]['name'] ?? '') ?></span>
                <?php if (!is_null($generalAvg)): ?>
                <span style="font-size:1.2rem;font-weight:700;color:<?= $generalAvg >= 10 ? '#22543d' : '#c53030' ?>">
                    Moy. générale : <?= $generalAvg ?>/20
                </span>
                <?php endif; ?>
            </div>
            <div class="data-table-wrapper">
            <table class="data-table">
                <thead><tr><th>Matière</th><th>Coeff.</th><th>Moyenne /20</th><th>Appréciation</th></tr></thead>
                <tbody>
                <?php foreach ($bulletinData as $b):
                    $avg = round($b['avg_score'] ?? 0, 2);
                    $col = $avg >= 10 ? '#22543d' : '#c53030';
                    $mention = $avg >= 16 ? 'Très Bien' : ($avg >= 14 ? 'Bien' : ($avg >= 12 ? 'Assez Bien' : ($avg >= 10 ? 'Passable' : 'Insuffisant')));
                ?>
                <tr>
                    <td><?= e($b['subject_name']) ?></td>
                    <td><?= e($b['coefficient']) ?></td>
                    <td><strong style="color:<?= $col ?>"><?= $avg ?></strong></td>
                    <td style="color:<?= $avg >= 10 ? '#22543d' : '#c53030' ?>;"><?= $mention ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr style="background:#f7fafc;font-weight:700;">
                        <td colspan="2">Moyenne générale</td>
                        <td style="color:<?= $generalAvg >= 10 ? '#22543d' : '#c53030' ?>;font-size:1.1rem;"><?= $generalAvg ?>/20</td>
                        <td><?= $generalAvg >= 16 ? 'Très Bien' : ($generalAvg >= 14 ? 'Bien' : ($generalAvg >= 12 ? 'Assez Bien' : ($generalAvg >= 10 ? 'Passable' : 'Insuffisant'))) ?></td>
                    </tr>
                </tfoot>
            </table>
                </div>
        </div>
        <?php endif; ?>

        <?php else: ?>
        <div class="card" style="text-align:center;padding:2rem;color:#718096;">
            <i class="fas fa-inbox" style="font-size:2rem;margin-bottom:.5rem;display:block;"></i>
            <p>Aucune note disponible pour le moment.</p>
        </div>
        <?php endif; ?>

        <?php else: ?>
        <!-- Paiements -->
        <div class="card">
            <div class="data-table-wrapper">
            <table class="data-table">
                <thead><tr><th>Montant</th><th>Date</th><th>Méthode</th><th>Référence</th><th>Description</th></tr></thead>
                <tbody>
                <?php foreach ($childPayments as $p): ?>
                <tr>
                    <td><strong style="color:#22543d;"><?= formatAmount($p['amount']) ?></strong></td>
                    <td><?= formatDate($p['payment_date']) ?></td>
                    <td><?= e($p['method']) ?></td>
                    <td><code style="font-size:.85rem;color:#718096;"><?= e($p['reference_code'] ?? '-') ?></code></td>
                    <td style="color:#718096;"><?= e($p['description'] ?? '-') ?></td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($childPayments)): ?>
                <tr><td colspan="5" style="text-align:center;color:#999;padding:2rem;">Aucun paiement</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
                </div>
        </div>
        <?php endif; ?>

        <?php endif; ?>
        <?php endif; ?>
    </div>
</div>
</body>
</html>
