<?php
// admin_exams_api.php - API endpoints for exam management

// Start session first
session_start();

// Include database configuration
if (file_exists('config.php')) {
    require_once 'config.php';
} elseif (file_exists('db.php')) {
    require_once 'db.php';
} else {
    // Basic database connection setup - user should modify as needed
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "report_system";
    
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    if ($conn->connect_error) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Database connection failed: ' . $conn->connect_error]);
        exit;
    }
}

// Include functions if available
if (file_exists('functions.php')) {
    require_once 'functions.php';
}

// Define role constants if not already defined
if (!defined('ROLE_SUPER_ADMIN')) {
    define('ROLE_SUPER_ADMIN', 1);
    define('ROLE_ADMIN', 2);
    define('ROLE_TEACHER', 3);
    define('ROLE_STUDENT', 4);
    define('ROLE_PARENT', 5);
    define('ROLE_STAFF', 6);
}

// Temporary: Skip authentication for debugging
// TODO: Re-enable authentication after testing
error_log("API Debug - Skipping authentication for testing");

/*
// Debug session data
error_log("API Debug - Session data: " . print_r($_SESSION, true));
error_log("API Debug - Session ID: " . session_id());

// Verify authentication
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role_code'])) {
    error_log("API Debug - Authentication failed. user_id: " . (isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 'NOT SET') . ", role_code: " . (isset($_SESSION['role_code']) ? $_SESSION['role_code'] : 'NOT SET'));
    http_response_code(401);
    echo json_encode([
        'success' => false, 
        'message' => 'Authentication required',
        'debug' => [
            'session_id' => session_id(),
            'user_id_set' => isset($_SESSION['user_id']),
            'role_code_set' => isset($_SESSION['role_code']),
            'session_data' => $_SESSION
        ]
    ]);
    exit;
}

$user_id = $_SESSION['user_id'];
$user_role_code = $_SESSION['role_code'];
$current_user_school_id = $_SESSION['school_id'] ?? null;

// Verify admin privileges
if (!in_array($user_role_code, [ROLE_SUPER_ADMIN, ROLE_ADMIN])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Insufficient privileges']);
    exit;
}
*/

// Temporary hardcoded values for testing
$user_id = 1;
$user_role_code = 1; // ROLE_SUPER_ADMIN
$current_user_school_id = 1; // Assuming school_id = 1

// Verify database connection
if (!isset($conn) || !($conn instanceof mysqli)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection not available']);
    exit;
}

// Get action parameter
$action = $_GET['action'] ?? '';

header('Content-Type: application/json');

try {
    switch ($action) {
        case 'get_exam_results_status':
            handleGetExamResultsStatus();
            break;
            
        default:
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid action specified']);
            break;
    }
} catch (Exception $e) {
    error_log("Admin Exams API Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal server error: ' . $e->getMessage()]);
}

function handleGetExamResultsStatus() {
    global $conn, $current_user_school_id;
    
    try {
        error_log("API Debug - handleGetExamResultsStatus started");
        
        $exam_id = $_GET['exam_id'] ?? '';
        $class_id = $_GET['class_id'] ?? '';
        $stream_id = $_GET['stream_id'] ?? '';
        
        error_log("API Debug - Parameters: exam_id=$exam_id, class_id=$class_id, stream_id=$stream_id");
        
        // Validate required parameters
        if (empty($exam_id) || empty($class_id) || empty($stream_id)) {
            echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
            return;
        }
        
        // Check if database connection exists
        if (!isset($conn) || !($conn instanceof mysqli)) {
            echo json_encode(['success' => false, 'message' => 'Database connection not available']);
            return;
        }
        
        error_log("API Debug - Database connection OK");
        
        // Verify exam exists (skip school_id check for now)
        $exam_check_sql = "SELECT exam_id, term, year, school_id FROM exams WHERE exam_id = ?";
        $exam_stmt = $conn->prepare($exam_check_sql);
        
        if (!$exam_stmt) {
            error_log("API Debug - Exam prepare failed: " . $conn->error);
            echo json_encode(['success' => false, 'message' => 'Database prepare error: ' . $conn->error]);
            return;
        }
        
        $exam_stmt->bind_param("i", $exam_id);
        $exam_stmt->execute();
        $exam_result = $exam_stmt->get_result();
        
        if ($exam_result->num_rows === 0) {
            error_log("API Debug - Exam not found: $exam_id");
            echo json_encode(['success' => false, 'message' => 'Exam not found']);
            $exam_stmt->close();
            return;
        }
        
        $exam_data = $exam_result->fetch_assoc();
        $current_user_school_id = $exam_data['school_id']; // Use exam's school_id
        $exam_stmt->close();
        
        error_log("API Debug - Exam found: " . print_r($exam_data, true));
        
        // Get subjects for this exam
        $subjects_sql = "SELECT DISTINCT es.subject_id, s.subject_name 
                         FROM exam_subjects es 
                         JOIN subjects s ON es.subject_id = s.subject_id 
                         WHERE es.exam_id = ? AND s.school_id = ?
                         ORDER BY s.subject_name";
        
        $subjects_stmt = $conn->prepare($subjects_sql);
        if (!$subjects_stmt) {
            error_log("API Debug - Subjects prepare failed: " . $conn->error);
            echo json_encode(['success' => false, 'message' => 'Database prepare error for subjects: ' . $conn->error]);
            return;
        }
        
        $subjects_stmt->bind_param("ii", $exam_id, $current_user_school_id);
        $subjects_stmt->execute();
        $subjects_result = $subjects_stmt->get_result();
        
        $subjects = [];
        while ($row = $subjects_result->fetch_assoc()) {
            $subjects[] = $row;
        }
        $subjects_stmt->close();
        
        error_log("API Debug - Found " . count($subjects) . " subjects");
        
        if (empty($subjects)) {
            echo json_encode(['success' => false, 'message' => 'No subjects found for this exam']);
            return;
        }
        
        // Get total students enrolled in this class and stream
        $students_sql = "SELECT DISTINCT u.id as student_id, u.username, u.ADM, u.email
                         FROM users u 
                         WHERE u.stream_id = ? 
                         AND u.class_id = ? 
                         AND u.school_id = ? 
                         AND u.role = ? 
                         AND u.status = 'active'";
        
        $student_role_code = 3; // ROLE_STUDENT hardcoded
        $students_stmt = $conn->prepare($students_sql);
        if (!$students_stmt) {
            error_log("API Debug - Students prepare failed: " . $conn->error);
            echo json_encode(['success' => false, 'message' => 'Database prepare error for students: ' . $conn->error]);
            return;
        }
        
        $students_stmt->bind_param("iiii", $stream_id, $class_id, $current_user_school_id, $student_role_code);
        $students_stmt->execute();
        $students_result = $students_stmt->get_result();
        
        $total_students = $students_result->num_rows;
        $students_list = [];
        while ($row = $students_result->fetch_assoc()) {
            $students_list[] = $row;
        }
        $students_stmt->close();
        
        error_log("API Debug - Found $total_students students");
        
        if ($total_students === 0) {
            echo json_encode(['success' => false, 'message' => 'No students found in this class and stream']);
            return;
        }
        
        // For each subject, count how many students have marks
        $results = [];
        
        foreach ($subjects as $subject) {
            $subject_id = $subject['subject_id'];
            $subject_name = $subject['subject_name'];
            
            error_log("API Debug - Processing subject: $subject_name (ID: $subject_id)");
            
            // Count students with marks for this subject and exam
            $marks_sql = "SELECT COUNT(DISTINCT m.student_id) as students_with_marks
                          FROM marks m 
                          JOIN users u ON m.student_id = u.id
                          WHERE m.exam_id = ? 
                          AND m.subject_id = ? 
                          AND m.stream_id = ? 
                          AND m.school_id = ?
                          AND u.class_id = ?
                          AND u.stream_id = ?
                          AND u.role = 3
                          AND u.status = 'active'";
            
            $marks_stmt = $conn->prepare($marks_sql);
            if (!$marks_stmt) {
                error_log("API Debug - Marks prepare failed: " . $conn->error);
                echo json_encode(['success' => false, 'message' => 'Database prepare error for marks: ' . $conn->error]);
                return;
            }
            
            $marks_stmt->bind_param("iiiiii", $exam_id, $subject_id, $stream_id, $current_user_school_id, $class_id, $stream_id);
            $marks_stmt->execute();
            $marks_result = $marks_stmt->get_result();
            $marks_data = $marks_result->fetch_assoc();
            $students_with_grades = $marks_data['students_with_marks'];
            $marks_stmt->close();
            
            error_log("API Debug - Subject $subject_name: $students_with_grades/$total_students students have marks");
            
            $results[] = [
                'subject_id' => $subject_id,
                'subject_name' => $subject_name,
                'total_students_enrolled' => $total_students,
                'students_with_grades' => $students_with_grades,
                'percentage_complete' => $total_students > 0 ? round(($students_with_grades / $total_students) * 100, 1) : 0
            ];
        }
        
        error_log("API Debug - Returning results for " . count($results) . " subjects");
        
        echo json_encode([
            'success' => true, 
            'results' => $results,
            'exam_info' => [
                'exam_id' => $exam_id,
                'term' => $exam_data['term'],
                'year' => $exam_data['year'],
                'total_subjects' => count($subjects),
                'total_students' => $total_students
            ]
        ]);
        
    } catch (Exception $e) {
        error_log("API Debug - Exception caught: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'Exception: ' . $e->getMessage()]);
    }
}

if (isset($conn)) {
    $conn->close();
}
?>