<?php
/**
 * Périodes de saisie des notes — Trimestre / Semestre
 */
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';
header('Content-Type: text/html; charset=utf-8');

checkRole(['super_admin', 'school_admin']);

$schoolFilter = currentSchoolId();
if (isSuperAdmin() && !empty($_GET['school_id'])) {
    $schoolFilter = (int)$_GET['school_id'];
}

$error = '';

$academicYears = $pdo->query("SELECT DISTINCT year FROM academic_years WHERE school_id=" . (int)($schoolFilter ?: 0))->fetchAll(PDO::FETCH_COLUMN);
if (empty($academicYears)) {
    $academicYears = $pdo->query("SELECT DISTINCT year FROM academic_years ORDER BY year DESC")->fetchAll(PDO::FETCH_COLUMN);
}
if (empty($academicYears)) { $academicYears = []; }
$academicYears = array_unique(array_merge($academicYears, [date('Y') . '-' . (date('Y')+1)]));

// ── CRUD ──────────────────────────────────────────────────────────────────────

// Suppression
if (isset($_GET['delete'])) {
    verifyCsrf();
    $id = (int)$_GET['delete'];
    $pdo->prepare("DELETE FROM grading_periods WHERE id=? AND school_id=COALESCE(?,school_id)")
        ->execute([$id, $schoolFilter]);
    flashMessage('success', 'Période supprimée.');
    header('Location: grading_periods.php?' . http_build_query(['academic_year'=>$_GET['academic_year']??'','school_id'=>$_GET['school_id']??''])); exit;
}

// Ajout / Modification
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
    verifyCsrf();
    $id            = (int)($_POST['id'] ?? 0);
    $school_id     = (int)($_POST['school_id'] ?? $schoolFilter);
    $academic_year = trim($_POST['academic_year'] ?? '');
    $period_type   = $_POST['period_type'] ?? 'trimestre';
    $period_number = (int)($_POST['period_number'] ?? 0);
    $label         = trim($_POST['label'] ?? '');
    $start_date    = $_POST['start_date'] ?? '';
    $end_date      = $_POST['end_date'] ?? '';
    $is_open       = isset($_POST['is_open']) ? 1 : 0;

    if (empty($academic_year) || empty($start_date) || empty($end_date)) {
        $error = 'Année, date début et date fin sont requis.';
    } elseif ($period_number < 1 || ($period_type === 'trimestre' && $period_number > 3) || ($period_type === 'semestre' && $period_number > 2)) {
        $error = 'Numéro de période invalide.';
    } elseif ($start_date > $end_date) {
        $error = 'La date de fin doit être postérieure à la date de début.';
    } else {
        if (!$label) {
            $label = match(true) {
                $period_type === 'trimestre' => match($period_number) {1=>'1er Trimestre',2=>'2ème Trimestre',3=>'3ème Trimestre',default=>"Trimestre $period_number"},
                $period_type === 'semestre'  => match($period_number) {1=>'1er Semestre',2=>'2ème Semestre',default=>"Semestre $period_number"},
                default => ucfirst($period_type) . ' ' . $period_number,
            };
        }
        if ($id) {
            $pdo->prepare("UPDATE grading_periods SET school_id=?,academic_year=?,period_type=?,period_number=?,label=?,start_date=?,end_date=?,is_open=? WHERE id=?")
                ->execute([$school_id,$academic_year,$period_type,$period_number,$label,$start_date,$end_date,$is_open,$id]);
            flashMessage('success', 'Période mise à jour.');
        } else {
            try {
                $pdo->prepare("INSERT INTO grading_periods (school_id,academic_year,period_type,period_number,label,start_date,end_date,is_open) VALUES (?,?,?,?,?,?,?,?)")
                    ->execute([$school_id,$academic_year,$period_type,$period_number,$label,$start_date,$end_date,$is_open]);
                flashMessage('success', 'Période ajoutée.');
            } catch (PDOException $e) {
                if ($e->getCode() == 23000) {
                    $error = 'Cette période existe déjà pour cette école et cette année.';
                } else {
                    $error = 'Erreur : ' . $e->getMessage();
                }
            }
        }
        if (empty($error)) {
            header('Location: grading_periods.php?' . http_build_query(['academic_year'=>$_GET['academic_year']??'','school_id'=>$_GET['school_id']??''])); exit;
        }
    }
}

// Chargement
$filterYear = $_GET['academic_year'] ?? '';
if ($filterYear) {
    $periods = $pdo->prepare("
        SELECT gp.*, s.name AS school_name
        FROM grading_periods gp
        JOIN schools s ON gp.school_id = s.id
        WHERE gp.academic_year = ? " . ($schoolFilter ? " AND gp.school_id=" . (int)$schoolFilter : "") . "
        ORDER BY gp.academic_year DESC, gp.period_type, gp.period_number
    ");
    $periods->execute([$filterYear]);
} else {
    $periods = $pdo->prepare("
        SELECT gp.*, s.name AS school_name
        FROM grading_periods gp
        JOIN schools s ON gp.school_id = s.id
        WHERE 1=1 " . ($schoolFilter ? " AND gp.school_id=" . (int)$schoolFilter : "") . "
        ORDER BY gp.academic_year DESC, gp.period_type, gp.period_number
    ");
    $periods->execute();
}
$periods = $periods->fetchAll();

$schools = $pdo->query("SELECT id, name FROM schools ORDER BY name")->fetchAll();

// Édition
$editPeriod = null;
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    $st = $pdo->prepare("SELECT * FROM grading_periods WHERE id=? AND school_id=COALESCE(?,school_id)");
    $st->execute([$id, $schoolFilter]);
    $editPeriod = $st->fetch();
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Périodes de saisie - 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>
        .period-card {
            background: #fff;
            border-radius: 10px;
            border: 1px solid #e2e8f0;
            padding: 1rem 1.25rem;
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        .period-card.open { border-left: 4px solid #38a169; }
        .period-card.closed { border-left: 4px solid #e53e3e; }
        .period-info { flex: 1; }
        .period-info .period-label { font-weight: 700; color: #2d3748; }
        .period-info .period-dates { font-size: .8rem; color: #718096; margin-top: .15rem; }
        .period-info .period-school { font-size: .75rem; color: #a0aec0; }
        .period-status {
            font-size: .75rem;
            font-weight: 600;
            padding: .25rem .6rem;
            border-radius: 20px;
        }
        .period-status.open { background: #c6f6d5; color: #22543d; }
        .period-status.closed { background: #fed7d7; color: #9b2c2c; }
        .period-actions { display: flex; gap: .4rem; }
        .periods-grid { display: flex; flex-direction: column; gap: .75rem; }
        .form-compact { display: grid; grid-template-columns: 1fr 1fr; gap: .75rem; }
        .form-compact .form-group { margin: 0; }
        .form-compact .full-width { grid-column: 1 / -1; }
    </style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-calendar-alt"></i> Périodes de saisie'; include '../includes/topbar.php'; ?>
        <?= showFlash() ?>
        <?php if ($error): ?><div class="error-message"><?= e($error) ?></div><?php endif; ?>

        <div class="dashboard-grid-2" style="align-items:start;">
            <!-- Formulaire -->
            <div class="card">
                <div class="card-header">
                    <span class="card-title"><?= $editPeriod ? 'Modifier' : 'Ajouter' ?> une période</span>
                </div>
                <form method="POST">
                    <?= csrfField() ?>
                    <?php if ($editPeriod): ?>
                    <input type="hidden" name="id" value="<?= $editPeriod['id'] ?>">
                    <?php endif; ?>
                    <div class="form-compact">
                        <?php if (isSuperAdmin()): ?>
                        <div class="form-group">
                            <label>École</label>
                            <select name="school_id" required>
                                <?php foreach ($schools as $sc): ?>
                                <option value="<?= $sc['id'] ?>" <?= ($editPeriod['school_id'] ?? $schoolFilter) == $sc['id'] ? 'selected' : '' ?>><?= e($sc['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php else: ?>
                        <input type="hidden" name="school_id" value="<?= $schoolFilter ?>">
                        <?php endif; ?>
                        <div class="form-group">
                            <label>Année scolaire</label>
                            <select name="academic_year" required>
                                <?php foreach ($academicYears as $y): ?>
                                <option value="<?= e($y) ?>" <?= ($editPeriod['academic_year'] ?? $filterYear) === $y ? 'selected' : '' ?>><?= e($y) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Type</label>
                            <select name="period_type" required onchange="togglePeriodNumber(this)">
                                <option value="trimestre" <?= ($editPeriod['period_type'] ?? '') === 'trimestre' ? 'selected' : '' ?>>Trimestre</option>
                                <option value="semestre" <?= ($editPeriod['period_type'] ?? '') === 'semestre' ? 'selected' : '' ?>>Semestre</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Numéro</label>
                            <select name="period_number" required id="periodNumber">
                                <?php for ($i = 1; $i <= 3; $i++): ?>
                                <option value="<?= $i ?>" <?= ($editPeriod['period_number'] ?? '') == $i ? 'selected' : '' ?>><?= $i ?><?= $i === 1 ? 'er' : 'ème' ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Libellé <small>(optionnel)</small></label>
                            <input type="text" name="label" value="<?= e($editPeriod['label'] ?? '') ?>" placeholder="Ex: 1er Trimestre">
                        </div>
                        <div class="form-group">
                            <label class="toggle-label" style="margin-top:1.5rem;">
                                <input type="checkbox" name="is_open" value="1" <?= ($editPeriod['is_open'] ?? 1) ? 'checked' : '' ?>>
                                <span>Période ouverte</span>
                            </label>
                        </div>
                        <div class="form-group">
                            <label>Date début</label>
                            <input type="date" name="start_date" required value="<?= e($editPeriod['start_date'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <label>Date fin</label>
                            <input type="date" name="end_date" required value="<?= e($editPeriod['end_date'] ?? '') ?>">
                        </div>
                    </div>
                    <div style="display:flex;gap:.5rem;margin-top:1rem;">
                        <button type="submit" name="save" class="btn-submit"><i class="fas fa-save"></i> Enregistrer</button>
                        <?php if ($editPeriod): ?>
                        <a href="grading_periods.php" class="btn-action" style="background:#e2e8f0;">Annuler</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>

            <!-- Liste des périodes -->
            <div>
                <div style="display:flex;gap:.5rem;margin-bottom:1rem;flex-wrap:wrap;align-items:center;">
                    <form method="GET" style="display:flex;gap:.5rem;align-items:end;">
                        <?php if (isSuperAdmin()): ?>
                        <select name="school_id" onchange="this.form.submit()" style="padding:.4rem .7rem;border:1px solid #e2e8f0;border-radius:6px;">
                            <option value="">Toutes les écoles</option>
                            <?php foreach ($schools as $sc): ?>
                            <option value="<?= $sc['id'] ?>" <?= $schoolFilter==$sc['id']?'selected':'' ?>><?= e($sc['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <?php endif; ?>
                        <select name="academic_year" onchange="this.form.submit()" style="padding:.4rem .7rem;border:1px solid #e2e8f0;border-radius:6px;">
                            <option value="" <?= $filterYear===''?'selected':'' ?>>Toutes les années</option>
                            <?php foreach ($academicYears as $y): ?>
                            <option value="<?= e($y) ?>" <?= $y===$filterYear?'selected':'' ?>><?= e($y) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <button type="submit" class="btn-action btn-view"><i class="fas fa-search"></i></button>
                    </form>
                </div>

                <?php if (empty($periods)): ?>
                <div class="card" style="text-align:center;padding:2rem;color:#999;">
                    Aucune période définie pour cette année.
                </div>
                <?php else: ?>
                <div class="periods-grid">
                    <?php foreach ($periods as $p):
                        $isOpen = (bool)$p['is_open'];
                    ?>
                    <div class="period-card <?= $isOpen ? 'open' : 'closed' ?>">
                        <div class="period-info">
                            <div class="period-label"><?= e($p['label']) ?></div>
                            <div class="period-dates">
                                Du <?= formatDate($p['start_date']) ?> au <?= formatDate($p['end_date']) ?>
                            </div>
                            <div class="period-school"><?= e($p['school_name']) ?> · <?= e($p['academic_year']) ?></div>
                        </div>
                        <span class="period-status <?= $isOpen ? 'open' : 'closed' ?>">
                            <i class="fas fa-<?= $isOpen ? 'lock-open' : 'lock' ?>"></i> <?= $isOpen ? 'Ouvert' : 'Fermé' ?>
                        </span>
                        <div class="period-actions">
                            <a href="?edit=<?= $p['id'] ?>&academic_year=<?= urlencode($filterYear) ?><?= $schoolFilter ? '&school_id='.$schoolFilter : '' ?>" class="btn-action btn-edit" title="Modifier"><i class="fas fa-edit"></i></a>
                            <a href="?delete=<?= $p['id'] ?>&csrf_token=<?= csrfToken() ?>&academic_year=<?= urlencode($filterYear) ?><?= $schoolFilter ? '&school_id='.$schoolFilter : '' ?>" class="btn-action btn-delete" title="Supprimer" onclick="return confirm('Supprimer cette période ?')"><i class="fas fa-trash"></i></a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
function togglePeriodNumber(sel) {
    const max = sel.value === 'semestre' ? 2 : 3;
    const select = document.getElementById('periodNumber');
    const current = parseInt(select.value);
    select.innerHTML = '';
    for (let i = 1; i <= max; i++) {
        const opt = document.createElement('option');
        opt.value = i;
        opt.textContent = i + (i === 1 ? 'er' : 'ème');
        if (i === current || (i === max && current > max)) opt.selected = true;
        select.appendChild(opt);
    }
}
</script>
</body>
</html>
