<?php
// ajax/update_exam_type.php
include('../session_validator.php');
include('../includes/db.php');

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid request'
    ]);
    exit;
}

// Check if all required fields are present
$required_fields = ['exam_id', 'exm_year', 'exm_year_ad', 'exam_type', 'class_id'];
foreach ($required_fields as $field) {
    if (!isset($_POST[$field]) || empty($_POST[$field])) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Please fill all required fields'
        ]);
        exit;
    }
}

// Sanitize inputs
$exam_id = intval($_POST['exam_id']);
$exm_year = trim($_POST['exm_year']);
$exm_year_ad = trim($_POST['exm_year_ad']);
$exam_type = trim($_POST['exam_type']);
$class_id = intval($_POST['class_id']);
$assigned_sections = isset($_POST['assigned_sections']) 
    ? implode(',', array_map('intval', $_POST['assigned_sections']))
    : '';

// Check for duplicate (excluding current record)
$check_stmt = $conn->prepare("
    SELECT id FROM examination_type 
    WHERE exm_year = ? AND exam_type = ? AND assigned_class = ? AND id != ?
");
$check_stmt->bind_param("ssii", $exm_year, $exam_type, $class_id, $exam_id);
$check_stmt->execute();
$check_stmt->store_result();

if ($check_stmt->num_rows > 0) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Exam type already exists for this year and class'
    ]);
    $check_stmt->close();
    exit;
}
$check_stmt->close();

// Update the exam type
$update_stmt = $conn->prepare("
    UPDATE examination_type 
    SET exm_year = ?, exm_year_ad = ?, exam_type = ?, assigned_class = ?, assigned_sections = ? 
    WHERE id = ?
");
$update_stmt->bind_param("sssssi", $exm_year, $exm_year_ad, $exam_type, $class_id, $assigned_sections, $exam_id);

if ($update_stmt->execute()) {
    echo json_encode([
        'status' => 'success',
        'message' => 'Exam type updated successfully'
    ]);
} else {
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error. Please try again'
    ]);
}

$update_stmt->close();
?>