<?php
/**
 * Demo Panels API - List all available scoring formats
 */

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

// Start output buffering to catch any unexpected output
ob_start();

try {
    require_once 'config.php';
} catch (Exception $e) {
    // Clear any output and send error
    ob_clean();
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Config error: ' . $e->getMessage()]);
    exit;
}

// Clear any output from includes and set JSON header
ob_clean();
header('Content-Type: application/json');

try {
    // Check if database connection exists
    if (!isset($pdo)) {
        throw new Exception('Database connection not available');
    }
    
    // Get all active scoring formats
    $stmt = $pdo->prepare("
        SELECT sf.format_id, sf.name, sf.sport, sf.mode,
               sfj.scale_min, sfj.scale_max, sfj.scale_type,
               (SELECT COUNT(*) FROM scoring_format_criteria sfc WHERE sfc.format_id = sf.format_id) as criteria_count,
               (SELECT COUNT(*) FROM scoring_format_diversity_rules sfdr WHERE sfdr.format_id = sf.format_id) as diversity_rules_count
        FROM scoring_formats sf
        LEFT JOIN scoring_format_judges sfj ON sf.format_id = sfj.format_id
        WHERE sf.is_active = 1
        ORDER BY sf.sport ASC, sf.name ASC
    ");
    $stmt->execute();
    $formats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Add panel file mapping and demo availability using smarter resolver
    foreach ($formats as &$format) {
        $panel = getPanelFileForFormat($format['format_id'], $format['mode'] ?? '');
        // Verify the panel file actually exists in the demo_panels folder
        $panelPath = __DIR__ . '/../' . $panel;
        $exists = $panel && file_exists($panelPath);
        $format['panel_file'] = $panel;
        $format['demo_available'] = $exists;
    }
    
    $response = [
        'formats' => $formats,
        'total_count' => count($formats),
        'demo_event' => $GLOBALS['DEMO_EVENT_DATA']
    ];
    
    sendSuccess($response);
    
} catch (Exception $e) {
    sendError('Database error: ' . $e->getMessage(), 500);
}
?>
