<?php
require_once '../../config/config.php';

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)($_POST['force'] ?? $_GET['force'] ?? 0);
    $count = (int)($_POST['count'] ?? $_GET['count'] ?? 8);

    // 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) {
        $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();
    }

    $results = [
        'halls' => ['created' => 0, 'skipped' => 0],
        'settings' => ['created' => 0, 'skipped' => 0]
    ];

    // Hall data with parallel seating for 25 students each
    $hallsData = [
        [
            'hall_name' => 'Hall A1',
            'capacity' => 25,
            'block_name' => 'Block A',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 5, 'columns_count' => 5, 'seating_method' => 'Parallel',
                'bench_capacity' => 1, 'max_students' => 25, 'row_labeling' => 'Numeric',
                'internal_invigilators_required' => 1, 'external_invigilators_required' => 1,
                'aisle_every_n_cols' => 3, 'aisle_every_n_rows' => 0
            ]
        ],
        [
            'hall_name' => 'Hall A2',
            'capacity' => 25,
            'block_name' => 'Block A',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 5, 'columns_count' => 5, 'seating_method' => 'Parallel',
                'bench_capacity' => 1, 'max_students' => 25, 'row_labeling' => 'Numeric',
                'internal_invigilators_required' => 1, 'external_invigilators_required' => 1,
                'aisle_every_n_cols' => 3, 'aisle_every_n_rows' => 0
            ]
        ],
        [
            'hall_name' => 'Hall B1',
            'capacity' => 25,
            'block_name' => 'Block B',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 5, 'columns_count' => 5, 'seating_method' => 'Parallel',
                'bench_capacity' => 1, 'max_students' => 25, 'row_labeling' => 'Numeric',
                'internal_invigilators_required' => 1, 'external_invigilators_required' => 1,
                'aisle_every_n_cols' => 3, 'aisle_every_n_rows' => 0
            ]
        ],
        [
            'hall_name' => 'Hall B2',
            'capacity' => 25,
            'block_name' => 'Block B',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 5, 'columns_count' => 5, 'seating_method' => 'Parallel',
                'bench_capacity' => 1, 'max_students' => 25, 'row_labeling' => 'Numeric',
                'internal_invigilators_required' => 1, 'external_invigilators_required' => 1,
                'aisle_every_n_cols' => 3, 'aisle_every_n_rows' => 0
            ]
        ],
        [
            'hall_name' => 'Hall C1',
            'capacity' => 25,
            'block_name' => 'Block C',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 5, 'columns_count' => 5, 'seating_method' => 'Parallel',
                'bench_capacity' => 1, 'max_students' => 25, 'row_labeling' => 'Numeric',
                'internal_invigilators_required' => 1, 'external_invigilators_required' => 1,
                'aisle_every_n_cols' => 3, 'aisle_every_n_rows' => 0
            ]
        ],
        [
            'hall_name' => 'Hall C2',
            'capacity' => 25,
            'block_name' => 'Block C',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 5, 'columns_count' => 5, 'seating_method' => 'Parallel',
                'bench_capacity' => 1, 'max_students' => 25, 'row_labeling' => 'Numeric',
                'internal_invigilators_required' => 1, 'external_invigilators_required' => 1,
                'aisle_every_n_cols' => 3, 'aisle_every_n_rows' => 0
            ]
        ],
        [
            'hall_name' => 'Hall D1',
            'capacity' => 25,
            'block_name' => 'Block D',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 5, 'columns_count' => 5, 'seating_method' => 'Parallel',
                'bench_capacity' => 1, 'max_students' => 25, 'row_labeling' => 'Numeric',
                'internal_invigilators_required' => 1, 'external_invigilators_required' => 1,
                'aisle_every_n_cols' => 3, 'aisle_every_n_rows' => 0
            ]
        ],
        [
            'hall_name' => 'Hall D2',
            'capacity' => 25,
            'block_name' => 'Block D',
            'college_id' => $collegeId,
            'settings' => [
                'rows_count' => 5, 'columns_count' => 5, 'seating_method' => 'Parallel',
                'bench_capacity' => 1, 'max_students' => 25, 'row_labeling' => 'Numeric',
                'internal_invigilators_required' => 1, 'external_invigilators_required' => 1,
                'aisle_every_n_cols' => 3, 'aisle_every_n_rows' => 0
            ]
        ]
    ];

    foreach (array_slice($hallsData, 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) {
            $results['halls']['skipped']++;
            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) {
            $results['halls']['created']++;

            // Handle hall settings
            $existingSettings = $pdo->prepare("SELECT hall_setting_id FROM hall_settings WHERE hall_id = ?");
            $existingSettings->execute([$hallId]);
            $existingSetting = $existingSettings->fetch();

            if ($existingSetting && !$force) {
                $results['settings']['skipped']++;
                continue;
            }

            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']
                ]);
            }
            $results['settings']['created']++;
        }
    }

    // Summary information
    $results['summary'] = [
        'total_halls_created' => $results['halls']['created'],
        'total_settings_created' => $results['settings']['created'],
        'total_halls_skipped' => $results['halls']['skipped'],
        'total_settings_skipped' => $results['settings']['skipped'],
        'hall_layout' => '5 rows × 5 columns = 25 students per hall',
        'seating_method' => 'Parallel',
        'invigilators_per_hall' => '1 Internal + 1 External'
    ];

    respond(true, 'Hall and hall settings seeded successfully with parallel seating for 25 students per hall', $results);

} catch (Throwable $e) {
    http_response_code(500);
    respond(false, $e->getMessage());
}
?>
