<?php
include("../config/db_exam.php");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize and validate the input data
    $exam_id = intval($_POST['exam_id']);  // Ensure it's an integer
    $exam_type = trim($_POST['exam_type']); // Remove unnecessary spaces
    $exm_year = intval($_POST['exm_year']); // Ensure it's a number
    $assigned_class = $_POST['assigned_class'];

    // Validate input
    if (empty($exam_type) || empty($exm_year) || empty($assigned_class)) {
        echo json_encode(["status" => "error", "message" => "All fields are required!"]);
        exit;
    }

    if (!is_numeric($exm_year)) {
        echo json_encode(["status" => "error", "message" => "Year must be a valid number!"]);
        exit;
    }

    // Convert array of classes to comma-separated string
    $assigned_class_str = implode(',', $assigned_class);

    // Update query
    $updateQuery = "UPDATE examination_type SET exam_type = ?, exm_year = ?, assigned_class = ? WHERE id = ?";
    $stmt = $conn->prepare($updateQuery);
    
    if ($stmt) {
        // Bind parameters to the prepared statement
        $stmt->bind_param("sssi", $exam_type, $exm_year, $assigned_class_str, $exam_id);

        // Execute the statement
        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "Exam Type Updated Successfully!"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Error Updating Exam Type: " . $stmt->error]);
        }

        // Close the statement
        $stmt->close();
    } else {
        echo json_encode(["status" => "error", "message" => "Error preparing the query: " . $conn->error]);
    }
}
?>
