<?php
/**
 * AJAX Handler for Admin Exam Publishing Management
 * Handles approving, rejecting, and managing exam publishing workflow
 */

session_start();
require_once 'config.php';

// Check if user is logged in and is an admin
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || 
    !isset($_SESSION['id']) || !isset($_SESSION['role']) || 
    $_SESSION['role'] != ROLE_ADMIN || !isset($_SESSION['school_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

$user_id = $_SESSION['id'];
$school_id = $_SESSION['school_id'];

// Handle different actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'get_pending_reviews':
            getPendingReviews($school_id, $conn);
            break;
            
        case 'approve_exam':
            $exam_id = intval($_POST['exam_id'] ?? 0);
            $admin_notes = trim($_POST['admin_notes'] ?? '');
            
            if (!$exam_id) {
                echo json_encode(['success' => false, 'message' => 'Missing exam ID']);
                exit;
            }
            
            approveExam($exam_id, $admin_notes, $user_id, $school_id, $conn);
            break;
            
        case 'reject_exam':
            $exam_id = intval($_POST['exam_id'] ?? 0);
            $admin_notes = trim($_POST['admin_notes'] ?? '');
            $teacher_user_id = intval($_POST['teacher_user_id'] ?? 0);
            
            if (!$exam_id || !$teacher_user_id) {
                echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
                exit;
            }
            
            rejectExam($exam_id, $admin_notes, $user_id, $school_id, $conn);
            break;
            
        case 'get_exam_details':
            $exam_id = intval($_POST['exam_id'] ?? 0);
            
            if (!$exam_id) {
                echo json_encode(['success' => false, 'message' => 'Missing exam ID']);
                exit;
            }
            
            getExamDetails($exam_id, $school_id, $conn);
            break;
            
        case 'get_publishing_history':
            $exam_id = intval($_POST['exam_id'] ?? 0);
            
            if (!$exam_id) {
                echo json_encode(['success' => false, 'message' => 'Missing exam ID']);
                exit;
            }
            
            getPublishingHistory($exam_id, $school_id, $conn);
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}

/**
 * Get all exams pending review
 */
function getPendingReviews($school_id, $conn) {
    try {
        $sql = "SELECT 
                    e.exam_id,
                    e.exam_name,
                    e.term,
                    e.year,
                    e.exam_type,
                    e.status,
                    e.teacher_submitted_at,
                    u.username as teacher_name,
                    c.class_name,
                    COUNT(es.subject_id) as subject_count,
                    GROUP_CONCAT(DISTINCT s.subject_name ORDER BY s.subject_name SEPARATOR ', ') AS subjects_list,
                    e.updated_by as teacher_user_id
                FROM exams e
                LEFT JOIN users u ON e.updated_by = u.id
                LEFT JOIN exam_classes ec ON e.exam_id = ec.exam_id
                LEFT JOIN classes c ON ec.class_id = c.class_id
                LEFT JOIN exam_subjects es ON e.exam_id = es.exam_id
                LEFT JOIN subjects s ON es.subject_id = s.subject_id
                WHERE e.school_id = ? 
                AND e.status = 'Pending Review'
                GROUP BY e.exam_id, e.exam_name, e.term, e.year, e.exam_type, e.status, e.teacher_submitted_at, u.username, c.class_name, e.updated_by
                ORDER BY e.exam_id ASC";
        
        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            throw new Exception('Database error: ' . $conn->error);
        }
        
        $stmt->bind_param("i", $school_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $pending_exams = [];
        while ($row = $result->fetch_assoc()) {
            $pending_exams[] = [
                'exam_id' => $row['exam_id'],
                'exam_name' => $row['exam_name'],
                'term' => $row['term'],
                'year' => $row['year'],
                'exam_type' => $row['exam_type'],
                'teacher_name' => $row['teacher_name'] ?? 'Unknown',
                'class_name' => $row['class_name'] ?? 'Multiple Classes',
                'subjects' => $row['subjects_list'] ?? '',
                'subject_count' => $row['subject_count'],
                'submitted_at' => $row['teacher_submitted_at'] ?? 'Not submitted',
                'teacher_user_id' => $row['teacher_user_id'],
                'feedback' => ''
            ];
        }
        
        $stmt->close();
        
        echo json_encode([
            'success' => true, 
            'data' => $pending_exams,
            'count' => count($pending_exams)
        ]);
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false, 
            'message' => 'Error fetching pending reviews: ' . $e->getMessage()
        ]);
    }
}

/**
 * Approve an exam and publish it
 */
function approveExam($exam_id, $admin_notes, $admin_id, $school_id, $conn) {
    try {
        $conn->begin_transaction();
        
        // First verify the exam is pending review
        $stmt = $conn->prepare("SELECT * FROM exams WHERE exam_id = ? AND school_id = ? AND status = 'Pending Review'");
        $stmt->bind_param("ii", $exam_id, $school_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $exam = $result->fetch_assoc();
        $stmt->close();
        
        if (!$exam) {
            throw new Exception('Exam not found or not in pending review status');
        }
        
        // Update exam status to Published
        $stmt = $conn->prepare("UPDATE exams 
            SET status = 'Published', 
                admin_reviewed_at = NOW(),
                admin_reviewer_id = ?,
                review_feedback = ?,
                updated_by = ?,
                updated_at = NOW()
            WHERE exam_id = ? AND school_id = ?");
        $stmt->bind_param("isiii", $admin_id, $admin_notes, $admin_id, $exam_id, $school_id);
        $stmt->execute();
        $stmt->close();
        
        // Lock all subjects in this exam for marks entry
        $stmt_lock = $conn->prepare("UPDATE exam_subjects SET status = 'Published' WHERE exam_id = ?");
        $stmt_lock->bind_param("i", $exam_id);
        $stmt_lock->execute();
        $stmt_lock->close();
        
        // Log the approval action
        logPublishingAction($exam_id, 'approved', $admin_id, $admin_notes, $conn);
        
        $conn->commit();
        
        echo json_encode([
            'success' => true, 
            'message' => 'Exam approved and published successfully. All subjects are now locked for marks entry.',
            'action' => 'approved'
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode([
            'success' => false, 
            'message' => 'Error approving exam: ' . $e->getMessage()
        ]);
    }
}

/**
 * Reject an exam and return to draft status
 */
function rejectExam($exam_id, $admin_notes, $admin_id, $school_id, $conn) {
    try {
        $conn->begin_transaction();
        
        // First verify the exam is pending review
        $stmt = $conn->prepare("SELECT * FROM exams WHERE exam_id = ? AND school_id = ? AND status = 'Pending Review'");
        $stmt->bind_param("ii", $exam_id, $school_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $exam = $result->fetch_assoc();
        $stmt->close();
        
        if (!$exam) {
            throw new Exception('Exam not found or not in pending review status');
        }
        
        // Update exam status back to Draft
        $stmt = $conn->prepare("UPDATE exams 
            SET status = 'Draft',
                admin_reviewed_at = NOW(),
                admin_reviewer_id = ?,
                review_feedback = ?,
                updated_by = ?,
                updated_at = NOW(),
                teacher_submitted_at = NULL
            WHERE exam_id = ? AND school_id = ?");
        $stmt->bind_param("isiii", $admin_id, $admin_notes, $admin_id, $exam_id, $school_id);
        $stmt->execute();
        $stmt->close();
        
        // Unlock all subjects in this exam for marks entry
        $stmt_unlock = $conn->prepare("UPDATE exam_subjects SET status = 'Draft' WHERE exam_id = ?");
        $stmt_unlock->bind_param("i", $exam_id);
        $stmt_unlock->execute();
        $stmt_unlock->close();
        
        // Log the rejection action
        logPublishingAction($exam_id, 'rejected', $admin_id, $admin_notes, $conn);
        
        $conn->commit();
        
        echo json_encode([
            'success' => true, 
            'message' => 'Exam rejected and returned to draft status. Teachers can now make changes.',
            'action' => 'rejected'
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode([
            'success' => false, 
            'message' => 'Error rejecting exam: ' . $e->getMessage()
        ]);
    }
}

/**
 * Get detailed information about an exam
 */
function getExamDetails($exam_id, $school_id, $conn) {
    try {
        // Get basic exam information
        $stmt = $conn->prepare("SELECT 
            e.*, 
            u.username as teacher_name,
            u2.username as reviewer_name
        FROM exams e
        LEFT JOIN users u ON e.created_by = u.id
        LEFT JOIN users u2 ON e.admin_reviewer_id = u2.id
        WHERE e.exam_id = ? AND e.school_id = ?");
        
        if (!$stmt) {
            throw new Exception('Database error: ' . $conn->error);
        }
        
        $stmt->bind_param("ii", $exam_id, $school_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $exam = $result->fetch_assoc();
        $stmt->close();
        
        if (!$exam) {
            throw new Exception('Exam not found');
        }
        
        // Get affected classes
        $stmt_classes = $conn->prepare("SELECT c.class_name, c.class_id
            FROM exam_classes ec
            INNER JOIN classes c ON ec.class_id = c.class_id
            WHERE ec.exam_id = ?");
        $stmt_classes->bind_param("i", $exam_id);
        $stmt_classes->execute();
        $result_classes = $stmt_classes->get_result();
        $classes = [];
        while ($row = $result_classes->fetch_assoc()) {
            $classes[] = $row;
        }
        $stmt_classes->close();
        
        // Get affected subjects
        $stmt_subjects = $conn->prepare("SELECT s.subject_name, s.subject_id
            FROM exam_subjects es
            INNER JOIN subjects s ON es.subject_id = s.subject_id
            WHERE es.exam_id = ?");
        $stmt_subjects->bind_param("i", $exam_id);
        $stmt_subjects->execute();
        $result_subjects = $stmt_subjects->get_result();
        $subjects = [];
        while ($row = $result_subjects->fetch_assoc()) {
            $subjects[] = $row;
        }
        $stmt_subjects->close();
        
        // Get marks entry status for each subject
        $marks_status = [];
        foreach ($subjects as $subject) {
            $stmt_marks = $conn->prepare("
                SELECT 
                    COUNT(DISTINCT se.user_id) as total_students,
                    COUNT(DISTINCT CASE WHEN m.student_id IS NOT NULL THEN se.user_id END) as students_with_marks
                FROM student_enrollment se
                LEFT JOIN marks m ON se.user_id = m.student_id AND m.exam_id = ? AND m.subject_id = ?
                WHERE se.class_id IN (SELECT class_id FROM exam_classes WHERE exam_id = ?)
            ");
            $stmt_marks->bind_param("iii", $exam_id, $subject['subject_id'], $exam_id);
            $stmt_marks->execute();
            $result_marks = $stmt_marks->get_result();
            $marks_data = $result_marks->fetch_assoc();
            $stmt_marks->close();
            
            $marks_status[] = [
                'subject_id' => $subject['subject_id'],
                'subject_name' => $subject['subject_name'],
                'total_students' => intval($marks_data['total_students']),
                'students_with_marks' => intval($marks_data['students_with_marks']),
                'completion_percentage' => $marks_data['total_students'] > 0 ? 
                    round(($marks_data['students_with_marks'] / $marks_data['total_students']) * 100, 1) : 0
            ];
        }
        
        echo json_encode([
            'success' => true,
            'exam' => [
                'exam_id' => $exam['exam_id'],
                'exam_name' => $exam['exam_name'],
                'exam_type' => $exam['exam_type'],
                'term' => $exam['term'],
                'year' => $exam['year'],
                'status' => $exam['status'],
                'created_at' => $exam['created_at'],
                'updated_at' => $exam['updated_at'],
                'teacher_name' => $exam['teacher_name'],
                'reviewer_name' => $exam['reviewer_name'],
                'teacher_submitted_at' => $exam['teacher_submitted_at'],
                'admin_reviewed_at' => $exam['admin_reviewed_at'],
                'feedback' => $exam['review_feedback'],
                'classes' => $classes,
                'subjects' => $marks_status
            ]
        ]);
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false, 
            'message' => 'Error fetching exam details: ' . $e->getMessage()
        ]);
    }
}

/**
 * Get publishing history for an exam
 */
function getPublishingHistory($exam_id, $school_id, $conn) {
    try {
        $sql = "SELECT 
            ehp.*,
            u.username as actor_name
        FROM exam_history_publishing ehp
        LEFT JOIN users u ON ehp.user_id = u.id
        WHERE ehp.exam_id = ? AND ehp.school_id = ?
        ORDER BY ehp.created_at DESC";
        
        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            throw new Exception('Database error: ' . $conn->error);
        }
        
        $stmt->bind_param("ii", $exam_id, $school_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $history = [];
        while ($row = $result->fetch_assoc()) {
            $history[] = [
                'action' => $row['action'],
                'actor_name' => $row['actor_name'] ?? 'Unknown',
                'notes' => $row['notes'],
                'created_at' => $row['created_at']
            ];
        }
        
        $stmt->close();
        
        echo json_encode([
            'success' => true,
            'history' => $history
        ]);
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false, 
            'message' => 'Error fetching publishing history: ' . $e->getMessage()
        ]);
    }
}

/**
 * Log publishing action for audit trail
 */
function logPublishingAction($exam_id, $action, $user_id, $notes, $conn) {
    try {
        $stmt = $conn->prepare("INSERT INTO exam_history_publishing 
            (exam_id, school_id, user_id, action, notes, created_at) 
            VALUES (?, ?, ?, ?, ?, NOW())");
        
        if (!$stmt) {
            throw new Exception('Database error: ' . $conn->error);
        }
        
        $school_id = $_SESSION['school_id'];
        $stmt->bind_param("iiiss", $exam_id, $school_id, $user_id, $action, $notes);
        $stmt->execute();
        $stmt->close();
        
    } catch (Exception $e) {
        // Log error but don't fail the main operation
        error_log("Failed to log publishing action: " . $e->getMessage());
    }
}
?>