<?php
header('Content-Type: application/json');
header('Cache-Control: no-cache, must-revalidate');

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors in JSON response

include '../includes/auth.php';
include '../includes/db.php';

$event_id = $_GET['event_id'] ?? null;

if (!$event_id) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Event ID is required'
    ]);
    exit;
}

try {
    // Verify event exists
    $event_stmt = $pdo->prepare("SELECT id FROM events WHERE id = ?");
    $event_stmt->execute([$event_id]);
    
    if (!$event_stmt->fetch()) {
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'message' => 'Event not found'
        ]);
        exit;
    }

    // Fetch updated configurations
    $configs_stmt = $pdo->prepare("
        SELECT 
            id,
            config_name,
            view_type,
            heat_number,
            category_filter,
            gender_filter,
            country_filter,
            custom_filters,
            sort_order,
            is_active,
            created_at,
            updated_at
        FROM public_dashboard_configs
        WHERE event_id = ? AND view_type = 'summary_table' AND is_active = 1
        ORDER BY sort_order ASC, config_name ASC
    ");
    $configs_stmt->execute([$event_id]);
    $configurations = $configs_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'message' => 'Configurations refreshed successfully',
        'count' => count($configurations),
        'configurations' => $configurations,
        'timestamp' => date('Y-m-d H:i:s')
    ]);

} catch (Exception $e) {
    error_log("Error refreshing start list configs: " . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred while refreshing configurations'
    ]);
}
?>
