<?php
header('Content-Type: application/json');
require_once("../../includes/config.php");
session_start();

// Auth check
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized access']);
    exit;
}

// 1. Get and Clean Input
$term_name = trim($_POST['term_name'] ?? '');
// Fixed the typo in your key from 'max_,arks' to 'max_marks'
$max_marks_raw = $_POST['max_marks'] ?? ''; 
$status = isset($_POST['status']) ? (int)$_POST['status'] : 1;

// 2. Validation
if (empty($term_name)) {
    echo json_encode(['status' => 'error', 'message' => 'Term name is required']);
    exit;
}

// Validate that max_marks is present and is a valid integer
if ($max_marks_raw === '') {
    echo json_encode(['status' => 'error', 'message' => 'Maximum marks are required']);
    exit;
}

$max_marks = (int)$max_marks_raw;

if ($max_marks <= 0) {
    echo json_encode(['status' => 'error', 'message' => 'Maximum marks must be a positive number']);
    exit;
}

try {
    // 3. Prepare and Execute
    // Note: PDO automatically handles the data types, but passing an (int) ensures clean data.
    $stmt = $pdo->prepare("INSERT INTO exam_terms (term_name, max_marks, status) VALUES (?, ?, ?)");
    
    if ($stmt->execute([$term_name, $max_marks, $status])) {
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to save to database']);
    }
} catch (PDOException $e) {
    // Check for duplicate entry error
    if ($e->getCode() == 23000) {
        echo json_encode(['status' => 'error', 'message' => 'This term name already exists']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
    }
}
?>