<?php
session_start();
require_once 'includes/database.php';

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

if(!isset($_SESSION['username'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$conn = new Database();

try {
    // Find teacher conflicts
    $teacherConflicts = [];
    $sql = "SELECT 
            t1.id as timetable_id_1,
            t2.id as timetable_id_2,
            t1.teacher_id,
            t1.day_id,
            t1.period_id,
            c1.name as class1_name,
            s1.name as section1_name,
            sub1.subject_name as subject1_name,
            teach1.name as teacher1_name,
            t1.room_number as room1,
            c2.name as class2_name,
            s2.name as section2_name,
            sub2.subject_name as subject2_name,
            teach2.name as teacher2_name,
            t2.room_number as room2,
            d.day_name,
            p.period_name
            FROM timetable t1
            JOIN timetable t2 ON t1.teacher_id = t2.teacher_id 
                AND t1.day_id = t2.day_id 
                AND t1.period_id = t2.period_id
                AND t1.id < t2.id
            LEFT JOIN classes c1 ON t1.class_id = c1.id
            LEFT JOIN sections s1 ON t1.section_id = s1.id
            LEFT JOIN subjects sub1 ON t1.subject_id = sub1.id
            LEFT JOIN teachers teach1 ON t1.teacher_id = teach1.id
            LEFT JOIN classes c2 ON t2.class_id = c2.id
            LEFT JOIN sections s2 ON t2.section_id = s2.id
            LEFT JOIN subjects sub2 ON t2.subject_id = sub2.id
            LEFT JOIN teachers teach2 ON t2.teacher_id = teach2.id
            LEFT JOIN timetable_days d ON t1.day_id = d.id
            LEFT JOIN timetable_periods p ON t1.period_id = p.id";

    $conn->query($sql);
    $teacherConflicts = $conn->fetchMultiple();

    // Find room conflicts
    $roomConflicts = [];
    $sql = "SELECT 
            t1.id as timetable_id_1,
            t2.id as timetable_id_2,
            t1.room_number,
            t1.day_id,
            t1.period_id,
            c1.name as class1_name,
            s1.name as section1_name,
            sub1.subject_name as subject1_name,
            teach1.name as teacher1_name,
            t1.room_number as room1,
            c2.name as class2_name,
            s2.name as section2_name,
            sub2.subject_name as subject2_name,
            teach2.name as teacher2_name,
            t2.room_number as room2,
            d.day_name,
            p.period_name
            FROM timetable t1
            JOIN timetable t2 ON t1.room_number = t2.room_number 
                AND t1.day_id = t2.day_id 
                AND t1.period_id = t2.period_id
                AND t1.id < t2.id
                AND t1.room_number IS NOT NULL
                AND t1.room_number != ''
            LEFT JOIN classes c1 ON t1.class_id = c1.id
            LEFT JOIN sections s1 ON t1.section_id = s1.id
            LEFT JOIN subjects sub1 ON t1.subject_id = sub1.id
            LEFT JOIN teachers teach1 ON t1.teacher_id = teach1.id
            LEFT JOIN classes c2 ON t2.class_id = c2.id
            LEFT JOIN sections s2 ON t2.section_id = s2.id
            LEFT JOIN subjects sub2 ON t2.subject_id = sub2.id
            LEFT JOIN teachers teach2 ON t2.teacher_id = teach2.id
            LEFT JOIN timetable_days d ON t1.day_id = d.id
            LEFT JOIN timetable_periods p ON t1.period_id = p.id";

    $conn->query($sql);
    $roomConflicts = $conn->fetchMultiple();

    // Prepare conflicts array
    $conflicts = [];
    $conflictIds = [];

    // Add teacher conflicts
    if($teacherConflicts) {
        foreach($teacherConflicts as $conflict) {
            $conflictKey = $conflict->day_id . '-' . $conflict->period_id . '-teacher-' . $conflict->teacher_id;

            if(!in_array($conflictKey, $conflictIds)) {
                // Check if already logged
                $sql = "SELECT id, is_resolved FROM timetable_conflicts 
                        WHERE conflict_type = 'teacher_clash'
                        AND entity_id = :entity_id
                        AND day_id = :day_id
                        AND period_id = :period_id
                        AND timetable_id_1 = :tid1
                        AND timetable_id_2 = :tid2";

                $conn->query($sql);
                $conn->bind(':entity_id', $conflict->teacher_id);
                $conn->bind(':day_id', $conflict->day_id);
                $conn->bind(':period_id', $conflict->period_id);
                $conn->bind(':tid1', $conflict->timetable_id_1);
                $conn->bind(':tid2', $conflict->timetable_id_2);
                $existing = $conn->fetchSingle();

                if(!$existing) {
                    // Log new conflict
                    $description = "{$conflict->teacher1_name} is scheduled for {$conflict->class1_name}-{$conflict->section1_name} and {$conflict->class2_name}-{$conflict->section2_name} at the same time";

                    $sql = "INSERT INTO timetable_conflicts 
                            (conflict_type, entity_id, day_id, period_id, timetable_id_1, timetable_id_2, conflict_description)
                            VALUES ('teacher_clash', :entity_id, :day_id, :period_id, :tid1, :tid2, :description)";

                    $conn->query($sql);
                    $conn->bind(':entity_id', $conflict->teacher_id);
                    $conn->bind(':day_id', $conflict->day_id);
                    $conn->bind(':period_id', $conflict->period_id);
                    $conn->bind(':tid1', $conflict->timetable_id_1);
                    $conn->bind(':tid2', $conflict->timetable_id_2);
                    $conn->bind(':description', $description);
                    $conn->execute();

                    $conflictId = $conn->lastInserted();
                    $isResolved = 0;
                } else {
                    $conflictId = $existing->id;
                    $isResolved = $existing->is_resolved;
                }

                $conflicts[] = [
                    'id' => $conflictId,
                    'conflict_type' => 'teacher_clash',
                    'day_name' => $conflict->day_name,
                    'period_name' => $conflict->period_name,
                    'conflict_description' => "{$conflict->teacher1_name} is scheduled for multiple classes at the same time",
                    'class1_name' => $conflict->class1_name,
                    'section1_name' => $conflict->section1_name,
                    'subject1_name' => $conflict->subject1_name,
                    'teacher1_name' => $conflict->teacher1_name,
                    'room1' => $conflict->room1,
                    'class2_name' => $conflict->class2_name,
                    'section2_name' => $conflict->section2_name,
                    'subject2_name' => $conflict->subject2_name,
                    'teacher2_name' => $conflict->teacher2_name,
                    'room2' => $conflict->room2,
                    'is_resolved' => $isResolved
                ];

                $conflictIds[] = $conflictKey;
            }
        }
    }

    // Add room conflicts
    if($roomConflicts) {
        foreach($roomConflicts as $conflict) {
            $conflictKey = $conflict->day_id . '-' . $conflict->period_id . '-room-' . $conflict->room_number;

            if(!in_array($conflictKey, $conflictIds)) {
                // Check if already logged
                $sql = "SELECT id, is_resolved FROM timetable_conflicts 
                        WHERE conflict_type = 'room_clash'
                        AND day_id = :day_id
                        AND period_id = :period_id
                        AND timetable_id_1 = :tid1
                        AND timetable_id_2 = :tid2";

                $conn->query($sql);
                $conn->bind(':day_id', $conflict->day_id);
                $conn->bind(':period_id', $conflict->period_id);
                $conn->bind(':tid1', $conflict->timetable_id_1);
                $conn->bind(':tid2', $conflict->timetable_id_2);
                $existing = $conn->fetchSingle();

                if(!$existing) {
                    // Log new conflict
                    $description = "Room {$conflict->room_number} is assigned to {$conflict->class1_name}-{$conflict->section1_name} and {$conflict->class2_name}-{$conflict->section2_name} at the same time";

                    $sql = "INSERT INTO timetable_conflicts 
                            (conflict_type, entity_id, day_id, period_id, timetable_id_1, timetable_id_2, conflict_description)
                            VALUES ('room_clash', 0, :day_id, :period_id, :tid1, :tid2, :description)";

                    $conn->query($sql);
                    $conn->bind(':day_id', $conflict->day_id);
                    $conn->bind(':period_id', $conflict->period_id);
                    $conn->bind(':tid1', $conflict->timetable_id_1);
                    $conn->bind(':tid2', $conflict->timetable_id_2);
                    $conn->bind(':description', $description);
                    $conn->execute();

                    $conflictId = $conn->lastInserted();
                    $isResolved = 0;
                } else {
                    $conflictId = $existing->id;
                    $isResolved = $existing->is_resolved;
                }

                $conflicts[] = [
                    'id' => $conflictId,
                    'conflict_type' => 'room_clash',
                    'day_name' => $conflict->day_name,
                    'period_name' => $conflict->period_name,
                    'conflict_description' => "Room {$conflict->room_number} is double-booked",
                    'class1_name' => $conflict->class1_name,
                    'section1_name' => $conflict->section1_name,
                    'subject1_name' => $conflict->subject1_name,
                    'teacher1_name' => $conflict->teacher1_name,
                    'room1' => $conflict->room1,
                    'class2_name' => $conflict->class2_name,
                    'section2_name' => $conflict->section2_name,
                    'subject2_name' => $conflict->subject2_name,
                    'teacher2_name' => $conflict->teacher2_name,
                    'room2' => $conflict->room2,
                    'is_resolved' => $isResolved
                ];

                $conflictIds[] = $conflictKey;
            }
        }
    }

    // Calculate statistics
    $statistics = [
        'total' => count($conflicts),
        'teacher_clash' => count(array_filter($conflicts, fn($c) => $c['conflict_type'] === 'teacher_clash')),
        'room_clash' => count(array_filter($conflicts, fn($c) => $c['conflict_type'] === 'room_clash')),
        'resolved' => count(array_filter($conflicts, fn($c) => $c['is_resolved'] == 1))
    ];

    echo json_encode([
        'success' => true,
        'conflicts' => $conflicts,
        'statistics' => $statistics
    ]);

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