<?php

require_once '../config.php';

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



if (!isset($_SESSION['user_id'])) {

    echo json_encode(['success' => false, 'message' => 'Unauthorised']); exit;

}

if (!in_array($_SESSION['role'] ?? '', ['admin', 'headteacher', 'director'])) {

    echo json_encode(['success' => false, 'message' => 'Access denied']); exit;

}



$conn   = getDBConnection();

$action = $_POST['action'] ?? $_GET['action'] ?? '';



// Ensure tables exist (idempotent)

$conn->query("CREATE TABLE IF NOT EXISTS school_terms (

    id           INT AUTO_INCREMENT PRIMARY KEY,

    academic_year VARCHAR(20) NOT NULL,

    term         VARCHAR(20) NOT NULL,

    start_date   DATE NOT NULL,

    end_date     DATE NOT NULL,

    created_at   DATETIME DEFAULT CURRENT_TIMESTAMP,

    updated_at   DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    UNIQUE KEY unique_term (academic_year, term)

)");



$conn->query("CREATE TABLE IF NOT EXISTS school_holidays (

    id           INT AUTO_INCREMENT PRIMARY KEY,

    holiday_name VARCHAR(100) NOT NULL,

    holiday_date DATE NOT NULL,

    is_observed  TINYINT(1) NOT NULL DEFAULT 1,

    is_movable   TINYINT(1) NOT NULL DEFAULT 0,

    note         VARCHAR(255) NULL,

    created_at   DATETIME DEFAULT CURRENT_TIMESTAMP,

    updated_at   DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    UNIQUE KEY unique_holiday_date (holiday_date, holiday_name(50))

)");



require_once __DIR__ . '/../includes/calendar_lib.php';
calendar_ensure_schema($conn);
$multiLevel = calendar_multilevel_enabled();

switch ($action) {



    // ── Terms ────────────────────────────────────────────────────────────────



    case 'get_terms':

        $year = trim($_GET['academic_year'] ?? '');

        if ($year !== '') {

            $stmt = $conn->prepare("SELECT * FROM school_terms WHERE academic_year = ? ORDER BY programme_level, start_date");

            $stmt->bind_param('s', $year);

        } else {

            $stmt = $conn->prepare("SELECT * FROM school_terms ORDER BY academic_year DESC, programme_level, start_date");

        }

        $stmt->execute();

        $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

        $stmt->close();

        echo json_encode(['success' => true, 'data' => $rows]);

        break;



    case 'save_term':

        $id           = (int)  ($_POST['id']            ?? 0);

        $academicYear = trim(  $_POST['academic_year']  ?? '');

        $term         = trim(  $_POST['term']           ?? '');

        $startDate    = trim(  $_POST['start_date']     ?? '');

        $endDate      = trim(  $_POST['end_date']       ?? '');
        $level        = $multiLevel ? (trim($_POST['programme_level'] ?? 'All') ?: 'All') : 'All';
        if (!in_array($level, calendar_levels(), true)) $level = 'All';



        if (!$academicYear || !$term || !$startDate || !$endDate) {

            echo json_encode(['success' => false, 'message' => 'All fields required']); break;

        }

        if ($startDate >= $endDate) {

            echo json_encode(['success' => false, 'message' => 'End date must be after start date']); break;

        }



        if ($id > 0) {

            $stmt = $conn->prepare("UPDATE school_terms SET academic_year=?, term=?, programme_level=?, start_date=?, end_date=? WHERE id=?");

            $stmt->bind_param('sssssi', $academicYear, $term, $level, $startDate, $endDate, $id);

        } else {

            $stmt = $conn->prepare("INSERT INTO school_terms (academic_year, term, programme_level, start_date, end_date) VALUES (?,?,?,?,?)

                                    ON DUPLICATE KEY UPDATE start_date=VALUES(start_date), end_date=VALUES(end_date)");

            $stmt->bind_param('sssss', $academicYear, $term, $level, $startDate, $endDate);

        }

        $ok = $stmt->execute();

        $newId = $stmt->insert_id ?: $id;

        $stmt->close();



        if ($ok) {

            logActivity($conn, $_SESSION['user_id'], 'save_term', "Term saved: {$academicYear} {$term} ({$startDate}–{$endDate})");

            echo json_encode(['success' => true, 'message' => 'Term saved', 'data' => ['id' => $newId]]);

        } else {

            echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);

        }

        break;



    case 'delete_term':

        $id = (int) ($_POST['id'] ?? 0);

        if (!$id) { echo json_encode(['success' => false, 'message' => 'Missing id']); break; }

        $stmt = $conn->prepare("DELETE FROM school_terms WHERE id=?");

        $stmt->bind_param('i', $id);

        $ok = $stmt->execute();

        $stmt->close();

        if ($ok) {

            logActivity($conn, $_SESSION['user_id'], 'delete_term', "Term id={$id} deleted");

            echo json_encode(['success' => true, 'message' => 'Term deleted']);

        } else {

            echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);

        }

        break;



    // ── Holidays ─────────────────────────────────────────────────────────────



    case 'get_holidays':

        $year = (int) ($_GET['year'] ?? date('Y'));

        $stmt = $conn->prepare("SELECT * FROM school_holidays WHERE YEAR(holiday_date) = ? ORDER BY holiday_date");

        $stmt->bind_param('i', $year);

        $stmt->execute();

        $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

        $stmt->close();

        echo json_encode(['success' => true, 'data' => $rows]);

        break;



    case 'save_holiday':

        $id          = (int)  ($_POST['id']           ?? 0);

        $name        = trim(  $_POST['holiday_name']  ?? '');

        $date        = trim(  $_POST['holiday_date']  ?? '');

        $isObserved  = (int)  ($_POST['is_observed']  ?? 1);

        $isMovable   = (int)  ($_POST['is_movable']   ?? 0);

        $note        = trim(  $_POST['note']          ?? '');



        if (!$name || !$date) {

            echo json_encode(['success' => false, 'message' => 'Name and date required']); break;

        }

        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {

            echo json_encode(['success' => false, 'message' => 'Invalid date format (YYYY-MM-DD required)']); break;

        }



        $noteVal = $note !== '' ? $note : null;



        if ($id > 0) {

            $stmt = $conn->prepare("UPDATE school_holidays SET holiday_name=?, holiday_date=?, is_observed=?, is_movable=?, note=? WHERE id=?");

            $stmt->bind_param('ssiisi', $name, $date, $isObserved, $isMovable, $noteVal, $id);

        } else {

            $stmt = $conn->prepare("INSERT INTO school_holidays (holiday_name, holiday_date, is_observed, is_movable, note) VALUES (?,?,?,?,?)

                                    ON DUPLICATE KEY UPDATE is_observed=VALUES(is_observed), note=VALUES(note)");

            $stmt->bind_param('ssiis', $name, $date, $isObserved, $isMovable, $noteVal);

        }

        $ok = $stmt->execute();

        $newId = $stmt->insert_id ?: $id;

        $stmt->close();



        if ($ok) {

            logActivity($conn, $_SESSION['user_id'], 'save_holiday', "Holiday saved: {$name} on {$date}");

            echo json_encode(['success' => true, 'message' => 'Holiday saved', 'data' => ['id' => $newId]]);

        } else {

            echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);

        }

        break;



    case 'toggle_holiday':

        $id         = (int) ($_POST['id']          ?? 0);

        $isObserved = (int) ($_POST['is_observed'] ?? 0);

        if (!$id) { echo json_encode(['success' => false, 'message' => 'Missing id']); break; }

        $stmt = $conn->prepare("UPDATE school_holidays SET is_observed=? WHERE id=?");

        $stmt->bind_param('ii', $isObserved, $id);

        $ok = $stmt->execute();

        $stmt->close();

        echo json_encode(['success' => (bool) $ok, 'message' => $ok ? 'Updated' : $conn->error]);

        break;



    case 'delete_holiday':

        $id = (int) ($_POST['id'] ?? 0);

        if (!$id) { echo json_encode(['success' => false, 'message' => 'Missing id']); break; }

        $stmt = $conn->prepare("DELETE FROM school_holidays WHERE id=?");

        $stmt->bind_param('i', $id);

        $ok = $stmt->execute();

        $stmt->close();

        if ($ok) {

            logActivity($conn, $_SESSION['user_id'], 'delete_holiday', "Holiday id={$id} deleted");

            echo json_encode(['success' => true, 'message' => 'Holiday deleted']);

        } else {

            echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);

        }

        break;



    // ── Utility: calculate school days for a term ─────────────────────────────



    case 'count_school_days':

        $academicYear = trim($_GET['academic_year'] ?? '');

        $term         = trim($_GET['term']          ?? '');
        $level        = $multiLevel ? (trim($_GET['programme_level'] ?? 'All') ?: 'All') : 'All';

        if (!$academicYear || !$term) {

            echo json_encode(['success' => false, 'message' => 'academic_year and term required']); break;

        }

        $termRow = getTermDatesForLevel($conn, $level, $academicYear, $term);



        if (!$termRow) {

            echo json_encode(['success' => false, 'message' => 'Term not found']); break;

        }



        $start = new DateTime($termRow['start_date']);

        $end   = new DateTime($termRow['end_date']);



        // Fetch observed holidays within this range

        $stmt = $conn->prepare("SELECT holiday_date FROM school_holidays

                                 WHERE is_observed=1 AND holiday_date BETWEEN ? AND ?");

        $stmt->bind_param('ss', $termRow['start_date'], $termRow['end_date']);

        $stmt->execute();

        $holidayRows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

        $stmt->close();



        $holidays = array_column($holidayRows, 'holiday_date');



        $schoolDays = 0;

        $current    = clone $start;

        while ($current <= $end) {

            $dow = (int) $current->format('N'); // 1=Mon … 7=Sun

            $ymd = $current->format('Y-m-d');

            if ($dow <= 5 && !in_array($ymd, $holidays, true)) {

                $schoolDays++;

            }

            $current->modify('+1 day');

        }



        echo json_encode(['success' => true, 'data' => [

            'academic_year' => $academicYear,

            'term'          => $term,

            'start_date'    => $termRow['start_date'],

            'end_date'      => $termRow['end_date'],

            'school_days'   => $schoolDays,

        ]]);

        break;



    default:

        echo json_encode(['success' => false, 'message' => 'Unknown action']);

}



$conn->close();

