<?php 
session_start();

// Validate session
if (!isset($_SESSION['id'])) {
    die('<div class="w3-panel w3-pale-red"><p>❌ You must be logged in.</p></div>');
}

$id = $_SESSION['id'];
$today = date("Y-m-d");
?>
<!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; }
body { width:90%; margin: auto; }
.status-message { margin: 15px 0; padding: 12px; border-radius: 4px; }
.status-success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
.status-warning { background-color: #fff3cd; color: #856404; border: 1px solid #ffeaa7; }
.status-error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
.agenda-card { margin: 15px 0; }
.agenda-item { 
    padding: 12px; 
    margin: 8px 0; 
    border-left: 4px solid #008CBA; 
    background-color: #f9f9f9;
    border-radius: 3px;
}
.delete-btn { 
    background-color: #f44336; 
    color: white; 
    padding: 6px 12px; 
    cursor: pointer; 
    border: none; 
    border-radius: 3px;
    font-size: 12px;
}
.delete-btn:hover { background-color: #da190b; }
.form-group { margin-bottom: 15px; }
.ajax-section { transition: opacity 0.2s; }
.ajax-section.loading { opacity: 0.35; pointer-events: none; }
</style>
</head>
<body>

<div class="w3-card-3 w3-padding">
<h2 class="w3-text-teal">📝 Écrire Agenda</h2>

<form method="post" action="" accept-charset="UTF-8" id="agendaForm">
<?php
include 'header.php';
include "_serveur.php";

// Set UTF-8 for database connection
mysqli_set_charset($link, "utf8mb4");

// --- Get classes and subjects for this professor ---
$sql = "SELECT classes.id AS classID, classes.name AS className, subjects.id AS subjectID, subjects.name AS subjectName
        FROM teachersSubjects
        JOIN subjects ON teachersSubjects.subjectID = subjects.id
        JOIN classes ON teachersSubjects.classID = classes.id
        WHERE teachersSubjects.userID = ?
        ORDER BY classes.id, subjects.ordering";

$stmt = mysqli_prepare($link, "SELECT classes.id AS classID, classes.name AS className
        FROM teachersSubjects
        JOIN classes ON teachersSubjects.classID = classes.id
        WHERE teachersSubjects.userID = ?
        GROUP BY classes.id
        ORDER BY classes.id");
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);

echo '<div class="form-group">';
echo '<label class="w3-text-teal"><strong>Classe - Matière :</strong></label><br>';
$assignmentCount = 0;
$classesData = [];
while ($row = mysqli_fetch_assoc($res)) {
    $classID = $row['classID'];
    $className = $row['className'];
    $classesData[] = ['id' => $classID, 'name' => $className];
    $assignmentCount++;
    echo '<input class="w3-check w3-pale-blue" type="checkbox" name="cla[]" value="'.$classID.'" onchange="updateSubjects(); triggerPreview()">
          <label>'.htmlspecialchars($className, ENT_QUOTES, 'UTF-8').'</label><br>';
}
if ($assignmentCount == 0) {
    echo '<p class="w3-text-grey"><i>❌ No classes assigned to you.</i></p>';
}
echo '</div>';

mysqli_stmt_close($stmt);
?>

<!-- ✅ SUBJECT DROPDOWN - Select ONE subject from teachersSubjects -->
<div class="form-group">
<label class="w3-text-teal"><strong>Matière :</strong></label><br>
<select name="subj" id="subjectSelect" class="w3-input w3-border w3-pale-blue" required disabled onchange="triggerPreview()">
    <option value="">-- Sélectionnez une classe d'abord --</option>
</select>
</div>

<div class="form-group">
<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>
</div>

<div class="form-group">
<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="<?= date("Y-m-d") ?>" required onchange="triggerPreview()" />
</div>

<div class="form-group">
<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>
</div>

<p>
  <input type="submit" name="envoyer" class="w3-button w3-teal w3-large" value="📤 Envoyer">
</p>

</form>
</div>

<?php
/* ═══════════════════ DELETE HANDLER ═════════════════════════════ */
if (isset($_POST['delete']) && isset($_POST['agendaID'])) {
    $agendaID = intval($_POST['agendaID']);
    
    if ($agendaID > 0) {
        // Verify this agenda belongs to this professor before deleting
        $verifySQL = "SELECT a.id FROM agenda a
                      JOIN teachersSubjects ts ON a.classID = ts.classID AND a.subjectID = ts.subjectID
                      WHERE a.id = ? AND ts.userID = ?";
        
        $verifyStmt = mysqli_prepare($link, $verifySQL);
        mysqli_stmt_bind_param($verifyStmt, "ii", $agendaID, $id);
        mysqli_stmt_execute($verifyStmt);
        $verifyRes = mysqli_stmt_get_result($verifyStmt);
        
        if (mysqli_num_rows($verifyRes) > 0) {
            $delStmt = mysqli_prepare($link, "DELETE FROM agenda WHERE id=?");
            mysqli_stmt_bind_param($delStmt, "i", $agendaID);
            if (mysqli_stmt_execute($delStmt)) {
                echo '<div class="w3-panel w3-pale-green w3-border status-message status-success">
                        <p>✅ Agenda supprimé avec succès.</p>
                      </div>';
            } else {
                echo '<div class="w3-panel w3-pale-red w3-border status-message status-error">
                        <p>❌ Erreur lors de la suppression.</p>
                      </div>';
            }
            mysqli_stmt_close($delStmt);
        } else {
            echo '<div class="w3-panel w3-pale-red w3-border status-message status-error">
                    <p>❌ Vous n\'avez pas la permission de supprimer cet agenda.</p>
                  </div>';
        }
        mysqli_stmt_close($verifyStmt);
    }
}

/* ═══════════════════ FORM SUBMISSION HANDLER ═════════════════════ */
if (isset($_POST['envoyer'])) {
    $cont1 = $_POST['cla'] ?? [];
    $subjectID = intval($_POST['subj'] ?? 0);  // ✅ Get selected subject from dropdown
    $rtl = intval($_POST['rtl'] ?? 0);
    $date = $_POST['date'] ?? '';
    $agenda = trim($_POST['agenda'] ?? '');

    // Validation
    if (empty($agenda)) {
        echo '<div class="w3-panel w3-pale-red w3-border status-message status-error">
                <p>❌ L\'agenda est obligatoire.</p>
              </div>';
    } elseif (empty($cont1)) {
        echo '<div class="w3-panel w3-pale-red w3-border status-message status-error">
                <p>❌ Veuillez sélectionner au moins une classe.</p>
              </div>';
    } elseif (empty($date)) {
        echo '<div class="w3-panel w3-pale-red w3-border status-message status-error">
                <p>❌ La date est obligatoire.</p>
              </div>';
    } elseif ($subjectID <= 0) {
        echo '<div class="w3-panel w3-pale-red w3-border status-message status-error">
                <p>❌ Veuillez sélectionner une matière.</p>
              </div>';
    } else {
        $successCount = 0;
        $existsCount = 0;

        foreach ($cont1 as $val) {
            $classID = intval($val);

            // ✅ Verify teacher teaches this subject in this class (fixed: use 1 instead of non-existent id column)
            $verifySQL = "SELECT 1 FROM teachersSubjects 
                       WHERE userID = ? AND classID = ? AND subjectID = ?";
            $verifyStmt = mysqli_prepare($link, $verifySQL);
            mysqli_stmt_bind_param($verifyStmt, "iii", $id, $classID, $subjectID);
            mysqli_stmt_execute($verifyStmt);
            $verifyRes = mysqli_stmt_get_result($verifyStmt);
            
            if (mysqli_num_rows($verifyRes) == 0) {
                mysqli_stmt_close($verifyStmt);
                continue;  // Skip if teacher doesn't teach this subject in this class
            }
            mysqli_stmt_close($verifyStmt);

            // Check if already exists for this class/subject/date
            $checkSQL = "SELECT id FROM agenda WHERE classID=? AND subjectID=? AND DATE(date)=?";
            $checkStmt = mysqli_prepare($link, $checkSQL);
            mysqli_stmt_bind_param($checkStmt, "iis", $classID, $subjectID, $date);
            mysqli_stmt_execute($checkStmt);
            $resCheck = mysqli_stmt_get_result($checkStmt);

            if (mysqli_num_rows($resCheck) == 0) {
                // Insert securely for selected subject only
                $insertSQL = "INSERT INTO agenda (classID, subjectID, date, description, rtl)
                              VALUES (?, ?, ?, ?, ?)";
                $insertStmt = mysqli_prepare($link, $insertSQL);
                mysqli_stmt_bind_param($insertStmt, "iissi", $classID, $subjectID, $date, $agenda, $rtl);
                if (mysqli_stmt_execute($insertStmt)) {
                    $successCount++;
                }
                mysqli_stmt_close($insertStmt);
            } else {
                $existsCount++;
            }
            mysqli_stmt_close($checkStmt);
        }

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

<!-- ═══════════════════ LIVE PREVIEW ════════════════════════════ -->
<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 w3-border" style="font-style:italic; padding: 16px;">
        📋 Cochez une classe pour voir son agenda du jour.
    </div>
    <div id="preview-content"></div>
</div>

<!-- ═══════════════════ JAVASCRIPT ════════════════════════════════ -->
<script>
// ✅ Load subjects from teachersSubjects table
const classSubjectsData = <?php
// Get ALL subjects for ALL classes THIS teacher teaches
$allSubjectsSQL = "SELECT DISTINCT 
                    ts.classID, 
                    ts.subjectID, 
                    s.name as subjectName
                  FROM teachersSubjects ts
                  JOIN subjects s ON ts.subjectID = s.id
                  WHERE ts.userID = ?
                  ORDER BY ts.classID, s.name";

$allSubjectsStmt = mysqli_prepare($link, $allSubjectsSQL);
mysqli_stmt_bind_param($allSubjectsStmt, "i", $id);
mysqli_stmt_execute($allSubjectsStmt);
$allSubjectsRes = mysqli_stmt_get_result($allSubjectsStmt);

$classSubjectMapping = [];
while ($row = mysqli_fetch_assoc($allSubjectsRes)) {
    $classID = $row['classID'];
    if (!isset($classSubjectMapping[$classID])) {
        $classSubjectMapping[$classID] = [];
    }
    $classSubjectMapping[$classID][] = [
        'id' => $row['subjectID'],
        'name' => $row['subjectName']
    ];
}
mysqli_stmt_close($allSubjectsStmt);

echo json_encode($classSubjectMapping);
?>;

// ✅ Update subjects when class is selected
function updateSubjects() {
    const selectedClasses = [...document.querySelectorAll('input[name="cla[]"]:checked')].map(c => c.value);
    const subjectSelect = document.getElementById('subjectSelect');
    
    if (selectedClasses.length === 0) {
        subjectSelect.disabled = true;
        subjectSelect.innerHTML = '<option value="">-- Sélectionnez une classe d\'abord --</option>';
        return;
    }
    
    subjectSelect.disabled = false;
    
    // Collect all unique subjects from selected classes
    const allSubjects = new Map();
    
    selectedClasses.forEach(classID => {
        if (classSubjectsData[classID]) {
            classSubjectsData[classID].forEach(subject => {
                if (!allSubjects.has(subject.id)) {
                    allSubjects.set(subject.id, subject.name);
                }
            });
        }
    });
    
    // Build dropdown with YOUR subjects only
    let html = '<option value="">-- Sélectionnez une matière --</option>';
    allSubjects.forEach((name, id) => {
        html += `<option value="${id}">${name}</option>`;
    });
    
    subjectSelect.innerHTML = html;
}

(function () {
    const userID = <?= json_encode($id, JSON_UNESCAPED_UNICODE) ?>;
    const previewBox = document.getElementById('preview-content');
    const previewPh  = document.getElementById('preview-placeholder');
    const previewSec = document.getElementById('preview-section');

    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 classIDs = getClasses();
        const dt  = getDate();
        if (classIDs.length === 0) {
            previewBox.innerHTML = '';
            previewPh.style.display = 'block';
            return;
        }
        previewPh.style.display = 'none';
        
        const p = new URLSearchParams();
        p.append('userID', userID);
        p.append('date',  dt);
        classIDs.forEach(id => p.append('classIDs[]', id));
        
        previewSec.classList.add('loading');
        fetch('_agenda_preview_prof.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);
        });
    }

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

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

</body>
</html>
