<?php
require_once '../../config/config.php';

// Ensure $pdo is accessible
global $pdo;

header('Content-Type: application/json');

function call_php_return_json($path, $get = [], $post = []){
    $oldGet = $_GET; $oldPost = $_POST;
    $_GET = $get; $_POST = $post;
    ob_start(); 
    include $path; 
    $out = ob_get_clean();
    $_GET = $oldGet; $_POST = $oldPost;
    $json = json_decode($out, true);
    return $json ?: ['status'=>'error','message'=>'Invalid response', 'raw'=>$out];
}

function respond($ok, $msg, $extra = []) {
    echo json_encode(($ok ? ['status' => 'success'] : ['status' => 'error']) + ['message' => $msg] + $extra);
    exit;
}

try {
    // Get parameters
    $ayLabel = trim($_POST['academic_year'] ?? ($_GET['academic_year'] ?? ''));
    $perStudent = isset($_POST['per_student']) ? max(1,(int)$_POST['per_student']) : (isset($_GET['per_student']) ? max(1,(int)$_GET['per_student']) : 1);
    $limitStudents = isset($_POST['limit_students']) ? max(1,(int)$_POST['limit_students']) : (isset($_GET['limit_students']) ? max(1,(int)$_GET['limit_students']) : 200);
    $forceClear = isset($_POST['force_clear']) ? in_array(strtolower((string)$_POST['force_clear']), ['1','true','yes'], true)
                                               : (isset($_GET['force_clear']) && in_array(strtolower((string)$_GET['force_clear']), ['1','true','yes'], true));
    $courseId = isset($_POST['course_id']) ? (($_POST['course_id']!=='') ? (int)$_POST['course_id'] : 0)
                                           : (isset($_GET['course_id']) && $_GET['course_id']!=='' ? (int)$_GET['course_id'] : 0);
    $dateFrom = trim($_POST['date_from'] ?? ($_GET['date_from'] ?? ''));
    $dateTo = trim($_POST['date_to'] ?? ($_GET['date_to'] ?? ''));

    if ($ayLabel === '') { 
        respond(false, 'Academic Year is required'); 
    }

    // Extract year from label (e.g., "2025-2026 Odd" -> "2025-2026")
    $yearOnly = $ayLabel;
    if (preg_match('/\b\d{4}-\d{4}\b/', $ayLabel, $m)) { 
        $yearOnly = $m[0]; 
    }

    $results = [];
    $totalCreated = 0; $totalSkipped = 0; $totalNoFee = 0; $totalDeleted = 0;

    // Step 1: Ensure SEM exam type exists
    $examTypeId = (int)($pdo->query("SELECT exam_type_id FROM exam_types WHERE UPPER(type_name)='SEM' LIMIT 1")->fetchColumn() ?: 0);
    if ($examTypeId <= 0) {
        // Create SEM exam type if it doesn't exist
        $pdo->prepare("INSERT INTO exam_types (type_name, description, is_active) VALUES ('SEM', 'Semester Examination', 1)")->execute();
        $examTypeId = (int)$pdo->lastInsertId();
        $results['created_exam_type'] = $examTypeId;
    }

    // Step 2: Check if we have subjects for seeding
    $subjectCount = (int)$pdo->query("SELECT COUNT(*) FROM subjects")->fetchColumn();
    if ($subjectCount === 0) {
        // Seed basic subjects if none exist
        $subjects = [
            ['subject_code' => 'CS101', 'subject_name' => 'Programming Fundamentals', 'semester' => 1, 'course_id' => 1, 'type' => 'Theory', 'is_lab' => 0],
            ['subject_code' => 'CS102', 'subject_name' => 'Data Structures', 'semester' => 2, 'course_id' => 1, 'type' => 'Theory', 'is_lab' => 0],
            ['subject_code' => 'CS103', 'subject_name' => 'Database Systems', 'semester' => 3, 'course_id' => 1, 'type' => 'Theory', 'is_lab' => 0],
            ['subject_code' => 'CS104', 'subject_name' => 'Computer Networks', 'semester' => 4, 'course_id' => 1, 'type' => 'Theory', 'is_lab' => 0],
            ['subject_code' => 'CS105', 'subject_name' => 'Software Engineering', 'semester' => 5, 'course_id' => 1, 'type' => 'Theory', 'is_lab' => 0],
            ['subject_code' => 'CS106', 'subject_name' => 'Operating Systems', 'semester' => 6, 'course_id' => 1, 'type' => 'Theory', 'is_lab' => 0],
        ];
        
        $subjectStmt = $pdo->prepare("INSERT INTO subjects (subject_code, subject_name, semester, course_id, type, is_lab, status) VALUES (?, ?, ?, ?, ?, ?, 'Active')");
        foreach ($subjects as $subj) {
            $subjectStmt->execute([$subj['subject_code'], $subj['subject_name'], $subj['semester'], $subj['course_id'], $subj['type'], $subj['is_lab']]);
        }
        $results['created_subjects'] = count($subjects);
    }

    // Step 3: Check if we have courses for seeding
    $courseCount = (int)$pdo->query("SELECT COUNT(*) FROM courses")->fetchColumn();
    if ($courseCount === 0) {
        // Create a basic course if none exist
        $pdo->prepare("INSERT INTO courses (course_name, course_code, duration_years, status) VALUES ('Computer Science Engineering', 'CSE', 4, 'Active')")->execute();
        $results['created_course'] = $pdo->lastInsertId();
    }

    // Step 4: Check if we have students for seeding
    $studentCount = (int)$pdo->query("SELECT COUNT(*) FROM students")->fetchColumn();
    if ($studentCount === 0) {
        // Create some basic students if none exist
        $students = [
            ['student_name' => 'John Doe', 'student_id' => 'CS001', 'course_id' => 1, 'semester' => 1, 'status' => 'Active'],
            ['student_name' => 'Jane Smith', 'student_id' => 'CS002', 'course_id' => 1, 'semester' => 1, 'status' => 'Active'],
            ['student_name' => 'Mike Johnson', 'student_id' => 'CS003', 'course_id' => 1, 'semester' => 2, 'status' => 'Active'],
            ['student_name' => 'Sarah Wilson', 'student_id' => 'CS004', 'course_id' => 1, 'semester' => 2, 'status' => 'Active'],
            ['student_name' => 'David Brown', 'student_id' => 'CS005', 'course_id' => 1, 'semester' => 3, 'status' => 'Active'],
        ];
        
        $studentStmt = $pdo->prepare("INSERT INTO students (student_name, student_id, course_id, semester, status) VALUES (?, ?, ?, ?, ?)");
        foreach ($students as $student) {
            $studentStmt->execute([$student['student_name'], $student['student_id'], $student['course_id'], $student['semester'], $student['status']]);
        }
        $results['created_students'] = count($students);
    }

    // Step 5: Check if we have halls for seeding
    $hallCount = (int)$pdo->query("SELECT COUNT(*) FROM halls")->fetchColumn();
    if ($hallCount === 0) {
        // Create some basic halls if none exist
        $halls = [
            ['hall_name' => 'Hall A', 'capacity' => 50, 'location' => 'Main Building'],
            ['hall_name' => 'Hall B', 'capacity' => 40, 'location' => 'Main Building'],
            ['hall_name' => 'Hall C', 'capacity' => 60, 'location' => 'Main Building'],
        ];
        
        $hallStmt = $pdo->prepare("INSERT INTO halls (hall_name, capacity, location, status) VALUES (?, ?, ?, 'Active')");
        foreach ($halls as $hall) {
            $hallStmt->execute([$hall['hall_name'], $hall['capacity'], $hall['location']]);
            $hallId = $pdo->lastInsertId();
            
            // Create hall settings for each hall
            $pdo->prepare("INSERT INTO hall_settings (hall_id, rows_count, columns_count, bench_capacity, max_students, row_labeling) VALUES (?, 5, 10, 1, ?, 'Numeric')")
                ->execute([$hallId, $hall['capacity']]);
        }
        $results['created_halls'] = count($halls);
    }

    // Step 6: Check if we have fee structures for seeding
    $feeCount = (int)$pdo->query("SELECT COUNT(*) FROM course_fee_structure")->fetchColumn();
    if ($feeCount === 0) {
        // Create basic fee structures if none exist
        $feeStmt = $pdo->prepare("INSERT INTO course_fee_structure (course_id, fee_type_id, amount, effective_from, effective_to) VALUES (?, ?, ?, CURDATE(), NULL)");
        
        // Get fee types
        $feeTypes = $pdo->query("SELECT fee_type_id FROM fee_types LIMIT 1")->fetchAll(PDO::FETCH_COLUMN);
        if (!$feeTypes) {
            // Create a basic fee type if none exist
            $pdo->prepare("INSERT INTO fee_types (fee_name, description, is_active) VALUES ('Examination Fee', 'Semester Examination Fee', 1)")->execute();
            $feeTypes = [$pdo->lastInsertId()];
        }
        
        $feeStmt->execute([1, $feeTypes[0], 500]);
        $results['created_fee_structures'] = 1;
    }

    // Step 7: Generate exams and timetable for the academic year
    $genResult = call_php_return_json(__DIR__.'/../exams/generate_semester_schedule.php', [], [
        'academic_year' => $ayLabel,
        'all_sem' => 1,
        'start_date' => date('Y-m-d'),
        'shuffle' => 0,
        'course_id' => $courseId
    ]);
    $results['exam_generation'] = $genResult;
    
    // Debug: Check what subjects exist
    $debugSubjects = $pdo->query("SELECT subject_id, subject_code, subject_name, semester, course_id, type, is_lab FROM subjects ORDER BY semester, subject_code")->fetchAll(PDO::FETCH_ASSOC);
    $results['debug_subjects'] = $debugSubjects;

    // Step 8: Get exam IDs for the academic year
    $stmt = $pdo->prepare('SELECT exam_id FROM exams WHERE exam_type_id=? AND academic_year=? ORDER BY semester');
    $stmt->execute([$examTypeId, $yearOnly]);
    $examIds = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Debug: Check exam subjects created
    $debugExamSubjects = $pdo->query("SELECT es.exam_subject_id, es.exam_id, es.subject_id, s.subject_code, s.subject_name, e.academic_year, e.semester FROM exam_subjects es JOIN subjects s ON es.subject_id = s.subject_id JOIN exams e ON es.exam_id = e.exam_id ORDER BY e.academic_year, e.semester")->fetchAll(PDO::FETCH_ASSOC);
    $results['debug_exam_subjects'] = $debugExamSubjects;
    
    if (!$examIds) {
        respond(false, 'No exams found for Academic Year after generation attempt', ['generation_result' => $genResult]);
    }

    // Step 9: Seed student registrations for each exam
    foreach ($examIds as $examId) {
        $res = call_php_return_json(__DIR__.'/student_registrations.php', [
            'limit_students' => $limitStudents,
            'offset' => 0,
            'per_student' => $perStudent,
            'exam_id' => (int)$examId,
            'force_clear_exam' => $forceClear ? '1' : '0'
        ], []);
        
        $results['exam_'.$examId] = $res;
        if (($res['status'] ?? '') === 'success') {
            $totalCreated += (int)($res['created'] ?? 0);
            $totalSkipped += (int)($res['skipped_existing'] ?? 0);
            $totalNoFee += (int)($res['skipped_no_fee'] ?? 0);
            $totalDeleted += (int)($res['deleted_existing_for_exam'] ?? 0);
        }
    }
    
    // Debug: Check final registration count
    $finalRegCount = $pdo->query('SELECT COUNT(*) FROM student_registrations')->fetchColumn();
    $results['final_registration_count'] = $finalRegCount;
    
    // Debug: Check registrations by exam_subject
    $regByExamSubject = $pdo->query('SELECT es.exam_subject_id, COUNT(sr.registration_id) as reg_count FROM exam_subjects es LEFT JOIN student_registrations sr ON es.exam_subject_id = sr.exam_subject_id GROUP BY es.exam_subject_id ORDER BY es.exam_subject_id')->fetchAll(PDO::FETCH_ASSOC);
    $results['registrations_by_exam_subject'] = $regByExamSubject;

    // Step 10: Generate hall allocations
    $resAlloc = call_php_return_json(__DIR__.'/../hall_allocations/generate.php', [], [
        'academic_year' => $ayLabel,
        'course_id' => $courseId,
        'date_from' => $dateFrom,
        'date_to' => $dateTo
    ]);
    $results['hall_allocation'] = $resAlloc;

    respond(true, 'Complete seed and allocation process finished', [
        'registrations' => [
            'created' => $totalCreated,
            'skipped_existing' => $totalSkipped,
            'skipped_no_fee' => $totalNoFee,
            'deleted_existing_for_exam' => $totalDeleted,
        ],
        'allocation' => $resAlloc,
        'setup_details' => $results
    ]);

} catch (Throwable $e) {
    http_response_code(500);
    respond(false, $e->getMessage());
}
?>
