<?php
/**
 * Portail — Historique des paiements (élève / parent)
 */
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);

$payments   = [];
$totalPaid  = 0;
$studentsInfo = [];

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

    // Infos élèves
    $stmt = $pdo->prepare("SELECT s.id, CONCAT(s.last_name,' ',s.first_name) AS full_name, c.name AS class_name
        FROM students s LEFT JOIN classes c ON s.class_id=c.id WHERE s.id IN ($in) ORDER BY s.last_name, s.first_name");
    $stmt->execute($studentIds);
    $studentsInfo = $stmt->fetchAll();

    // Filtre élève (parent multi-enfants)
    $filterStudent = isset($_GET['student_id']) ? (int)$_GET['student_id'] : 0;
    if ($filterStudent && !in_array($filterStudent, $studentIds)) {
        flashMessage('error', 'Accès non autorisé.'); header('Location: dashboard.php'); exit;
    }
    $activeIds = $filterStudent ? [$filterStudent] : $studentIds;
    $inActive  = implode(',', array_fill(0, count($activeIds), '?'));

    // Total payé
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM payments WHERE student_id IN ($inActive)");
    $stmt->execute($activeIds);
    $totalPaid = (float)$stmt->fetchColumn();

    // Liste paiements
    $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 ($inActive)
        ORDER BY p.payment_date DESC
    ");
    $stmt->execute($activeIds);
    $payments = $stmt->fetchAll();
} else {
    $filterStudent = 0;
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mes paiements - 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">
</head>
<body>
<div class="dashboard">
    <?php include '../includes/portal_sidebar.php'; ?>
    <div class="main-content">
        <div class="header-bar">
            <h1><i class="fas fa-money-bill-wave"></i> Mes paiements</h1>
        </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 lié à votre compte.</p>
        </div>
        <?php else: ?>

        <!-- Carte total -->
        <div class="container" style="grid-template-columns:repeat(auto-fit,minmax(200px,1fr));margin-bottom:1.5rem;">
            <div class="stat-card">
                <i class="fas fa-coins" style="color:#48bb78;"></i>
                <h3><?= formatAmount($totalPaid) ?></h3>
                <p>Total versé</p>
            </div>
            <div class="stat-card">
                <i class="fas fa-receipt" style="color:#667eea;"></i>
                <h3><?= count($payments) ?></h3>
                <p>Paiements enregistrés</p>
            </div>
        </div>

        <!-- Filtre élève (parent) -->
        <?php if ($userRole === 'parent' && count($studentsInfo) > 1): ?>
        <div class="card" style="margin-bottom:1rem;">
            <form method="GET" style="display:flex;gap:1rem;align-items:flex-end;">
                <div class="form-group" style="margin:0;min-width:220px;">
                    <label>Filtrer par enfant</label>
                    <select name="student_id" onchange="this.form.submit()">
                        <option value="">Tous mes enfants</option>
                        <?php foreach ($studentsInfo as $st): ?>
                        <option value="<?= $st['id'] ?>" <?= $filterStudent == $st['id'] ? 'selected' : '' ?>><?= e($st['full_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </form>
        </div>
        <?php endif; ?>

        <div class="card">
            <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>
                        <th>Référence</th>
                        <th>Description</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($payments as $p): ?>
                <tr>
                    <?php if ($userRole === 'parent'): ?><td><?= e($p['student_name']) ?></td><?php endif; ?>
                    <td><strong style="color:#22543d;"><?= formatAmount($p['amount']) ?></strong></td>
                    <td><?= formatDate($p['payment_date']) ?></td>
                    <td>
                        <?php
                        $icons = ['Espèces'=>'fa-money-bill','Virement'=>'fa-university','Mobile Money'=>'fa-mobile-alt','Carte'=>'fa-credit-card'];
                        $icon  = $icons[$p['method']] ?? 'fa-receipt';
                        ?>
                        <i class="fas <?= $icon ?>"></i> <?= e($p['method']) ?>
                    </td>
                    <td><code style="font-size:.85rem;color:#718096;"><?= e($p['reference_code'] ?? '-') ?></code></td>
                    <td style="color:#718096;font-size:.9rem;"><?= e($p['description'] ?? '-') ?></td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($payments)): ?>
                <tr><td colspan="<?= $userRole === 'parent' ? 6 : 5 ?>" style="text-align:center;color:#999;padding:2rem;">Aucun paiement enregistré</td></tr>
                <?php endif; ?>
                </tbody>
                <?php if (!empty($payments)): ?>
                <tfoot>
                    <tr style="background:#f7fafc;font-weight:700;">
                        <?php if ($userRole === 'parent'): ?>
                        <td></td>
                        <?php endif; ?>
                        <td>Total</td>
                        <td style="color:#22543d;"><?= formatAmount($totalPaid) ?></td>
                        <td colspan="4"></td>
                    </tr>
                </tfoot>
                <?php endif; ?>
            </table>
                </div>
        </div>
        <?php endif; ?>
    </div>
</div>
</body>
</html>
