<?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_terms.php - school_id: $school_id");
    }

    $terms = [];

    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 term_name FROM academic_years_terms WHERE school_id = ? ORDER BY term_name ASC",
        "SELECT DISTINCT term FROM exams WHERE school_id = ? ORDER BY term ASC",
        "SELECT DISTINCT term_name FROM terms WHERE school_id = ? ORDER BY term_name ASC"
    ];

    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['term_name']) ? 'term_name' : 'term';
                $terms[] = $row[$field_name];
            }
            $stmt->close();
            
            if (!empty($terms)) {
                if ($debug) {
                    error_log("get_terms.php - Found data in table using: $sql");
                }
                break; // Found data, stop trying other tables
            }
        }
    }
    
    $conn->close();

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

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