<?php
ob_start();
session_start();
include '_serveur.php';
ob_end_clean(); // discard anything _serveur.php printed or buffered
ob_start();     // start a fresh clean buffer for our own output

// _serveur.php already sent Content-Type: application/json
// and will exit on DB failure

$classIDs = $_POST['classIDs'] ?? [];
$date     = $_POST['date']     ?? '';
$cycle    = $_POST['cycle']    ?? '';
$mode     = $_POST['mode']     ?? 'preview';

$date     = preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) ? $date : date('Y-m-d');
$classIDs = array_filter(array_map('intval', $classIDs));

$html = '';

// ── FULL-DAY MODE ─────────────────────────────────────────────────
if ($mode === 'fullday') {

    $allClassStmt = mysqli_prepare($link, "SELECT id, name FROM classes WHERE cycleID=? ORDER BY id ASC");
    mysqli_stmt_bind_param($allClassStmt, "s", $cycle);
    mysqli_stmt_execute($allClassStmt);
    $allClasses = [];
    while ($cls = mysqli_fetch_assoc(mysqli_stmt_get_result($allClassStmt))) {
        $allClasses[] = $cls;
    }

    if (empty($allClasses)) {
        ob_end_clean();
        echo json_encode(['html' => '<div class="w3-panel w3-pale-yellow w3-border"><p>📭 Aucune classe trouvée pour ce cycle.</p></div>']);
        exit;
    }

    $countStmt = mysqli_prepare($link, "SELECT COUNT(*) AS total FROM agenda a JOIN classes c ON a.classID=c.id WHERE c.cycleID=? AND DATE(a.date)=?");
    mysqli_stmt_bind_param($countStmt, "ss", $cycle, $date);
    mysqli_stmt_execute($countStmt);
    $total = mysqli_fetch_assoc(mysqli_stmt_get_result($countStmt))['total'];

    if ($total == 0) {
        $html = '<div class="w3-panel w3-pale-yellow w3-border"><p>📭 Aucun agenda enregistré pour ce cycle à cette date.</p></div>';
    } else {
        $html = '<p class="w3-text-grey"><b>'.$total.' entrée(s)</b> enregistrée(s) pour ce cycle ce jour-là.</p>';
        foreach ($allClasses as $cls) {
            $cid    = intval($cls['id']);
            $cname  = htmlspecialchars($cls['name']);
            $agStmt = mysqli_prepare($link, "SELECT s.name AS subject, a.description, a.rtl FROM agenda a JOIN subjects s ON a.subjectID=s.id WHERE a.classID=? AND DATE(a.date)=? ORDER BY s.name ASC");
            mysqli_stmt_bind_param($agStmt, "is", $cid, $date);
            mysqli_stmt_execute($agStmt);
            $agRes  = mysqli_stmt_get_result($agStmt);
            $count  = mysqli_num_rows($agRes);
            $cc     = $count > 0 ? 'w3-pale-green' : 'w3-light-grey';
            $badge  = '<span class="w3-badge '.($count>0?'w3-teal':'w3-grey').' w3-small" style="margin-left:8px">'.$count.'</span>';
            $html  .= '<div class="w3-card w3-margin '.$cc.'" style="padding:12px 16px">';
            $html  .= '<h4 style="margin:0 0 8px 0">📚 '.$cname.$badge.'</h4>';
            if ($count > 0) {
                $html .= '<table class="w3-table w3-bordered w3-white" style="font-size:0.95em"><tr class="w3-teal"><th>Matière</th><th>Description</th></tr>';
                while ($r = mysqli_fetch_assoc($agRes)) {
                    $dir   = $r['rtl'] ? 'rtl' : 'ltr';
                    $html .= '<tr><td><b>'.htmlspecialchars($r['subject']).'</b></td><td dir="'.$dir.'">'.htmlspecialchars($r['description'], ENT_QUOTES).'</td></tr>';
                }
                $html .= '</table>';
            } else {
                $html .= '<p class="w3-text-grey" style="margin:0"><i>Aucun agenda pour cette classe.</i></p>';
            }
            $html .= '</div>';
        }
    }

    ob_end_clean();
    echo json_encode(['html' => $html]);
    exit;
}

// ── PREVIEW MODE ──────────────────────────────────────────────────
if (empty($classIDs)) {
    ob_end_clean();
    echo json_encode(['html' => '<div class="w3-panel w3-pale-yellow w3-border"><p>📋 Sélectionnez au moins une classe.</p></div>']);
    exit;
}

foreach ($classIDs as $cid) {
    $nameStmt = mysqli_prepare($link, "SELECT name FROM classes WHERE id=?");
    mysqli_stmt_bind_param($nameStmt, "i", $cid);
    mysqli_stmt_execute($nameStmt);
    $nameRow  = mysqli_fetch_assoc(mysqli_stmt_get_result($nameStmt));
    if (!$nameRow) continue;
    $cname = htmlspecialchars($nameRow['name']);

    $agStmt = mysqli_prepare($link, "SELECT s.name AS subject, a.description, a.rtl FROM agenda a JOIN subjects s ON a.subjectID=s.id WHERE a.classID=? AND DATE(a.date)=? ORDER BY s.name ASC");
    mysqli_stmt_bind_param($agStmt, "is", $cid, $date);
    mysqli_stmt_execute($agStmt);
    $agRes  = mysqli_stmt_get_result($agStmt);
    $count  = mysqli_num_rows($agRes);
    $cc     = $count > 0 ? 'w3-pale-green' : 'w3-light-grey';
    $badge  = '<span class="w3-badge '.($count>0?'w3-teal':'w3-grey').' w3-small" style="margin-left:8px">'.$count.'</span>';

    $html .= '<div class="w3-card w3-margin '.$cc.'" style="padding:12px 16px">';
    $html .= '<h4 style="margin:0 0 8px 0">📚 '.$cname.$badge.'</h4>';
    if ($count > 0) {
        $html .= '<table class="w3-table w3-bordered w3-white" style="font-size:0.95em"><tr class="w3-teal"><th>Matière</th><th>Description</th></tr>';
        while ($r = mysqli_fetch_assoc($agRes)) {
            $dir   = $r['rtl'] ? 'rtl' : 'ltr';
            $html .= '<tr><td><b>'.htmlspecialchars($r['subject']).'</b></td><td dir="'.$dir.'">'.htmlspecialchars($r['description'], ENT_QUOTES).'</td></tr>';
        }
        $html .= '</table>';
    } else {
        $html .= '<p class="w3-text-grey" style="margin:0"><i>Aucun agenda pour cette classe à cette date.</i></p>';
    }
    $html .= '</div>';
}

ob_end_clean();
echo json_encode(['html' => $html]);
