<?php session_start(); ?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="w3.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@600;700&family=Source+Serif+4:ital,wght@0,300;0,400;0,600;1,400&display=swap" rel="stylesheet">
<title>Sous-matières – Attribution</title>
<style>
:root {
    --navy:   #1a2744;
    --gold:   #c9a84c;
    --cream:  #faf8f3;
    --light:  #f0ece0;
    --text:   #1c1c1c;
    --muted:  #6b6356;
    --green:  #2d6a4f;
    --red:    #9b2335;
    --border: #d4c9a8;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
    background: var(--cream);
    font-family: 'Source Serif 4', Georgia, serif;
    font-size: 14px;
    color: var(--text);
    min-height: 100vh;
}

/* ---- Top bar ---- */
.top-bar {
    background: var(--navy);
    padding: 18px 36px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 12px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.25);
}
.top-bar h1 {
    font-family: 'Playfair Display', serif;
    color: var(--gold);
    font-size: 22px;
    letter-spacing: 1px;
}
.top-bar .subtitle {
    color: rgba(255,255,255,0.55);
    font-size: 12px;
    letter-spacing: 2px;
    text-transform: uppercase;
    margin-top: 3px;
}
.btn-back {
    background: transparent;
    border: 1px solid rgba(201,168,76,0.5);
    color: var(--gold);
    padding: 8px 18px;
    border-radius: 4px;
    font-size: 13px;
    cursor: pointer;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: background 0.2s;
}
.btn-back:hover { background: rgba(201,168,76,0.1); }

/* ---- Page wrapper ---- */
.page-wrap {
    max-width: 920px;
    margin: 36px auto;
    padding: 0 20px 60px;
    display: flex;
    flex-direction: column;
    gap: 28px;
}

/* ---- Card ---- */
.card {
    background: #fff;
    border: 1px solid var(--border);
    border-radius: 2px;
    box-shadow: 0 2px 16px rgba(0,0,0,0.07);
    overflow: hidden;
}
.card::before {
    content: '';
    display: block;
    height: 5px;
    background: linear-gradient(90deg, var(--navy) 0%, var(--gold) 50%, var(--navy) 100%);
}
.card-header {
    padding: 16px 24px;
    border-bottom: 1px solid var(--border);
    background: linear-gradient(135deg, var(--cream) 0%, #fff 100%);
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
}
.card-header h2 {
    font-family: 'Playfair Display', serif;
    font-size: 16px;
    color: var(--navy);
    letter-spacing: 0.5px;
}
.card-header .teacher-badge {
    background: var(--navy);
    color: var(--gold);
    font-family: 'Playfair Display', serif;
    font-size: 13px;
    padding: 4px 14px;
    border-radius: 20px;
    letter-spacing: 0.5px;
}
.card-body { padding: 24px; }

/* ---- Existing reservations table ---- */
.res-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13px;
}
.res-table thead tr th {
    background: var(--navy);
    color: #fff;
    padding: 9px 12px;
    text-align: left;
    font-weight: 600;
    letter-spacing: 0.3px;
    border: 1px solid #2e3f6e;
    font-size: 12px;
}
.res-table tbody tr td {
    padding: 9px 12px;
    border: 1px solid var(--border);
    vertical-align: middle;
}
.res-table tbody tr:nth-child(even) td { background: var(--cream); }
.res-table tbody tr:hover td { background: #fdf9ee; }

.no-data {
    text-align: center;
    color: var(--muted);
    font-style: italic;
    padding: 24px;
    font-size: 13px;
}

/* ---- Grouped class header inside table ---- */
.group-header td {
    background: linear-gradient(90deg, #eee8d5, #f5f1e8);
    font-family: 'Playfair Display', serif;
    color: var(--navy);
    font-size: 12px;
    letter-spacing: 0.5px;
    padding: 6px 12px;
    border: 1px solid var(--border);
}

/* ---- Delete button ---- */
.btn-delete {
    background: transparent;
    border: 1px solid #e8b4b4;
    color: var(--red);
    padding: 4px 12px;
    border-radius: 4px;
    font-size: 12px;
    cursor: pointer;
    transition: all 0.15s;
    white-space: nowrap;
}
.btn-delete:hover { background: var(--red); color: #fff; border-color: var(--red); }

/* ---- Add section: checkbox grid by class ---- */
.class-block { margin-bottom: 20px; }
.class-block:last-child { margin-bottom: 0; }

.class-title {
    font-family: 'Playfair Display', serif;
    font-size: 13px;
    color: var(--navy);
    background: linear-gradient(90deg, #eee8d5, #f5f1e8);
    padding: 8px 14px;
    border: 1px solid var(--border);
    border-bottom: none;
    letter-spacing: 0.5px;
}

.sub-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 0;
    border: 1px solid var(--border);
}
.sub-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 14px;
    border-right: 1px solid var(--border);
    border-bottom: 1px solid var(--border);
    cursor: pointer;
    transition: background 0.15s;
    font-size: 13px;
    background: #fff;
}
.sub-item:hover { background: #fdf9ee; }
.sub-item input[type="checkbox"] {
    accent-color: var(--navy);
    width: 15px;
    height: 15px;
    cursor: pointer;
    flex-shrink: 0;
}
.sub-item.already-reserved {
    background: #f0f8f4;
    color: var(--green);
}
.sub-item.already-reserved input { accent-color: var(--green); }
.badge-reserved {
    font-size: 10px;
    background: var(--green);
    color: #fff;
    padding: 1px 7px;
    border-radius: 10px;
    margin-left: auto;
    white-space: nowrap;
    flex-shrink: 0;
}

/* ---- Submit button ---- */
.btn-submit {
    background: var(--gold);
    color: var(--navy);
    border: none;
    padding: 11px 32px;
    font-family: 'Playfair Display', serif;
    font-weight: 700;
    font-size: 14px;
    letter-spacing: 0.5px;
    border-radius: 4px;
    cursor: pointer;
    transition: background 0.2s;
    margin-top: 20px;
    display: inline-block;
}
.btn-submit:hover { background: #b8923a; }

/* ---- Alerts ---- */
.alert {
    padding: 11px 16px;
    border-radius: 4px;
    font-size: 13px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 8px;
}
.alert-success { background: #edf7f2; border: 1px solid #a8d5be; color: var(--green); }
.alert-err     { background: #fdf0f0; border: 1px solid #e8b4b4; color: var(--red); }
.alert-warn    { background: #fef9ec; border: 1px solid #f0d080; color: #8a6d00; }

/* ---- Empty state ---- */
.empty-add {
    text-align: center;
    color: var(--muted);
    font-style: italic;
    padding: 32px;
    font-size: 13px;
}
</style>
</head>
<body>

<?php
include '_serveur.php';

/* ---- Session data ---- */
$teacherID = (int)($_SESSION['id']   ?? 0);
$cla1      = $_SESSION['cla1'] ?? [];
$mat1      = (int)($_SESSION['mat1'] ?? 0);

/* Redirect back if session is empty */
if (!$teacherID || empty($cla1) || !$mat1) {
    echo '<p style="color:red;padding:20px">Session expirée. <a href="javascript:history.back()">Retour</a></p>';
    exit;
}

/* ---- Load teacher name ---- */
$res_t = mysqli_query($link, 'SELECT firstName, lastName FROM users WHERE id=' . $teacherID);
$teacher = $res_t ? mysqli_fetch_assoc($res_t) : null;
$teacherName = $teacher
    ? htmlspecialchars($teacher['firstName'] . ' ' . $teacher['lastName'])
    : 'Enseignant #' . $teacherID;

/* ---- Load subject name ---- */
$res_m = mysqli_query($link, 'SELECT name FROM subjects WHERE id=' . $mat1);
$subjectRow  = $res_m ? mysqli_fetch_assoc($res_m) : null;
$subjectName = $subjectRow ? htmlspecialchars($subjectRow['name']) : 'Matière #' . $mat1;

/* ============================================================
   HANDLE DELETE
   ============================================================ */
$deleteMsg = '';
if (isset($_POST['action']) && $_POST['action'] === 'delete') {
    $d_classID    = (int)($_POST['d_classID']    ?? 0);
    $d_subjectID  = (int)($_POST['d_subjectID']  ?? 0);
    $d_subsubID   = (int)($_POST['d_subsubID']   ?? 0);
    if ($d_classID && $d_subjectID && $d_subsubID) {
        $sql_del = 'DELETE FROM teachersSubsubjects
                    WHERE userID="'    . $teacherID   . '"
                      AND classID="'   . $d_classID   . '"
                      AND subjectID="' . $d_subjectID . '"
                      AND subsubjectID="' . $d_subsubID . '"';
        if (mysqli_query($link, $sql_del)) {
            $deleteMsg = 'success';
        } else {
            $deleteMsg = 'error: ' . mysqli_error($link);
        }
    }
}

/* ============================================================
   HANDLE SAVE (new assignments)
   ============================================================ */
$saveMessages = [];
if (isset($_POST['save'])) {
    $sub1 = $_POST['sub'] ?? [];
    foreach ($sub1 as $sub_val) {
        $parts = explode(';', $sub_val);
        if (count($parts) < 3) continue;
        $clid   = (int)$parts[0];
        $subid  = (int)$parts[1];
        $subsub = (int)$parts[2];

        /* Duplicate check */
        $sql_chk = 'SELECT COUNT(*) AS cnt FROM teachersSubsubjects
                    WHERE userID="'       . $teacherID . '"
                      AND classID="'     . $clid      . '"
                      AND subjectID="'   . $subid     . '"
                      AND subsubjectID="'. $subsub     . '"';
        $res_chk = mysqli_query($link, $sql_chk);
        $row_chk = $res_chk ? mysqli_fetch_assoc($res_chk) : null;

        if ($row_chk && (int)$row_chk['cnt'] > 0) {
            $saveMessages[] = ['type' => 'warn', 'text' => 'Déjà réservé — ignoré.'];
            continue;
        }

        $sql_ins = 'INSERT INTO teachersSubsubjects (userID, classID, subjectID, subsubjectID)
                    VALUES("' . $teacherID . '","' . $clid . '","' . $subid . '","' . $subsub . '")';
        if (!mysqli_query($link, $sql_ins)) {
            $saveMessages[] = ['type' => 'err', 'text' => 'Erreur: ' . mysqli_error($link)];
        } else {
            $saveMessages[] = ['type' => 'success', 'text' => 'Sous-matière enregistrée avec succès.'];
        }
    }
}

/* ============================================================
   BUILD LIST OF CLASSES
   ============================================================ */
$classes = []; // [ classID => className ]
foreach ($cla1 as $cla_val) {
    $parts = explode(';', $cla_val);
    if (count($parts) >= 2) {
        $classes[(int)$parts[0]] = strtoupper(trim($parts[1]));
    }
}

/* ============================================================
   LOAD EXISTING RESERVATIONS for this teacher + subject
   ============================================================ */
$class_ids_str = implode(',', array_map('intval', array_keys($classes)));
$existing = []; // [ classID => [ [subjectID, subsubID, subsubName], ... ] ]

if ($class_ids_str) {
    $sql_ex = 'SELECT ts.classID, ts.subjectID, ts.subsubjectID, ss.name AS subsubName
               FROM teachersSubsubjects ts
               INNER JOIN subSubjects ss ON ss.id = ts.subsubjectID
               WHERE ts.userID="' . $teacherID . '"
                 AND ts.subjectID="' . $mat1 . '"
                 AND ts.classID IN (' . $class_ids_str . ')
               ORDER BY ts.classID, ss.name';
    $res_ex = mysqli_query($link, $sql_ex);
    if ($res_ex) {
        while ($row = mysqli_fetch_assoc($res_ex)) {
            $existing[(int)$row['classID']][] = $row;
        }
    }
}

/* ============================================================
   LOAD AVAILABLE SUB-SUBJECTS per class for this subject
   ============================================================ */
// [ classID => [ [subjectID, subsubjectID, subsubName], ... ] ]
$available = [];
foreach ($classes as $cid => $cname) {
    $sql_av = 'SELECT su.id AS subjectID, ss.id AS subsubjectID, ss.name AS subsubName
               FROM subjects su
               INNER JOIN subSubjects ss ON su.id = ss.subjectID
               INNER JOIN gradesSubjects gs ON ss.id = gs.subSubjectID
               WHERE gs.classID="' . $cid . '" AND ss.subjectID="' . $mat1 . '"
               ORDER BY ss.name';
    $res_av = mysqli_query($link, $sql_av);
    if ($res_av) {
        while ($row = mysqli_fetch_assoc($res_av)) {
            $available[$cid][] = $row;
        }
    }
}
?>

<div class="top-bar">
    <div>
        <h1>📋 Attribution des Sous-matières</h1>
        <div class="subtitle">Matière : <?= $subjectName ?></div>
    </div>
    <a href="javascript:history.back()" class="btn-back">← Retour</a>
</div>

<div class="page-wrap">

<?php
/* ---- Show save messages ---- */
foreach ($saveMessages as $msg):
    $cls = $msg['type'] === 'success' ? 'alert-success' : ($msg['type'] === 'warn' ? 'alert-warn' : 'alert-err');
?>
<div class="alert <?= $cls ?>"><?= htmlspecialchars($msg['text']) ?></div>
<?php endforeach; ?>

<?php if ($deleteMsg === 'success'): ?>
<div class="alert alert-success">✓ Réservation supprimée avec succès.</div>
<?php elseif ($deleteMsg && $deleteMsg !== ''): ?>
<div class="alert alert-err">Erreur lors de la suppression : <?= htmlspecialchars($deleteMsg) ?></div>
<?php endif; ?>

<!-- =============================================
     SECTION 1 — EXISTING RESERVATIONS
     ============================================= -->
<div class="card">
    <div class="card-header">
        <h2>Réservations actuelles</h2>
        <div class="teacher-badge"><?= $teacherName ?></div>
    </div>
    <div class="card-body">
        <?php
        $hasAny = false;
        foreach ($classes as $cid => $cname) {
            if (!empty($existing[$cid])) { $hasAny = true; break; }
        }
        if (!$hasAny):
        ?>
        <div class="no-data">Aucune réservation existante pour cet enseignant sur cette matière.</div>
        <?php else: ?>
        <table class="res-table">
            <thead>
                <tr>
                    <th style="width:25%">Classe</th>
                    <th>Sous-matière</th>
                    <th style="width:15%;text-align:center">Action</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($classes as $cid => $cname): ?>
                <?php if (empty($existing[$cid])) continue; ?>
                <tr class="group-header">
                    <td colspan="3"><?= htmlspecialchars($cname) ?></td>
                </tr>
                <?php foreach ($existing[$cid] as $ex_row): ?>
                <tr>
                    <td style="padding-left:24px;color:var(--muted);font-size:12px">↳ <?= htmlspecialchars($cname) ?></td>
                    <td><?= htmlspecialchars($ex_row['subsubName']) ?></td>
                    <td style="text-align:center">
                        <form method="post" action="teachersubcont.php"
                              onsubmit="return confirm('Supprimer cette réservation ?');"
                              style="display:inline">
                            <input type="hidden" name="action"       value="delete">
                            <input type="hidden" name="d_classID"    value="<?= (int)$ex_row['classID'] ?>">
                            <input type="hidden" name="d_subjectID"  value="<?= (int)$ex_row['subjectID'] ?>">
                            <input type="hidden" name="d_subsubID"   value="<?= (int)$ex_row['subsubjectID'] ?>">
                            <button type="submit" class="btn-delete">🗑 Supprimer</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
</div>

<!-- =============================================
     SECTION 2 — ADD NEW SUB-SUBJECTS
     ============================================= -->
<div class="card">
    <div class="card-header">
        <h2>Ajouter des sous-matières</h2>
        <div class="teacher-badge"><?= $subjectName ?></div>
    </div>
    <div class="card-body">
        <?php
        $hasAvailable = false;
        foreach ($classes as $cid => $cname) {
            if (!empty($available[$cid])) { $hasAvailable = true; break; }
        }
        if (!$hasAvailable):
        ?>
        <div class="empty-add">Aucune sous-matière disponible pour les classes sélectionnées.</div>
        <?php else: ?>

        <form method="post" action="teachersubcont.php">
        <?php foreach ($classes as $cid => $cname): ?>
            <?php if (empty($available[$cid])) continue; ?>

            <!-- Build a set of already-reserved subsubjectIDs for this class -->
            <?php
            $reserved_ids = [];
            foreach (($existing[$cid] ?? []) as $ex) {
                $reserved_ids[] = (int)$ex['subsubjectID'];
            }
            ?>

            <div class="class-block">
                <div class="class-title"><?= htmlspecialchars($cname) ?></div>
                <div class="sub-grid">
                <?php foreach ($available[$cid] as $av): ?>
                    <?php
                    $is_reserved = in_array((int)$av['subsubjectID'], $reserved_ids);
                    $val = $cid . ';' . (int)$av['subjectID'] . ';' . (int)$av['subsubjectID'];
                    ?>
                    <label class="sub-item <?= $is_reserved ? 'already-reserved' : '' ?>">
                        <input type="checkbox"
                               name="sub[]"
                               value="<?= $val ?>"
                               <?= $is_reserved ? 'checked disabled' : '' ?>>
                        <?= htmlspecialchars($av['subsubName']) ?>
                        <?php if ($is_reserved): ?>
                            <span class="badge-reserved">✓ Réservé</span>
                        <?php endif; ?>
                    </label>
                <?php endforeach; ?>
                </div>
            </div>
        <?php endforeach; ?>

        <button type="submit" name="save" class="btn-submit">💾 Enregistrer</button>
        </form>

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

</div><!-- /page-wrap -->
<?php mysqli_close($link); ?>
</body>
</html>
