<?php
require_once '../../config/config.php';

// Ensure $pdo is accessible
global $pdo;

header('Content-Type: application/json');

function respond($ok, $msg, $extra = []) {
    echo json_encode(($ok ? ['status' => 'success'] : ['status' => 'error']) + ['message' => $msg] + $extra);
    exit;
}

try {
    $force = (int)($_GET['force'] ?? 0);
    $count = (int)($_GET['count'] ?? 5);

    // Ensure we have a valid college_id
    $collegeId = 1;
    
    // Check if college exists by code, if not create one
    $collegeCheck = $pdo->prepare("SELECT college_id FROM colleges WHERE college_code = ?");
    $collegeCheck->execute(['INEC']);
    $existingCollege = $collegeCheck->fetch();
    
    if ($existingCollege) {
        // Use existing college
        $collegeId = $existingCollege['college_id'];
    } else {
        // Create a default college
        $createCollege = $pdo->prepare("INSERT INTO colleges (college_name, college_code, status) VALUES (?, ?, ?)");
        $createCollege->execute([
            'Isaac Newton Engineering College',
            'INEC',
            'Active'
        ]);
        $collegeId = $pdo->lastInsertId();
    }

    // Sample halls data
    $halls = [
        [
            'hall_name' => 'Main Hall A',
            'capacity' => 120,
            'block_name' => 'Block A',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 10,
                'columns_count' => 12,
                'seating_method' => 'Parallel',
                'bench_capacity' => 1,
                'max_students' => 120,
                'row_labeling' => 'Numeric',
                'internal_invigilators_required' => 2,
                'external_invigilators_required' => 1,
                'aisle_every_n_cols' => 4,
                'aisle_every_n_rows' => 0
            ]
        ],
        [
            'hall_name' => 'Main Hall B',
            'capacity' => 100,
            'block_name' => 'Block B',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 8,
                'columns_count' => 12,
                'seating_method' => 'Parallel',
                'bench_capacity' => 1,
                'max_students' => 96,
                'row_labeling' => 'Numeric',
                'internal_invigilators_required' => 2,
                'external_invigilators_required' => 1,
                'aisle_every_n_cols' => 4,
                'aisle_every_n_rows' => 0
            ]
        ],
        [
            'hall_name' => 'Seminar Hall',
            'capacity' => 80,
            'block_name' => 'Block A',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 8,
                'columns_count' => 10,
                'seating_method' => 'Curved',
                'bench_capacity' => 1,
                'max_students' => 80,
                'row_labeling' => 'Alphabetic',
                'internal_invigilators_required' => 1,
                'external_invigilators_required' => 1,
                'aisle_every_n_cols' => 5,
                'aisle_every_n_rows' => 0
            ]
        ],
        [
            'hall_name' => 'Computer Lab Hall',
            'capacity' => 60,
            'block_name' => 'Block B',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 6,
                'columns_count' => 10,
                'seating_method' => 'Parallel',
                'bench_capacity' => 1,
                'max_students' => 60,
                'row_labeling' => 'Numeric',
                'internal_invigilators_required' => 1,
                'external_invigilators_required' => 0,
                'aisle_every_n_cols' => 5,
                'aisle_every_n_rows' => 0
            ]
        ],
        [
            'hall_name' => 'Auditorium',
            'capacity' => 200,
            'block_name' => 'Central Block',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 15,
                'columns_count' => 13,
                'seating_method' => 'Curved',
                'bench_capacity' => 1,
                'max_students' => 195,
                'row_labeling' => 'Alphabetic',
                'internal_invigilators_required' => 3,
                'external_invigilators_required' => 2,
                'aisle_every_n_cols' => 6,
                'aisle_every_n_rows' => 5
            ]
        ],
        [
            'hall_name' => 'Small Hall C',
            'capacity' => 40,
            'block_name' => 'Block C',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 5,
                'columns_count' => 8,
                'seating_method' => 'Parallel',
                'bench_capacity' => 1,
                'max_students' => 40,
                'row_labeling' => 'Numeric',
                'internal_invigilators_required' => 1,
                'external_invigilators_required' => 0,
                'aisle_every_n_cols' => 4,
                'aisle_every_n_rows' => 0
            ]
        ],
        [
            'hall_name' => 'Library Hall',
            'capacity' => 50,
            'block_name' => 'Library Block',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 5,
                'columns_count' => 10,
                'seating_method' => 'Parallel',
                'bench_capacity' => 1,
                'max_students' => 50,
                'row_labeling' => 'Numeric',
                'internal_invigilators_required' => 1,
                'external_invigilators_required' => 0,
                'aisle_every_n_cols' => 5,
                'aisle_every_n_rows' => 0
            ]
        ],
        [
            'hall_name' => 'Conference Hall',
            'capacity' => 30,
            'block_name' => 'Admin Block',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 3,
                'columns_count' => 10,
                'seating_method' => 'Parallel',
                'bench_capacity' => 1,
                'max_students' => 30,
                'row_labeling' => 'Numeric',
                'internal_invigilators_required' => 1,
                'external_invigilators_required' => 0,
                'aisle_every_n_cols' => 5,
                'aisle_every_n_rows' => 0
            ]
        ]
    ];

    $createdHalls = 0;
    $createdSettings = 0;
    $skippedHalls = 0;

    foreach (array_slice($halls, 0, $count) as $hallData) {
        $settings = $hallData['settings'];
        unset($hallData['settings']);

        // Check if hall already exists
        $existingHall = $pdo->prepare("SELECT hall_id FROM halls WHERE hall_name = ?");
        $existingHall->execute([$hallData['hall_name']]);
        $existing = $existingHall->fetch();

        if ($existing && !$force) {
            $skippedHalls++;
            continue;
        }

        if ($existing && $force) {
            // Update existing hall
            $updateHall = $pdo->prepare("UPDATE halls SET capacity = ?, block_name = ? WHERE hall_id = ?");
            $updateHall->execute([$hallData['capacity'], $hallData['block_name'], $existing['hall_id']]);
            $hallId = $existing['hall_id'];
        } else {
            // Insert new hall
            $insertHall = $pdo->prepare("INSERT INTO halls (hall_name, capacity, block_name, college_id) VALUES (?, ?, ?, ?)");
            $insertHall->execute([$hallData['hall_name'], $hallData['capacity'], $hallData['block_name'], $hallData['college_id']]);
            $hallId = $pdo->lastInsertId();
        }

        if ($hallId) {
            $createdHalls++;

            // Check if hall settings already exist
            $existingSettings = $pdo->prepare("SELECT hall_setting_id FROM hall_settings WHERE hall_id = ?");
            $existingSettings->execute([$hallId]);
            $existingSetting = $existingSettings->fetch();

            if ($existingSetting && !$force) {
                continue; // Skip settings if hall exists and not forcing
            }

            if ($existingSetting && $force) {
                // Update existing settings
                $updateSettings = $pdo->prepare("
                    UPDATE hall_settings SET 
                    rows_count = ?, columns_count = ?, seating_method = ?, bench_capacity = ?, 
                    max_students = ?, row_labeling = ?, internal_invigilators_required = ?, 
                    external_invigilators_required = ?, aisle_every_n_cols = ?, aisle_every_n_rows = ?
                    WHERE hall_id = ?
                ");
                $updateSettings->execute([
                    $settings['rows_count'], $settings['columns_count'], $settings['seating_method'],
                    $settings['bench_capacity'], $settings['max_students'], $settings['row_labeling'],
                    $settings['internal_invigilators_required'], $settings['external_invigilators_required'],
                    $settings['aisle_every_n_cols'], $settings['aisle_every_n_rows'], $hallId
                ]);
            } else {
                // Insert new settings
                $insertSettings = $pdo->prepare("
                    INSERT INTO hall_settings (
                        hall_id, rows_count, columns_count, seating_method, bench_capacity,
                        max_students, row_labeling, internal_invigilators_required,
                        external_invigilators_required, aisle_every_n_cols, aisle_every_n_rows
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $insertSettings->execute([
                    $hallId, $settings['rows_count'], $settings['columns_count'], $settings['seating_method'],
                    $settings['bench_capacity'], $settings['max_students'], $settings['row_labeling'],
                    $settings['internal_invigilators_required'], $settings['external_invigilators_required'],
                    $settings['aisle_every_n_cols'], $settings['aisle_every_n_rows']
                ]);
            }
            $createdSettings++;
        }
    }

    respond(true, 'Halls and settings seeded successfully', [
        'created_halls' => $createdHalls,
        'created_settings' => $createdSettings,
        'skipped_halls' => $skippedHalls,
        'total_halls' => count($halls),
        'requested_count' => $count
    ]);

} catch (Throwable $e) {
    http_response_code(500);
    respond(false, $e->getMessage());
}
?>
