<?php
ob_start();
session_start();

// Check if user is logged in
if (!isset($_SESSION['id'])) {
    ob_end_clean();
    echo json_encode(['html' => '<div class="w3-panel w3-pale-red w3-border"><p>❌ Not logged in.</p></div>']);
    exit;
}

include '_serveur.php';
ob_end_clean();
ob_start();

// _serveur.php already sent Content-Type: application/json

$userID  = intval($_POST['userID'] ?? 0);
$classIDs = $_POST['classIDs'] ?? [];
$date     = $_POST['date']     ?? '';

// Verify session user matches
if ($userID != $_SESSION['id']) {
    ob_end_clean();
    echo json_encode(['html' => '<div class="w3-panel w3-pale-red w3-border"><p>❌ Unauthorized.</p></div>']);
    exit;
}

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

$html = '';

// Add date header at the top
$html .= '<div style="background-color: #e8f4f8; padding: 12px 16px; border-radius: 4px; margin-bottom: 16px; border-left: 4px solid #0066cc;">';
$html .= '<p style="margin: 0; font-weight: bold; color: #0066cc; font-size: 14px;">📅 Date sélectionnée: ' . htmlspecialchars($date) . '</p>';
$html .= '</div>';

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;
}

$foundAny = false;

// For each class, verify professor has access and get ALL agenda entries for that class/date
foreach ($classIDs as $cid) {
    // SECURITY: Verify this professor teaches this class
    $verifySQL = "SELECT DISTINCT c.id, c.name FROM teachersSubjects ts
                  JOIN classes c ON ts.classID = c.id
                  WHERE ts.userID = ? AND ts.classID = ?
                  LIMIT 1";
    $verifyStmt = mysqli_prepare($link, $verifySQL);
    
    if (!$verifyStmt) {
        continue;
    }
    
    mysqli_stmt_bind_param($verifyStmt, "ii", $userID, $cid);
    mysqli_stmt_execute($verifyStmt);
    $verifyRes = mysqli_stmt_get_result($verifyStmt);
    $verifyRow = mysqli_fetch_assoc($verifyRes);
    
    if (!$verifyRow) {
        mysqli_stmt_close($verifyStmt);
        continue; // Skip if not authorized
    }
    $cname = htmlspecialchars($verifyRow['name'], ENT_QUOTES, 'UTF-8');
    mysqli_stmt_close($verifyStmt);

    // Get ALL agenda entries for this class on this date with user teaching status
    $agStmt = mysqli_prepare($link, "SELECT a.id, a.description, a.rtl, s.name AS subject, s.ordering,
                  IF(ts.userID IS NOT NULL, 1, 0) AS user_teaches_subject
                  FROM agenda a
                  JOIN subjects s ON a.subjectID=s.id
                  LEFT JOIN teachersSubjects ts ON a.classID = ts.classID 
                    AND a.subjectID = ts.subjectID AND ts.userID = ?
                  WHERE a.classID=? AND DATE(a.date)=?
                  ORDER BY s.ordering ASC, s.name ASC");
    
    if (!$agStmt) {
        continue;
    }
    
    mysqli_stmt_bind_param($agStmt, "iis", $userID, $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 . ' <span style="font-size:12px; color:#666;">(' . htmlspecialchars($date) . ')</span>' . $badge . '</h4>';
    
    if ($count > 0) {
        $foundAny = true;
        $html .= '<table class="w3-table w3-bordered w3-white" style="font-size:0.95em; margin-bottom: 0;"><tr class="w3-teal"><th>Matière</th><th>Description</th><th style="width:80px;text-align:center;">Action</th></tr>';
        while ($r = mysqli_fetch_assoc($agRes)) {
            $dir   = intval($r['rtl']) === 1 ? 'rtl' : 'ltr';
            $teaches = intval($r['user_teaches_subject']) === 1;
            
            $html .= '<tr>';
            $html .= '<td style="font-weight:bold; width:120px;">'.htmlspecialchars($r['subject'], ENT_QUOTES, 'UTF-8');
            
            // Show badge if this is not a subject the user teaches
            if (!$teaches) {
                $html .= ' <span style="font-size:9px; color:#999; font-weight:normal;">(Autre prof)</span>';
            }
            $html .= '</td>';
            
            $html .= '<td dir="'.$dir.'" style="text-align:'.($dir === 'rtl' ? 'right' : 'left').';">'.htmlspecialchars($r['description'], ENT_QUOTES, 'UTF-8').'</td>';
            
            // Show delete button ONLY if user teaches this subject
            if ($teaches) {
                $html .= '<td style="text-align:center"><form method="post" style="display:inline; margin:0;" onsubmit="return confirm(\'Êtes-vous sûr ?\');">';
                $html .= '<input type="hidden" name="delete" value="1">';
                $html .= '<input type="hidden" name="agendaID" value="'.intval($r['id']).'">';
                $html .= '<button type="submit" style="background-color:#f44336;color:white;padding:4px 8px;border:none;border-radius:3px;cursor:pointer;font-size:11px;">🗑️ Del</button>';
                $html .= '</form></td>';
            } else {
                $html .= '<td style="text-align:center"><span style="color:#999; font-size:11px;">-</span></td>';
            }
            
            $html .= '</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>';
    mysqli_stmt_close($agStmt);
}

if (empty($html) || !$foundAny) {
    if (empty($classIDs)) {
        $html = '<div class="w3-panel w3-pale-yellow w3-border"><p>📋 Sélectionnez au moins une classe.</p></div>';
    } else {
        $html = '<div style="background-color: #e8f4f8; padding: 12px 16px; border-radius: 4px; margin-bottom: 16px; border-left: 4px solid #0066cc;">';
        $html .= '<p style="margin: 0; font-weight: bold; color: #0066cc; font-size: 14px;">📅 Date sélectionnée: ' . htmlspecialchars($date) . '</p>';
        $html .= '</div>';
        $html .= '<div class="w3-panel w3-pale-yellow w3-border"><p>📭 Aucun agenda pour les classes sélectionnées à cette date.</p></div>';
    }
}

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