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

// Get and trim inputs
$year_name = trim($_POST['year_name'] ?? '');
$start_date = $_POST['start_date'] ?? '';
$end_date = $_POST['end_date'] ?? '';
$is_current = isset($_POST['is_current']) ? 1 : 0;

if (empty($year_name) || empty($start_date) || empty($end_date)) {
    echo json_encode(['status' => 'error', 'message' => 'All fields are required.']);
    exit;
}

try {
    // 1. Check for Duplicate Year Name
    $checkStmt = $pdo->prepare("SELECT id FROM academic_years WHERE year_name = ?");
    $checkStmt->execute([$year_name]);
    if ($checkStmt->fetch()) {
        echo json_encode(['status' => 'error', 'message' => 'This academic year already exists!']);
        exit;
    }

    $pdo->beginTransaction();

    // 2. If setting as current, reset others
    if ($is_current == 1) {
        $pdo->query("UPDATE academic_years SET is_current = 0");
    }

    // 3. Insert new year
    $sql = "INSERT INTO academic_years (year_name, start_date, end_date, is_current) 
            VALUES (:name, :start, :end, :current)";
    $stmt = $pdo->prepare($sql);
    $result = $stmt->execute([
        ':name' => $year_name,
        ':start' => $start_date,
        ':end' => $end_date,
        ':current' => $is_current
    ]);

    if ($result) {
        $pdo->commit();
        echo json_encode(['status' => 'success', 'message' => 'Academic year added successfully!']);
    } else {
        throw new Exception("Failed to insert record.");
    }

} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}
?>