<?php
/**
 * Action: Detect timetable conflicts and generate AI-powered suggestions.
 */

if (!defined('DB_HOST')) {
    require_once __DIR__ . '/../../config.php';
}
require_once __DIR__ . '/../provider_engine.php';

function action_check_timetable_conflicts(array $params): array
{
    $conn          = getDBConnection();
    $academic_year = $params['academic_year'] ?? getSettingValue('academic_year') ?? date('Y');
    $term          = $params['term'] ?? getSettingValue('current_term') ?? 'First Term';

    $conflicts   = [];
    $empty_slots = 0;

    // Detect teacher double-booked: same teacher, same day, same period
    $double_stmt = $conn->prepare(
        "SELECT t.full_name AS teacher_name, ts.day_of_week, tp.period_name,
                GROUP_CONCAT(ts.class_name ORDER BY ts.class_name SEPARATOR ', ') AS classes,
                COUNT(*) AS conflict_count
         FROM timetable_slots ts
         JOIN staff t ON t.id = ts.teacher_id
         JOIN timetable_periods tp ON tp.id = ts.period_id
         WHERE ts.academic_year = ? AND ts.term = ? AND ts.teacher_id IS NOT NULL
         GROUP BY ts.teacher_id, ts.day_of_week, ts.period_id
         HAVING conflict_count > 1"
    );

    if ($double_stmt) {
        $double_stmt->bind_param('ss', $academic_year, $term);
        $double_stmt->execute();
        $doubles = $double_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        foreach ($doubles as $d) {
            $conflicts[] = [
                'conflict_type' => 'teacher_double_booked',
                'description'   => "Teacher {$d['teacher_name']} is double-booked on {$d['day_of_week']} {$d['period_name']} for classes: {$d['classes']}",
                'day'           => $d['day_of_week'],
                'period'        => $d['period_name'],
                'teacher'       => $d['teacher_name'],
            ];
        }
    }

    // Detect empty slots (periods with no assignment for a class/day)
    $empty_stmt = $conn->prepare(
        "SELECT COUNT(*) AS empty_count FROM timetable_slots
         WHERE academic_year = ? AND term = ?
         AND (teacher_id IS NULL OR subject_id IS NULL)"
    );
    if ($empty_stmt) {
        $empty_stmt->bind_param('ss', $academic_year, $term);
        $empty_stmt->execute();
        $e_row       = $empty_stmt->get_result()->fetch_assoc();
        $empty_slots = (int) ($e_row['empty_count'] ?? 0);
    }

    // AI suggestions
    $ai_suggestions = [];
    if (!empty($conflicts) || $empty_slots > 0) {
        $conflict_summary = json_encode(array_slice($conflicts, 0, 20));
        $ai_result = RBCAIEngine::generate(
            "Review these timetable issues and suggest practical resolutions. " .
            "Conflicts: {$conflict_summary}. " .
            "Empty/incomplete slots: {$empty_slots}. " .
            "Return JSON array: [{\"conflict_type\":\"...\",\"description\":\"...\",\"suggested_fix\":\"...\"}]",
            "You are a school timetable coordinator. Suggest practical fixes for scheduling conflicts.",
            1500,
            true
        );

        if ($ai_result['success']) {
            $raw = preg_replace('/^```json\s*/i', '', trim($ai_result['content']));
            $raw = preg_replace('/^```\s*/i', '', $raw);
            $raw = preg_replace('/\s*```$/', '', $raw);
            $parsed = json_decode(trim($raw), true);
            if (is_array($parsed)) {
                $ai_suggestions = $parsed;
            }
        }
    }

    return [
        'success'        => true,
        'conflicts'      => $conflicts,
        'ai_suggestions' => $ai_suggestions,
        'empty_slots'    => $empty_slots,
        'academic_year'  => $academic_year,
        'term'           => $term,
    ];
}
