<?php
/**
 * Enhanced admin_exams.php - Class-by-Class Publishing Interface
 * This page allows admins to publish individual classes instead of whole exams
 */

session_start();

// Include database configuration
require_once 'config.php';

// Set current page for navigation
$currentPage = 'exams';

echo "<!DOCTYPE html>\n";
echo "<html lang='en'>\n";
echo "<head>\n";
echo "    <meta charset='UTF-8'>\n";
echo "    <meta name='viewport' content='width=device-width, initial-scale=1.0'>\n";
echo "    <title>Manage Exams - Class Publishing</title>\n";
echo "    <style>\n";
echo "        body { font-family: Arial, sans-serif; margin: 0; background: #f5f5f5; }\n";
echo "        .main-container { display: flex; min-height: 100vh; }\n";
echo "        .sidebar { width: 250px; background: #2c3e50; color: white; padding: 20px; }\n";
echo "        .content { flex: 1; padding: 20px; }\n";
echo "        .exam-card { background: white; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); margin-bottom: 20px; overflow: hidden; }\n";
echo "        .exam-header { background: #3498db; color: white; padding: 15px 20px; }\n";
echo "        .exam-body { padding: 20px; }\n";
echo "        .class-list { margin-top: 15px; }\n";
echo "        .class-item { background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 6px; margin: 10px 0; padding: 15px; display: flex; justify-content: space-between; align-items: center; }\n";
echo "        .class-info { flex: 1; }\n";
echo "        .class-name { font-weight: bold; color: #2c3e50; }\n";
echo "        .stream-name { color: #6c757d; font-size: 0.9rem; }\n";
echo "        .status-badge { padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: bold; }\n";
echo "        .status-draft { background: #ffc107; color: #856404; }\n";
echo "        .status-published { background: #28a745; color: white; }\n";
echo "        .publish-btn { background: #28a745; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; }\n";
echo "        .unpublish-btn { background: #dc3545; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; }\n";
echo "        .publish-btn:hover { background: #218838; }\n";
echo "        .unpublish-btn:hover { background: #c82333; }\n";
echo "        .publish-btn:disabled { background: #6c757d; cursor: not-allowed; }\n";
echo "        .success-message { background: #d4edda; color: #155724; padding: 15px; border-radius: 6px; margin: 15px 0; }\n";
echo "        .error-message { background: #f8d7da; color: #721c24; padding: 15px; border-radius: 6px; margin: 15px 0; }\n";
echo "        .section-title { color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; margin-bottom: 20px; }\n";
echo "    </style>\n";
echo "</head>\n";
echo "<body>\n";

// Check authentication and role
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("location: login.php");
    exit;
}

if ($_SESSION["role"] !== 1 && $_SESSION["role"] !== 0) { // Admin or Super Admin
    header("location: login.php");
    exit;
}

$user_id = $_SESSION["id"];
$current_user_school_id = $_SESSION["school_id"];
$username = $_SESSION["username"];

echo "<div class='main-container'>\n";
echo "<div class='sidebar'>\n";
echo "    <h2>Admin Panel</h2>\n";
echo "    <p>Logged in as: <strong>$username</strong></p>\n";
echo "    <nav>\n";
echo "        <a href='admin_dashboard.php' style='color: white; text-decoration: none; display: block; padding: 10px 0;'>Dashboard</a>\n";
echo "        <a href='admin_exams.php' style='color: white; text-decoration: none; display: block; padding: 10px 0; background: #34495e; border-radius: 4px;'>Manage Exams</a>\n";
echo "        <a href='logout.php' style='color: #ecf0f1; text-decoration: none; display: block; padding: 10px 0;'>Logout</a>\n";
echo "    </nav>\n";
echo "</div>\n";

echo "<div class='content'>\n";
echo "<h1 class='section-title'>📚 Manage Exams - Class Publishing</h1>\n";

$message = $_GET['message'] ?? '';
$message_type = $_GET['message_type'] ?? '';

if ($message) {
    $message_class = $message_type === 'success' ? 'success-message' : 'error-message';
    echo "<div class='$message_class'>$message</div>\n";
}

// Display success/error messages from AJAX calls
if (isset($_SESSION['ajax_message'])) {
    $message_class = $_SESSION['ajax_message_type'] === 'success' ? 'success-message' : 'error-message';
    echo "<div class='$message_class'>{$_SESSION['ajax_message']}</div>\n";
    unset($_SESSION['ajax_message'], $_SESSION['ajax_message_type']);
}

echo "<div class='exam-list'>\n";

// Get all exams for this school
$sql_exams = "SELECT exam_id, exam_name, exam_type, status, created_at FROM exams WHERE school_id = ? ORDER BY created_at DESC";
$stmt_exams = $conn->prepare($sql_exams);
$stmt_exams->bind_param("i", $current_user_school_id);
$stmt_exams->execute();
$result_exams = $stmt_exams->get_result();

while ($exam = $result_exams->fetch_assoc()) {
    echo "<div class='exam-card'>\n";
    echo "<div class='exam-header'>\n";
    echo "    <h3>{$exam['exam_name']}</h3>\n";
    echo "    <p>Type: {$exam['exam_type']} | Overall Status: <span class='status-badge status-" . strtolower($exam['status']) . "'>{$exam['status']}</span></p>\n";
    echo "</div>\n";
    
    echo "<div class='exam-body'>\n";
    
    // Get classes and their individual publishing status for this exam
    $class_sql = "
        SELECT DISTINCT
            c.class_id,
            c.class_name,
            st.stream_id,
            st.stream_name,
            COALESCE(ecs.status, 'Draft') as class_status,
            ecs.published_at,
            COUNT(DISTINCT cst.subject_id) as subject_count
        FROM classes c
        LEFT JOIN streams st ON st.school_id = c.school_id
        LEFT JOIN class_subject_teachers cst ON cst.class_id = c.class_id 
            AND cst.stream_id = st.stream_id 
            AND cst.school_id = ?
        LEFT JOIN exam_subjects es ON es.subject_id = cst.subject_id 
            AND es.exam_id = ?
        LEFT JOIN exam_class_status ecs ON ecs.exam_id = ?
            AND ecs.class_id = c.class_id 
            AND (ecs.stream_id = st.stream_id OR ecs.stream_id IS NULL)
        WHERE c.school_id = ?
        GROUP BY c.class_id, st.stream_id, st.stream_name
        HAVING subject_count > 0
        ORDER BY c.class_name, st.stream_name
    ";
    
    $stmt_class = $conn->prepare($class_sql);
    $stmt_class->bind_param("iiii", $current_user_school_id, $exam['exam_id'], $exam['exam_id'], $current_user_school_id);
    $stmt_class->execute();
    $result_class = $stmt_class->get_result();
    
    $class_count = $result_class->num_rows;
    
    if ($class_count > 0) {
        echo "<p><strong>$class_count Class" . ($class_count > 1 ? "es" : "") . " available for this exam:</strong></p>\n";
        echo "<div class='class-list'>\n";
        
        $published_count = 0;
        while ($class = $result_class->fetch_assoc()) {
            if ($class['class_status'] === 'Published') {
                $published_count++;
            }
            
            $is_published = $class['class_status'] === 'Published';
            
            echo "<div class='class-item'>\n";
            echo "<div class='class-info'>\n";
            echo "    <div class='class-name'>{$class['class_name']}</div>\n";
            echo "    <div class='stream-name'>Stream: {$class['stream_name']} | {$class['subject_count']} subjects</div>\n";
            if ($is_published && $class['published_at']) {
                echo "    <div style='font-size: 0.8rem; color: #6c757d; margin-top: 4px;'>Published: " . date('M j, Y g:i A', strtotime($class['published_at'])) . "</div>\n";
            }
            echo "</div>\n";
            
            echo "<div class='class-controls'>\n";
            echo "    <span class='status-badge status-{$class['class_status']}'>{$class['class_status']}</span>\n";
            
            if (!$is_published) {
                echo "    <button class='publish-btn' onclick='publishClass({$exam['exam_id']}, {$class['class_id']}, {$class['stream_id']})'>\n";
                echo "        <i class='fas fa-lock-open'></i> Publish Class\n";
                echo "    </button>\n";
            } else {
                echo "    <button class='unpublish-btn' onclick='unpublishClass({$exam['exam_id']}, {$class['class_id']}, {$class['stream_id']})'>\n";
                echo "        <i class='fas fa-lock'></i> Unpublish\n";
                echo "    </button>\n";
            }
            echo "</div>\n";
            echo "</div>\n";
        }
        
        echo "</div>\n";
        
        // Show summary
        if ($published_count > 0) {
            echo "<div style='background: #e8f5e8; padding: 15px; border-radius: 6px; margin-top: 15px;'>\n";
            echo "    <strong>📊 Summary:</strong> {$published_count} out of {$class_count} class" . ($class_count > 1 ? "es" : "") . " published\n";
            echo "</div>\n";
        }
        
    } else {
        echo "<p>No classes found for this exam or no teacher assignments.</p>\n";
    }
    
    echo "</div>\n";
    echo "</div>\n";
}

$stmt_exams->close();
$stmt_class->close();

echo "</div>\n";
echo "</div>\n";

echo "<script>\n";
echo "function publishClass(examId, classId, streamId) {\n";
echo "    if (!confirm('Publish this class for marks entry? Students and teachers will be able to view results.')) {\n";
echo "        return;\n";
echo "    }\n";
echo "    \n";
echo "    const formData = new FormData();\n";
echo "    formData.append('exam_id', examId);\n";
echo "    formData.append('class_id', classId);\n";
echo "    formData.append('stream_id', streamId || 0);\n";
echo "    formData.append('action', 'publish');\n";
echo "    \n";
echo "    fetch('ajax_manage_exam_class_status.php', {\n";
echo "        method: 'POST',\n";
echo "        body: formData\n";
echo "    })\n";
echo "    .then(response => response.json())\n";
echo "    .then(data => {\n";
echo "        if (data.success) {\n";
echo "            alert('Class published successfully!');\n";
echo "            location.reload();\n";
echo "        } else {\n";
echo "            alert('Error: ' + data.message);\n";
echo "        }\n";
echo "    })\n";
echo "    .catch(error => {\n";
echo "        console.error('Error:', error);\n";
echo "        alert('An error occurred. Please try again.');\n";
echo "    });\n";
echo "}\n";

echo "function unpublishClass(examId, classId, streamId) {\n";
echo "    if (!confirm('Unpublish this class? Marks entry will be enabled again.')) {\n";
echo "        return;\n";
echo "    }\n";
echo "    \n";
echo "    const formData = new FormData();\n";
echo "    formData.append('exam_id', examId);\n";
echo "    formData.append('class_id', classId);\n";
echo "    formData.append('stream_id', streamId || 0);\n";
echo "    formData.append('action', 'unpublish');\n";
echo "    \n";
echo "    fetch('ajax_manage_exam_class_status.php', {\n";
echo "        method: 'POST',\n";
echo "        body: formData\n";
echo "    })\n";
echo "    .then(response => response.json())\n";
echo "    .then(data => {\n";
echo "        if (data.success) {\n";
echo "            alert('Class unpublished successfully!');\n";
echo "            location.reload();\n";
echo "        } else {\n";
echo "            alert('Error: ' + data.message);\n";
echo "        }\n";
echo "    })\n";
echo "    .catch(error => {\n";
echo "        console.error('Error:', error);\n";
echo "        alert('An error occurred. Please try again.');\n";
echo "    });\n";
echo "}\n";
echo "</script>\n";

echo "</body>\n";
echo "</html>\n";

$conn->close();
?>