<?php
//save_exam_type.php
include('../includes/db.php');

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

function sanitize($data) {
    return trim(htmlspecialchars($data));
}

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

$exm_year        = sanitize($_POST['exm_year'] ?? '');
$exm_year_ad     = sanitize($_POST['exm_year_ad'] ?? '');
$exam_type       = sanitize($_POST['exam_type'] ?? '');
$assigned_class  = sanitize($_POST['class_id'] ?? '');
$assigned_sections = isset($_POST['assigned_sections'])
    ? implode(',', $_POST['assigned_sections'])
    : '';

if (!$exm_year || !$exm_year_ad || !$exam_type || !$assigned_class) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Please fill all required fields'
    ]);
    exit;
}

/* 🔎 Duplicate check */
$check = $conn->prepare(
    "SELECT id FROM examination_type WHERE exm_year=? AND exam_type=? AND assigned_class=?"
);
$check->bind_param("iss", $exm_year, $exam_type, $assigned_class);
$check->execute();
$check->store_result();

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

/* 💾 Insert */
$insert = $conn->prepare(
    "INSERT INTO examination_type 
    (exm_year, exm_year_ad, exam_type, assigned_class, assigned_sections)
    VALUES (?, ?, ?, ?, ?)"
);
$insert->bind_param(
    "iisss",
    $exm_year,
    $exm_year_ad,
    $exam_type,
    $assigned_class,
    $assigned_sections
);

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

$insert->close();
