<?php
require_once '../../config/config.php';
header('Content-Type: application/json');

try {
    $limit = isset($_REQUEST['limit']) ? max(1,(int)$_REQUEST['limit']) : 10;
    $clear = isset($_REQUEST['clear']) ? (int)$_REQUEST['clear'] === 1 : true;

    if ($clear) {
        $pdo->exec('DELETE FROM hall_allocations');
    }

    // Fetch timetable sessions and some halls
    $timetable = $pdo->query('SELECT timetable_id FROM exam_timetable ORDER BY exam_date, session LIMIT 50')->fetchAll(PDO::FETCH_COLUMN);
    $halls = $pdo->query('SELECT hall_id, capacity FROM halls ORDER BY hall_id LIMIT 10')->fetchAll(PDO::FETCH_ASSOC);
    if (!$timetable || !$halls) { echo json_encode(['status'=>'error','message'=>'Need timetable and halls to seed allocations']); exit; }

    $created=0; $rows=[]; $ti=0;
    for ($i=0; $i<$limit; $i++) {
        $tid = (int)$timetable[$ti % count($timetable)]; $ti++;
        $hall = $halls[$i % count($halls)];
        $num = max(10, (int)floor(($hall['capacity'] ?? 60) * 0.6));
        $stmt=$pdo->prepare('INSERT INTO hall_allocations (timetable_id, hall_id, num_students) VALUES (?,?,?)');
        $stmt->execute([$tid, (int)$hall['hall_id'], $num]);
        $aid=(int)$pdo->lastInsertId();
        $created++;
        $rows[]=['allocation_id'=>$aid,'timetable_id'=>$tid,'hall_id'=>(int)$hall['hall_id'],'num_students'=>$num];
    }

    echo json_encode(['status'=>'success','message'=>'Hall allocations seeded','created'=>$created,'data'=>$rows]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>


