<?php
// Filename: api_timetable.php
require 'config.php';
requireLogin();

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

try {
    $uid = $_SESSION['user_id'];
    $user_full_name = $_SESSION['full_name'] ?? 'A teacher';
    $user_roles = explode(',', $_SESSION['role'] ?? '');
    $is_admin = !empty(array_intersect($user_roles, ['admin', 'timetable_coord', 'principal', 'assistant']));

    function jsonResponse($success, $message, $data = []) {
        ob_clean();
        echo json_encode(['success' => $success, 'message' => $message, 'data' => $data]);
        exit;
    }

    function getSubjectType($pdo, $subject_name) {
        $stmt = $pdo->prepare("SELECT type FROM subjects WHERE subject_name = ? LIMIT 1");
        $stmt->execute([$subject_name]);
        return $stmt->fetchColumn() ?: 'core';
    }

    function checkConflict($pdo, $teacher_id, $class_id, $day, $start, $end, $subject, $ignore_id = null) {
        $new_type = getSubjectType($pdo, $subject);
        $errors = [];
        $sql_t = "SELECT id, subject, class_id FROM timetable WHERE teacher_id = ? AND day_of_week = ? AND (start_time < ? AND end_time > ?) AND subject != ? "; 
        if ($ignore_id) $sql_t .= " AND id != $ignore_id";
        $stmt_t = $pdo->prepare($sql_t);
        $stmt_t->execute([$teacher_id, $day, $end, $start, $subject]);
        if ($stmt_t->fetch()) { $errors[] = "Teacher is busy with another subject."; }
        $sql_c = "SELECT t.id, t.subject, s.type FROM timetable t LEFT JOIN subjects s ON t.subject = s.subject_name WHERE t.class_id = ? AND t.day_of_week = ? AND (t.start_time < ? AND t.end_time > ?)";
        if ($ignore_id) $sql_c .= " AND t.id != $ignore_id";
        $stmt_c = $pdo->prepare($sql_c);
        $stmt_c->execute([$class_id, $day, $end, $start]);
        while ($row = $stmt_c->fetch()) {
            $existing_type = $row['type'] ?? 'core';
            if ($new_type === 'core' || $existing_type === 'core') { $errors[] = "Class clash: '{$row['subject']}' ($existing_type) vs '$subject' ($new_type)."; }
        }
        return $errors;
    }

    $s_start = getSetting('start_time', '07:30');
    $s_dur = intval(getSetting('slot_duration', 30));
    $time_slots = [];
    $curr_ts = strtotime($s_start);
    for($i=1; $i<=25; $i++) {
        $end_ts = $curr_ts + ($s_dur * 60);
        $time_slots[$i] = ['start' => date('H:i', $curr_ts), 'end' => date('H:i', $end_ts)];
        $curr_ts = $end_ts;
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = $_POST['action'] ?? '';

        if ($action === 'teacher_request_slot' || $action === 'teacher_request_delete') {
            if ($action === 'teacher_request_slot') {
                $class_id = $_POST['class_id'];
                $subject = $_POST['subject'];
                $day = $_POST['day_of_week'];
                $period_num = intval($_POST['period_num']);
                $duration = intval($_POST['duration'] ?? 1);
                $start = $time_slots[$period_num]['start'];
                $end = $time_slots[$period_num + $duration - 1]['end'] ?? $time_slots[$period_num]['end'];
                $conflicts = checkConflict($pdo, $uid, $class_id, $day, $start, $end, $subject);
                if (!empty($conflicts)) jsonResponse(false, implode(" ", $conflicts));
                $pdo->prepare("INSERT INTO timetable_requests (class_id, teacher_id, subject, day_of_week, start_time, end_time, request_type, status) VALUES (?,?,?,?,?,?, 'add', 'pending')")->execute([$class_id, $uid, $subject, $day, $start, $end]);
                $msg_text = "requested to ADD $subject.";
            } else {
                $pdo->prepare("UPDATE timetable_requests SET status='rejected' WHERE teacher_id=? AND status='pending'"); // Cleanup old
                $pdo->prepare("INSERT INTO timetable_requests (teacher_id, request_type, status, timetable_id) VALUES (?, 'delete', 'pending', ?)")->execute([$uid, $_POST['slot_id']]);
                $msg_text = "requested to DELETE a slot.";
            }

            // NOTIFY ADMINS
            $admins = $pdo->query("SELECT id FROM users WHERE role LIKE '%admin%'")->fetchAll(PDO::FETCH_COLUMN);
            $notif_body = "$user_full_name $msg_text";
            $ins_notif = $pdo->prepare("INSERT INTO notifications (user_id, message, link, type, is_read, created_at) VALUES (?, ?, 'admin_timetable.php', 'timetable', 0, NOW())");
            foreach ($admins as $aid) { $ins_notif->execute([$aid, $notif_body]); }
            if (function_exists('sendTelegram')) { sendTelegram("?? <b>Timetable Request</b>\n$notif_body"); }
            jsonResponse(true, "Request submitted.");
        }

        if ($is_admin && $action === 'admin_save_slot') {
            $tid = $_POST['slot_id'] ?? null; $class_id = $_POST['class_id']; $teacher_id = $_POST['teacher_id']; $subject = $_POST['subject']; $day = $_POST['day_of_week']; $period_num = intval($_POST['period_num']); $duration = intval($_POST['duration']);
            $start = $time_slots[$period_num]['start']; $end = $time_slots[$period_num + $duration - 1]['end'];
            $conflicts = checkConflict($pdo, $teacher_id, $class_id, $day, $start, $end, $subject, $tid);
            if (!empty($conflicts)) jsonResponse(false, implode(" ", $conflicts));
            if ($tid) { $pdo->prepare("UPDATE timetable SET class_id=?, teacher_id=?, subject=?, day_of_week=?, start_time=?, end_time=? WHERE id=?")->execute([$class_id, $teacher_id, $subject, $day, $start, $end, $tid]); }
            else { $pdo->prepare("INSERT INTO timetable (class_id, teacher_id, subject, day_of_week, start_time, end_time) VALUES (?,?,?,?,?,?)")->execute([$class_id, $teacher_id, $subject, $day, $start, $end]); }
            jsonResponse(true, "Saved.");
        }

        if ($is_admin && $action === 'admin_delete_slot') { $pdo->prepare("DELETE FROM timetable WHERE id = ?")->execute([$_POST['slot_id']]); jsonResponse(true, "Deleted."); }
        
        if ($is_admin && $action === 'approve_request') {
            $req = $pdo->query("SELECT * FROM timetable_requests WHERE id = ".intval($_POST['request_id']))->fetch();
            if ($req && $req['request_type'] === 'add') {
                $pdo->prepare("INSERT INTO timetable (class_id, teacher_id, subject, day_of_week, start_time, end_time) VALUES (?,?,?,?,?,?)")->execute([$req['class_id'], $req['teacher_id'], $req['subject'], $req['day_of_week'], $req['start_time'], $req['end_time']]);
            } elseif ($req && $req['request_type'] === 'delete') {
                $pdo->prepare("DELETE FROM timetable WHERE id = ?")->execute([$req['timetable_id']]);
            }
            $pdo->prepare("UPDATE timetable_requests SET status = 'approved' WHERE id = ?")->execute([$_POST['request_id']]);
            jsonResponse(true, "Approved.");
        }
    }
} catch (Exception $e) { jsonResponse(false, $e->getMessage()); }
?>