<?php
// Demo Panels Database Configuration
require_once dirname(__DIR__, 3) . '/includes/db.php';

// Demo panel format mapping
$DEMO_FORMATS = [
    'panel_best_run.html' => 'best_run',
    'panel_attempts.html' => 'attempts',
    'panel_attempts_oi.html' => 'attempts_oi',
    'panel_sections_oi.html' => 'sections_oi',
    'panel_runs_tricks.html' => 'runs_tricks',
    'panel_best_avg.html' => 'best_avg',
    'panel_ed_components.html' => 'ed_components',
    'panel_comparative.html' => 'comparative'
];

// Mock event data for demos
$DEMO_EVENT_DATA = [
    'event_id' => 'DEMO001',
    'event_name' => 'Demo Competition 2025',
    'sport' => 'snowboard',
    'judge_id' => 'J001',
    'heat_number' => 1,
    'run_number' => 1
];

// Mock participants for demos
$DEMO_PARTICIPANTS = [
    ['id' => 'P001', 'name' => 'Alex Rodriguez', 'bib' => 'A01'],
    ['id' => 'P002', 'name' => 'Sarah Chen', 'bib' => 'B02'],
    ['id' => 'P003', 'name' => 'Mike Johnson', 'bib' => 'C03'],
    ['id' => 'P004', 'name' => 'Emma Davis', 'bib' => 'D04'],
    ['id' => 'P005', 'name' => 'Carlos Santos', 'bib' => 'E05'],
    ['id' => 'P006', 'name' => 'Yuki Tanaka', 'bib' => 'F06']
];

/**
 * Get scoring format data by format ID
 */
function getFormatData($pdo, $formatId) {
    try {
        $stmt = $pdo->prepare("
            SELECT sf.*, 
                   sfj.min_judges, sfj.max_judges, sfj.scale_min, sfj.scale_max, 
                   sfj.scale_type, sfj.precision_decimal, sfj.drop_rule
            FROM scoring_formats sf
            LEFT JOIN scoring_format_judges sfj ON sf.format_id = sfj.format_id
            WHERE sf.format_id = ? AND sf.is_active = 1
        ");
        $stmt->execute([$formatId]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        return null;
    }
}

/**
 * Get format criteria/sections
 */
function getFormatCriteria($pdo, $formatId) {
    try {
        $stmt = $pdo->prepare("
            SELECT criteria_type, criteria_name, sort_order
            FROM scoring_format_criteria
            WHERE format_id = ?
            ORDER BY sort_order ASC, criteria_name ASC
        ");
        $stmt->execute([$formatId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        return [];
    }
}

/**
 * Get format diversity rules
 */
function getFormatDiversityRules($pdo, $formatId) {
    try {
        $stmt = $pdo->prepare("
            SELECT rule_type, scope, group_name, min_distinct, is_optional
            FROM scoring_format_diversity_rules
            WHERE format_id = ?
            ORDER BY rule_type, group_name
        ");
        $stmt->execute([$formatId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        return [];
    }
}

/**
 * Get figures for a sport
 */
function getSportFigures($pdo, $sport) {
    try {
        $stmt = $pdo->prepare("
            SELECT fc.category_name, fi.item_name, fi.sort_order
            FROM figure_categories fc
            LEFT JOIN figure_items fi ON fc.sport_name = fi.sport_name 
                                     AND fc.category_name = fi.category_name
            WHERE fc.sport_name = ? AND fc.is_active = 1 AND fi.is_active = 1
            ORDER BY fc.sort_order ASC, fc.category_name ASC, fi.sort_order ASC, fi.item_name ASC
        ");
        $stmt->execute([$sport]);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Group by category
        $figures = [];
        foreach ($results as $row) {
            if (!isset($figures[$row['category_name']])) {
                $figures[$row['category_name']] = [];
            }
            if (!empty($row['item_name'])) {
                $figures[$row['category_name']][] = $row['item_name'];
            }
        }
        
        return $figures;
    } catch (Exception $e) {
        return [];
    }
}

/**
 * Get format mode configuration
 */
function getFormatModeConfig($pdo, $formatId) {
    try {
        $stmt = $pdo->prepare("
            SELECT config_type, config_key, config_value
            FROM scoring_format_mode_config
            WHERE format_id = ?
            ORDER BY config_type, config_key
        ");
        $stmt->execute([$formatId]);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Group by config_type
        $config = [];
        foreach ($results as $row) {
            if (!isset($config[$row['config_type']])) {
                $config[$row['config_type']] = [];
            }
            $config[$row['config_type']][$row['config_key']] = $row['config_value'];
        }
        
        return $config;
    } catch (Exception $e) {
        return [];
    }
}

/**
 * Format mapping to panel files
 */
function getPanelFile($formatId) {
    $mapping = [
        'best_run' => 'panel_best_run.html',
        'attempts' => 'panel_attempts.html',
        'attempts_oi' => 'panel_attempts_oi.html',
        'sections_oi' => 'panel_sections_oi.html',
        'runs_tricks' => 'panel_runs_tricks.html',
        'best_avg' => 'panel_best_avg.html',
        'ed_components' => 'panel_ed_components.html',
        'comparative' => 'panel_comparative.html'
    ];
    
    return $mapping[$formatId] ?? null;
}

/**
 * Smarter panel resolver: prefer mode mapping, fallback to format_id substring rules.
 */
function getPanelFileForFormat($formatId, $mode) {
    $id = strtolower((string)$formatId);
    $m = strtolower((string)$mode);

    // Primary mapping by mode
    $byMode = [
        'best_run' => 'panel_best_run.html',
        'attempts' => 'panel_attempts.html',
        'attempts_oi' => 'panel_attempts_oi.html',
        'sections_plus_oi' => 'panel_sections_oi.html',
        'sections_oi' => 'panel_sections_oi.html',
        'runs_tricks' => 'panel_runs_tricks.html',
        'best_avg' => 'panel_best_avg.html',
        'ed_components' => 'panel_ed_components.html',
        'comparative' => 'panel_comparative.html',
    ];
    if (isset($byMode[$m])) return $byMode[$m];

    // Fallback heuristics using format_id
    if (strpos($id, 'comparative') !== false) return 'panel_comparative.html';
    if (strpos($id, 'best') !== false && strpos($id, 'run') !== false) return 'panel_best_run.html';
    if (strpos($id, 'attempt') !== false && strpos($id, 'oi') !== false) return 'panel_attempts_oi.html';
    if (strpos($id, 'attempt') !== false) return 'panel_attempts.html';
    if ((strpos($id, 'sections') !== false && strpos($id, 'oi') !== false) || strpos($id, 'sections_oi') !== false) return 'panel_sections_oi.html';
    if (strpos($id, 'runs_tricks') !== false) return 'panel_runs_tricks.html';
    if (strpos($id, 'best_avg') !== false || strpos($id, 'average') !== false) return 'panel_best_avg.html';
    if (strpos($id, 'ed_components') !== false || strpos($id, 'components') !== false) return 'panel_ed_components.html';

    // Last fallback: if original mapping knows it
    $legacy = getPanelFile($formatId);
    return $legacy;
}

/**
 * Error response helper
 */
function sendError($message, $code = 400) {
    http_response_code($code);
    echo json_encode(['error' => $message]);
    exit;
}

/**
 * Success response helper
 */
function sendSuccess($data) {
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}
?>
