<?php
session_start();
require_once '../config.php';

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

$debug = false; // Enable for debugging

try {
    // Check if user is logged in and has admin role
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== 1) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
        exit;
    }

    $input = json_decode(file_get_contents('php://input'), true);
    $school_id = $input['school_id'] ?? $_SESSION["school_id"];

    if ($debug) {
        error_log("get_academic_years.php - school_id: $school_id");
    }

    $academic_years = [];

    if (!isset($conn) || !($conn instanceof mysqli)) {
        echo json_encode(['success' => false, 'message' => 'Database connection failed']);
        exit;
    }

    // Try multiple table possibilities since database structure might vary
    $tables_to_try = [
        "SELECT DISTINCT academic_year FROM academic_years_terms WHERE school_id = ? ORDER BY academic_year DESC",
        "SELECT DISTINCT year FROM exams WHERE school_id = ? ORDER BY year DESC",
        "SELECT DISTINCT academic_year FROM academic_years WHERE school_id = ? ORDER BY academic_year DESC"
    ];

    foreach ($tables_to_try as $sql) {
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("i", $school_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            while ($row = $result->fetch_assoc()) {
                $field_name = isset($row['academic_year']) ? 'academic_year' : 'year';
                $academic_years[] = $row[$field_name];
            }
            $stmt->close();
            
            if (!empty($academic_years)) {
                if ($debug) {
                    error_log("get_academic_years.php - Found data in table using: $sql");
                }
                break; // Found data, stop trying other tables
            }
        }
    }
    
    $conn->close();

    echo json_encode([
        'success' => true,
        'academic_years' => $academic_years,
        'count' => count($academic_years),
        'school_id' => $school_id
    ]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>