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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $ay_bs = $conn->real_escape_string(trim($_POST['ay_bs']));
    $ay_ad = $conn->real_escape_string(trim($_POST['ay_ad']));
    $start_date = !empty($_POST['start_date']) ? $_POST['start_date'] : NULL;
    $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : NULL;
    $status = $conn->real_escape_string($_POST['status']);
    
    // Check if year already exists
    $check = $conn->query("SELECT * FROM academic_years WHERE ay_ad = '$ay_ad' OR ay_bs = '$ay_bs'");
    
    if ($check->num_rows > 0) {
        echo json_encode(['success' => false, 'message' => 'Academic year already exists']);
    } else {
        $query = "INSERT INTO academic_years (ay_bs, ay_ad, start_date, end_date, status) 
                  VALUES ('$ay_bs', '$ay_ad', '$start_date', '$end_date', '$status')";
        
        if ($conn->query($query)) {
            echo json_encode(['success' => true, 'message' => 'Academic year added successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
        }
    }
}
?>