<?php
require_once '../config/database.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

try {
    $db = getDB();

    // Disable foreign key checks temporarily
    $db->exec("SET FOREIGN_KEY_CHECKS = 0");

    // Clean all data from tables (keep table structure, remove all rows)
    $tables = [
        'users',
        'students',
        'attendance',
        'timing_records',
        'sprint_races',
        'sprint_rounds',
        'sprint_results',
        'fee_receipts',
        'equipment',
        'equipment_transactions',
        'expenses',
    ];

    $cleaned = [];
    foreach ($tables as $table) {
        $db->exec("TRUNCATE TABLE {$table}");
        $cleaned[] = $table;
    }

    // Re-enable foreign key checks
    $db->exec("SET FOREIGN_KEY_CHECKS = 1");

    // Insert back only the admin and assistant users (keep these)
    $db->exec("INSERT INTO users (username, password_hash, name, role, phone, email) VALUES
        ('admin', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Admin User', 'admin', '9999999999', 'admin@skatepro.com'),
        ('assistant', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Coach Rahul', 'assistant', '8888888888', 'coach@skatepro.com')");

    // Insert default batches
    $db->exec("INSERT INTO batches (id, name, time_slot) VALUES
        (1, 'Morning Batch A', '6:00 AM - 8:00 AM'),
        (2, 'Evening Batch B', '4:00 PM - 6:00 PM'),
        (3, 'Weekend Batch', '9:00 AM - 12:00 PM')");

    sendJson([
        'success' => true,
        'message' => 'All data cleaned successfully!',
        'tables_cleaned' => $cleaned,
        'note' => 'Only admin and assistant login remain. All student data removed. Ready for import.'
    ]);

} catch (Exception $e) {
    sendJson(['error' => $e->getMessage()], 500);
}
