<?php
session_start();
include 'header.php';
include '_serveur.php';

$cycle = $_GET['cycle'] ?? '';
$today = date("Y-m-d");

// Set UTF-8 for database connection
mysqli_set_charset($link, "utf8mb4");
?>
<!DOCTYPE html>
<html lang="ar">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>كتابة جدول الأعمال - Écrire Agenda</title>
<link rel="stylesheet" href="w3.css">
<style>
* { direction: auto; }
html, body { direction: ltr; }
body { width:90%; margin:auto; }
.ajax-section { transition: opacity 0.2s; }
.ajax-section.loading { opacity: 0.35; pointer-events: none; }
.rtl-text { direction: rtl; text-align: right; }
.ltr-text { direction: ltr; text-align: left; }
</style>
</head>
<body>

<!-- ═══════════════════ FORM ════════════════════════════════════ -->
<div class="w3-card-3 w3-padding">
<h2 class="w3-text-teal">📝 Écrire Agenda</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES, 'UTF-8'); ?>" id="agendaForm" accept-charset="UTF-8">
<input type="hidden" name="cycle" value="<?= htmlspecialchars($cycle, ENT_QUOTES, 'UTF-8') ?>">

<?php
/* ── Classes ──────────────────────────────────────────────── */
$stmt = mysqli_prepare($link, "SELECT * FROM classes WHERE cycleID=? ORDER BY id ASC");
mysqli_stmt_bind_param($stmt, "s", $cycle);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

echo '<p><label class="w3-text-teal"><strong>Classe :</strong></label><br>';
$classCount = 0;
while ($data = mysqli_fetch_assoc($result)) {
    $id    = intval($data['id']);
    $name  = strtoupper($data['name']);
    $classCount++;
    echo '<input class="w3-check w3-pale-blue" type="checkbox" name="cla[]"
                 value="'.$id.'" onchange="triggerAll()">
          <label>'.htmlspecialchars($name, ENT_QUOTES, 'UTF-8').'</label>&emsp;';
}
if ($classCount == 0) {
    echo '<p class="w3-text-grey">No classes found for this cycle.</p>';
}
echo '</p>';

/* ── Direction ────────────────────────────────────────────── */
echo '<p><label class="w3-text-teal"><strong>Direction :</strong></label><br>
  <input class="w3-radio" type="radio" name="rtl" value="0" checked>
  <label>Gauche à droite (LTR)</label>&emsp;
  <input class="w3-radio" type="radio" name="rtl" value="1">
  <label>Droite à gauche (RTL) - العربية</label>
</p>';

/* ── Subjects ─────────────────────────────────────────────── */
$res = mysqli_query($link, "SELECT * FROM subjects WHERE id NOT IN (4,9,10,38,39,40) ORDER BY ordering");
echo '<p><label class="w3-text-teal"><strong>Matière :</strong></label><br>
      <select name="sub" class="w3-select w3-border w3-pale-blue" required>';
echo '<option value="">-- Sélectionner une matière --</option>';
while ($data = mysqli_fetch_assoc($res)) {
    echo '<option value="'.$data['id'].'">'.htmlspecialchars($data['name'], ENT_QUOTES, 'UTF-8').'</option>';
}
echo '</select></p>';

/* ── Date ─────────────────────────────────────────────────── */
echo '<p><label class="w3-text-teal"><strong>Date :</strong></label><br>
      <input class="w3-input w3-border w3-pale-blue" type="date"
             id="dateInput" name="date" value="'.$today.'" required
             onchange="triggerAll()"></p>';

/* ── Agenda ───────────────────────────────────────────────── */
echo '<p><label class="w3-text-teal"><strong>Agenda (العربية أم الفرنسية) :</strong></label><br>
      <textarea name="agenda" cols="60" rows="4" required
                class="w3-input w3-border w3-pale-blue"
                placeholder="Entrez le contenu de l\'agenda... أدخل محتوى جدول الأعمال..."></textarea></p>';

echo '<p><input name="envoyer" type="submit" class="w3-button w3-teal w3-large" value="📤 Envoyer"></p>';
?>
</form>
</div>

<!-- ═══════════════════ POST RESULT ════════════════════════════ -->
<?php
if (isset($_POST['envoyer'])) {
    $cla1      = $_POST['cla']   ?? [];
    $rtl       = intval($_POST['rtl']  ?? 0);
    $subjectId = intval($_POST['sub']  ?? 0);
    $date      = $_POST['date']        ?? '';
    $agenda    = trim($_POST['agenda'] ?? '');

    // Validate inputs
    if (empty($agenda)) {
        echo '<div class="w3-panel w3-pale-red w3-border">
                <p>❌ L\'agenda est obligatoire.</p>
              </div>';
    } elseif (empty($cla1)) {
        echo '<div class="w3-panel w3-pale-red w3-border">
                <p>❌ Veuillez sélectionner au moins une classe.</p>
              </div>';
    } elseif ($subjectId == 0) {
        echo '<div class="w3-panel w3-pale-red w3-border">
                <p>❌ Veuillez sélectionner une matière.</p>
              </div>';
    } else {
        $successCount = 0;
        $existsCount = 0;

        foreach ($cla1 as $classID) {
            $classID = intval($classID);
            $chk     = mysqli_prepare($link, "SELECT id FROM agenda WHERE classID=? AND subjectID=? AND DATE(date)=?");
            mysqli_stmt_bind_param($chk, "iis", $classID, $subjectId, $date);
            mysqli_stmt_execute($chk);
            
            if (mysqli_num_rows(mysqli_stmt_get_result($chk)) == 0) {
                $ins = mysqli_prepare($link, "INSERT INTO agenda (classID, subjectID, date, description, rtl) VALUES (?, ?, ?, ?, ?)");
                mysqli_stmt_bind_param($ins, "iissi", $classID, $subjectId, $date, $agenda, $rtl);
                if (mysqli_stmt_execute($ins)) {
                    $successCount++;
                }
                mysqli_stmt_close($ins);
            } else {
                $existsCount++;
            }
            mysqli_stmt_close($chk);
        }

        // Display results
        if ($successCount > 0) {
            echo '<div class="w3-panel w3-leftbar w3-sand w3-xxlarge w3-serif">
                    <p align="center"><i>✅ Agenda écrit avec succès pour '.$successCount.' classe(s)</i></p>
                  </div>';
        }
        if ($existsCount > 0) {
            echo '<div class="w3-panel w3-leftbar w3-pale-yellow w3-border">
                    <p align="center"><i>⚠️ Agenda déjà écrit pour '.$existsCount.' classe(s)</i></p>
                  </div>';
        }
    }
}
?>

<!-- ═══════════════════ PREVIEW (selected classes) ═════════════ -->
<hr class="w3-border-teal" style="margin-top:30px">
<h3 class="w3-text-teal">👁️ Aperçu — classes sélectionnées</h3>
<div id="preview-section" class="ajax-section">
    <div id="preview-placeholder" class="w3-panel w3-pale-yellow" style="font-style:italic">
        📋 Cochez une classe pour voir son agenda.
    </div>
    <div id="preview-content"></div>
</div>

<!-- ═══════════════════ FULL-DAY (all classes) ═════════════════ -->
<hr class="w3-border-teal" style="margin-top:30px">
<h3 class="w3-text-teal">📅 Agenda complet du <span id="fullDateLabel"><?= htmlspecialchars($today, ENT_QUOTES, 'UTF-8') ?></span></h3>
<div id="fullday-section" class="ajax-section">
    <p class="w3-text-grey" style="font-style:italic">Chargement…</p>
</div>

<!-- ═══════════════════ JAVASCRIPT ════════════════════════════════ -->
<script>
(function () {
    const CYCLE      = <?= json_encode($cycle, JSON_UNESCAPED_UNICODE) ?>;
    const previewBox = document.getElementById('preview-content');
    const previewPh  = document.getElementById('preview-placeholder');
    const previewSec = document.getElementById('preview-section');
    const fulldaySec = document.getElementById('fullday-section');
    const dateLabel  = document.getElementById('fullDateLabel');

    let timer = null;

    function getDate()    { return document.getElementById('dateInput').value; }
    function getClasses() {
        return [...document.querySelectorAll('input[name="cla[]"]:checked')].map(c => c.value);
    }

    /* ── load preview (selected classes only) ── */
    function loadPreview() {
        const ids = getClasses();
        const dt  = getDate();
        if (ids.length === 0) {
            previewBox.innerHTML = '';
            previewPh.style.display = 'block';
            return;
        }
        previewPh.style.display = 'none';
        
        const p = new URLSearchParams();
        p.append('cycle', CYCLE);
        p.append('date',  dt);
        p.append('mode',  'preview');
        ids.forEach(id => p.append('classIDs[]', id));
        
        previewSec.classList.add('loading');
        fetch('_agenda_preview.php', {
            method:'POST',
            headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
            body: p.toString()
        })
        .then(r => r.json())
        .then(data => {
            previewSec.classList.remove('loading');
            previewBox.innerHTML = data.html || '<p class="w3-text-grey">Aucun agenda.</p>';
        })
        .catch(err => {
            previewSec.classList.remove('loading');
            previewBox.innerHTML = '<p class="w3-text-red">⚠️ Erreur de chargement.</p>';
            console.error(err);
        });
    }

    /* ── load full-day (all cycle classes) ── */
    function loadFullday() {
        const dt = getDate();
        dateLabel.textContent = dt;
        
        const p = new URLSearchParams();
        p.append('cycle', CYCLE);
        p.append('date',  dt);
        p.append('mode',  'fullday');
        
        fulldaySec.classList.add('loading');
        fetch('_agenda_preview.php', {
            method:'POST',
            headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
            body: p.toString()
        })
        .then(r => r.json())
        .then(data => {
            fulldaySec.classList.remove('loading');
            fulldaySec.innerHTML = data.html || '<p class="w3-text-grey">Aucun agenda.</p>';
        })
        .catch(err => {
            fulldaySec.classList.remove('loading');
            fulldaySec.innerHTML = '<p class="w3-text-red">⚠️ Erreur de chargement.</p>';
            console.error(err);
        });
    }

    /* ── debounced trigger for both ── */
    window.triggerAll = function () {
        clearTimeout(timer);
        timer = setTimeout(() => { loadPreview(); loadFullday(); }, 280);
    };

    /* ── initial load on page ready ── */
    document.addEventListener('DOMContentLoaded', () => {
        loadFullday();
        loadPreview();
    });
})();
</script>

</body>
</html>
