<?php
require_once '../../config/config.php';
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];
}

try {
    $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 === '') { echo json_encode(['status'=>'error','message'=>'academic_year is required']); exit; }
    $yearOnly = $ayLabel;
    if (preg_match('/\b\d{4}-\d{4}\b/', $ayLabel, $m)) { $yearOnly = $m[0]; }

    // Find SEM exam_type_id
    $examTypeId = (int)($pdo->query("SELECT exam_type_id FROM exam_types WHERE UPPER(type_name)='SEM' LIMIT 1")->fetchColumn() ?: 0);
    if ($examTypeId <= 0) { echo json_encode(['status'=>'error','message'=>'SEM exam type not found']); exit; }

    // Collect exams for this AY
    $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);
    if (!$examIds) {
        // Attempt to generate exams and timetable for the AY (all semesters per term)
        $gen = 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
        ]);
        $stmt->execute([$examTypeId, $yearOnly]);
        $examIds = $stmt->fetchAll(PDO::FETCH_COLUMN);
        if (!$examIds) {
            echo json_encode(['status'=>'error','message'=>'No exams found for Academic Year (attempted to create but none found)','generate_result'=>$gen]);
            exit;
        }
    }

    // Proceed with registrations seeding
    $results = [];
    $totalCreated = 0; $totalSkipped = 0; $totalNoFee = 0; $totalDeleted = 0;
    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);
        }
    }

    // Generate hall allocations for the same AY
    $resAlloc = call_php_return_json(__DIR__.'/../hall_allocations/generate.php', [], [
        'academic_year' => $ayLabel,
        'course_id' => $courseId,
        'date_from' => $dateFrom,
        'date_to' => $dateTo
    ]);

    echo json_encode([
        'status' => 'success',
        'message' => 'Seeded registrations and generated allocations',
        'registrations' => [
            'created' => $totalCreated,
            'skipped_existing' => $totalSkipped,
            'skipped_no_fee' => $totalNoFee,
            'deleted_existing_for_exam' => $totalDeleted,
        ],
        'allocation' => $resAlloc,
        'details' => $results
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>