<?php
session_start();
include '../includes/db.php';

/**
 * Main function to generate final results based on configuration
 */
function generateFinalResults($config) {
    global $pdo;
    
    try {
        // Get event settings first
        $event_settings = getEventSettings($config['event_id']);
        
        // Get scores for selected heats with table structure
        $score_data = getScoresForHeats($config, $event_settings);
        
        // Calculate final scores based on scoring method
        $results = calculateFinalScores($config, $score_data, $event_settings);
        
        // Sort results
        $sorted_results = sortResults($config, $results);
        
        return [
            'success' => true,
            'results' => $sorted_results,
            'config' => $config,
            'event_settings' => $event_settings
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

/**
 * Get event settings
 */
function getEventSettings($event_id) {
    global $pdo;
    
    $heats_total = 2;
    $runs_per_heat = 2;
    
    if ($event_id) {
        $event_settings_stmt = $pdo->prepare("SELECT heats_total, runs_per_heat FROM events WHERE id = ?");
        $event_settings_stmt->execute([$event_id]);
        $event_settings = $event_settings_stmt->fetch(PDO::FETCH_ASSOC);
        if ($event_settings) {
            $heats_total = intval($event_settings['heats_total']);
            $runs_per_heat = intval($event_settings['runs_per_heat']);
        }
    }
    
    return [
        'heats_total' => $heats_total,
        'runs_per_heat' => $runs_per_heat
    ];
}

/**
 * Get scores for specified heats and participants using the working query structure
 */
function getScoresForHeats($config, $event_settings) {
    global $pdo;
    
    $selected_heats = json_decode($config['selected_heats'], true) ?: [];
    $categories = json_decode($config['categories'], true) ?: [];
    $genders = json_decode($config['gender'], true) ?: [];
    $year_from = $config['year_from'] ?: null;
    $year_to = $config['year_to'] ?: null;
    
    $summary_data = [];
    $heat_numbers = [];
    
    if (empty($selected_heats)) {
        // If no heats selected, use all heats from 1 to heats_total
        for ($h = 1; $h <= $event_settings['heats_total']; $h++) {
            $selected_heats[] = $h;
        }
    }
    
    // Get all categories if none specified
    if (empty($categories)) {
        $categories = $pdo
            ->query("SELECT DISTINCT category FROM participants ORDER BY category")
            ->fetchAll(PDO::FETCH_COLUMN);
    }
    
    foreach ($categories as $cat) {
        // Use the exact same query structure that works in ajax_summary_table.php
        $sql = "
            SELECT
                p.category,
                ep.bib_number as bib,
                p.first_name,
                p.last_name,
                p.gender,
                p.club,
                p.fis_code,
                p.licence_code,
                YEAR(p.date_of_birth) as birth_year,
                ep.heat_number,
                r.run_number,
                AVG(s.score_value) AS avg_score
            FROM runs r
            JOIN event_participants ep
              ON r.event_participant_id = ep.id
            JOIN participants p
              ON ep.participant_id = p.id
            LEFT JOIN scores s
              ON r.id = s.run_id
            WHERE ep.event_id = ?
              AND p.category = ?
        ";
        
        $params = [$config['event_id'], $cat];
        
        // Add heat filter if specific heats are selected
        if (!empty($selected_heats)) {
            $heat_placeholders = str_repeat('?,', count($selected_heats) - 1) . '?';
            $sql .= " AND ep.heat_number IN ($heat_placeholders)";
            $params = array_merge($params, $selected_heats);
        }
        
        // Add gender filter
        if (!empty($genders)) {
            $gender_placeholders = str_repeat('?,', count($genders) - 1) . '?';
            $sql .= " AND p.gender IN ($gender_placeholders)";
            $params = array_merge($params, $genders);
        }
        
        // Add birth year filters
        if ($year_from) {
            $sql .= " AND YEAR(p.date_of_birth) >= ?";
            $params[] = $year_from;
        }
        
        if ($year_to) {
            $sql .= " AND YEAR(p.date_of_birth) <= ?";
            $params[] = $year_to;
        }
        
        $sql .= " GROUP BY p.id, ep.heat_number, r.run_number";
        $sql .= " ORDER BY ep.heat_number, r.run_number";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($rows as $row) {
            // Skip if gender filter doesn't match (additional check)
            if (!empty($genders) && !in_array($row['gender'], $genders)) {
                continue;
            }

            $key = "{$row['bib']} - {$row['first_name']} {$row['last_name']}";
            $score = floatval($row['avg_score']);
            $heat = $row['heat_number'];
            $run = $row['run_number'];
            $code = "H{$heat}R{$run}";

            // Store participant info
            $summary_data[$cat][$key]['bib_number'] = $row['bib'];
            $summary_data[$cat][$key]['first_name'] = $row['first_name'];
            $summary_data[$cat][$key]['last_name'] = $row['last_name'];
            $summary_data[$cat][$key]['club'] = $row['club'] ?? '-';
            $summary_data[$cat][$key]['gender'] = $row['gender'];
            $summary_data[$cat][$key]['category'] = $row['category'];
            $summary_data[$cat][$key]['fis_code'] = $row['fis_code'] ?? '';
            $summary_data[$cat][$key]['licence_code'] = $row['licence_code'] ?? '';
            $summary_data[$cat][$key]['birth_year'] = $row['birth_year'] ?? null;
            
            // Store scores
            $summary_data[$cat][$key][$code] = number_format($score, 2);
            $summary_data[$cat][$key]['raw'][$code] = $score;
            $summary_data[$cat][$key]['all_scores'][] = $score;

            $heat_numbers[$code] = true;
        }
    }

    // Compute best and average for each heat, and overall statistics
    foreach ($summary_data as $cat => &$participants) {
        foreach ($participants as &$p) {
            // Calculate heat-specific stats
            foreach ($selected_heats as $h) {
                $scores = [];
                for ($r = 1; $r <= $event_settings['runs_per_heat']; $r++) {
                    $score = $p['raw']["H{$h}R{$r}"] ?? null;
                    if ($score !== null) $scores[] = $score;
                }
                if (!empty($scores)) {
                    $p["H{$h}Best"] = number_format(max($scores), 2);
                    $p["H{$h}Average"] = number_format(array_sum($scores)/count($scores), 2);
                    $p["H{$h}BestRaw"] = max($scores);
                    $p["H{$h}AverageRaw"] = array_sum($scores)/count($scores);
                }
            }
            
            // Calculate overall statistics
            $all_scores = $p['all_scores'] ?? [];
            if (!empty($all_scores)) {
                $p["OverallBest"] = number_format(max($all_scores), 2);
                $p["OverallBestRaw"] = max($all_scores);
                
                // Collect all heat averages for HighestAverage
                $heat_avgs = [];
                foreach ($selected_heats as $h) {
                    if (isset($p["H{$h}AverageRaw"])) {
                        $heat_avgs[] = $p["H{$h}AverageRaw"];
                    }
                }
                $heat_avgs = array_filter($heat_avgs);
                $p["HighestAverage"] = !empty($heat_avgs) 
                    ? number_format(max($heat_avgs), 2) 
                    : '-';
                $p["HighestAverageRaw"] = !empty($heat_avgs) ? max($heat_avgs) : 0;
            }
        }
    }
    
    return [
        'summary_data' => $summary_data,
        'heat_numbers' => array_keys($heat_numbers),
        'runs_per_heat' => $event_settings['runs_per_heat'],
        'selected_heats' => $selected_heats
    ];
}

/**
 * Calculate final scores based on scoring method
 */
function calculateFinalScores($config, $score_data, $event_settings) {
    $scoring_method = $config['scoring_method'];
    $results = [];
    $summary_data = $score_data['summary_data'];
    
    // Flatten all participants from all categories
    foreach ($summary_data as $category => $category_participants) {
        foreach ($category_participants as $participant_key => $participant_data) {
            $final_score = calculateParticipantFinalScore($scoring_method, $config, $participant_data);
            
            $participant_data['final_score'] = $final_score;
            $participant_data['participant_key'] = $participant_key;
            
            $results[] = $participant_data;
        }
    }
    
    return $results;
}

/**
 * Calculate individual participant final score
 */
function calculateParticipantFinalScore($method, $config, $participant_data) {
    $all_scores = $participant_data['all_scores'] ?? [];
    
    if (empty($all_scores)) {
        return 0;
    }
    
    switch ($method) {
        case 'best_single':
            return $participant_data['OverallBestRaw'] ?? 0;
            
        case 'best_average':
            $count = intval($config['count_best_runs']) ?: 3;
            return calculateBestAverage($all_scores, $count);
            
        case 'highest_heat_average':
            return $participant_data['HighestAverageRaw'] ?? 0;
            
        case 'total_points':
            return array_sum($all_scores);
            
        case 'average_all':
            return array_sum($all_scores) / count($all_scores);
            
        default:
            return $participant_data['OverallBestRaw'] ?? 0;
    }
}

/**
 * Calculate best average from X runs
 */
function calculateBestAverage($scores, $count) {
    if (count($scores) < $count) {
        return count($scores) > 0 ? array_sum($scores) / count($scores) : 0;
    }
    
    rsort($scores); // Sort descending
    $best_scores = array_slice($scores, 0, $count);
    
    return array_sum($best_scores) / count($best_scores);
}

/**
 * Sort results based on configuration
 */
function sortResults($config, $results) {
    $sort_by = $config['sort_by'] ?? 'final_score';
    $sort_order = $config['sort_order'] ?? 'DESC';
    
    usort($results, function($a, $b) use ($sort_by, $sort_order) {
        $value_a = getResultValue($a, $sort_by);
        $value_b = getResultValue($b, $sort_by);
        
        if ($sort_order === 'ASC') {
            return $value_a <=> $value_b;
        } else {
            return $value_b <=> $value_a;
        }
    });
    
    // Add ranking with tie handling
    $current_rank = 1;
    $previous_score = null;
    $participants_with_same_rank = 0;
    
    foreach ($results as $index => &$result) {
        $current_score = $result['final_score'];
        
        if ($previous_score !== null && $current_score != $previous_score) {
            $current_rank += $participants_with_same_rank;
            $participants_with_same_rank = 1;
        } else {
            $participants_with_same_rank++;
        }
        
        $result['rank'] = $current_rank;
        $previous_score = $current_score;
    }
    
    return $results;
}

/**
 * Get value for sorting
 */
function getResultValue($result, $sort_by) {
    switch ($sort_by) {
        case 'final_score':
            return floatval($result['final_score']);
        case 'OverallBest':
            return floatval($result['OverallBestRaw'] ?? 0);
        case 'HighestAverage':
            return floatval($result['HighestAverageRaw'] ?? 0);
        case 'name':
            return $result['first_name'] . ' ' . $result['last_name'];
        case 'bib_number':
            return intval($result['bib_number']);
        case 'category':
            return $result['category'];
        case 'club':
            return $result['club'];
        default:
            return $result['final_score'];
    }
}

/**
 * Get column CSS class based on header type
 */
function getColClass($header) {
    if (preg_match('/^H\d+Best$/', $header)) return 'col-best table-primary';
    if (preg_match('/^H\d+Average$/', $header)) return 'col-average table-secondary';
    if ($header === 'OverallBest') return 'col-overall-best table-success';
    if ($header === 'HighestAverage') return 'col-highest-average table-info';
    if ($header === 'final_score') return 'col-final-score table-warning';
    return '';
}

/**
 * Generate HTML table with heat columns structure
 */
function generateResultsTable($config, $results) {
    $display_columns = json_decode($config['display_columns'], true) ?: [];
    $selected_heats = json_decode($config['selected_heats'], true) ?: [];
    
    // Get event settings
    $event_settings = getEventSettings($config['event_id']);
    $runs_per_heat = $event_settings['runs_per_heat'];
    
    // If no heats selected, use all heats
    if (empty($selected_heats)) {
        for ($h = 1; $h <= $event_settings['heats_total']; $h++) {
            $selected_heats[] = $h;
        }
    }
    
    // Build header list
    $final_headers = [];
    foreach ($selected_heats as $h) {
        if (in_array('individualheats', $display_columns)) {
           for ($r = 1; $r <= $runs_per_heat; $r++) {
            $final_headers[] = "H{$h}R{$r}";
        }
        }
        
        if (in_array('summary', $display_columns)) {
            $final_headers[] = "H{$h}Best";
            $final_headers[] = "H{$h}Average";
        }
    }
    
    if (in_array('summary', $display_columns)) {
        $final_headers[] = 'OverallBest';
        $final_headers[] = 'HighestAverage';
    }
    
    ob_start();
    ?>
    <div class="table-responsive">
        <table class="table table-striped table-hover table-sm">
            <thead class="table-light">
                <tr>
                    <th scope="col"><span>Rank</span></th>
                    <?php if (in_array('bibnumber', $display_columns)): ?>
                        <th scope="col"><span>BIB</span></th>
                    <?php endif; ?>
                    <th scope="col"><span>Participant</span></th>
                    <?php if (in_array('category', $display_columns)): ?>
                        <th scope="col"><span>Category</span></th>
                    <?php endif; ?>
                    <?php if (in_array('club', $display_columns)): ?>
                        <th scope="col"><span>Club</span></th>
                    <?php endif; ?>
                    <?php if (in_array('gender', $display_columns)): ?>
                        <th scope="col"><span>Gender</span></th>
                    <?php endif; ?>
                    <?php if (in_array('fiscode', $display_columns)): ?>
                        <th scope="col"><span>FIS Code</span></th>
                    <?php endif; ?>
                    <?php if (in_array('licencecode', $display_columns)): ?>
                        <th scope="col"><span>Licence</span></th>
                    <?php endif; ?>
                    <?php if (in_array('age', $display_columns)): ?>
                        <th scope="col"><span>Age</span></th>
                    <?php endif; ?>
                    
                    <?php foreach ($final_headers as $h): ?>
                        <th scope="col" class="angle-th <?= getColClass($h) ?>"><span><?= $h ?></span></th>
                    <?php endforeach; ?>
                    
                    <th scope="col" class="<?= getColClass('final_score') ?>"><span>Final Score</span></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($results as $result): ?>
                    <tr>
                        <td scope="row"><span><?= $result['rank'] ?></span></td>
                        <?php if (in_array('bibnumber', $display_columns)): ?>
                            <td><span><?= htmlspecialchars($result['bib_number'] ?? '-') ?></span></td>
                        <?php endif; ?>
                        <td><span><?= htmlspecialchars($result['first_name'] . ' ' . $result['last_name']) ?></span></td>
                        <?php if (in_array('category', $display_columns)): ?>
                            <td><span><?= htmlspecialchars($result['category'] ?? '-') ?></span></td>
                        <?php endif; ?>
                        <?php if (in_array('club', $display_columns)): ?>
                            <td><span><?= htmlspecialchars($result['club'] ?? '-') ?></span></td>
                        <?php endif; ?>
                        <?php if (in_array('gender', $display_columns)): ?>
                            <td><span><?= htmlspecialchars($result['gender'] ?? '-') ?></span></td>
                        <?php endif; ?>
                        <?php if (in_array('fiscode', $display_columns)): ?>
                            <td><span><?= htmlspecialchars($result['fis_code'] ?? '-') ?></span></td>
                        <?php endif; ?>
                        <?php if (in_array('licencecode', $display_columns)): ?>
                            <td><span><?= htmlspecialchars($result['licence_code'] ?? '-') ?></span></td>
                        <?php endif; ?>
                        <?php if (in_array('age', $display_columns) && $result['birth_year']): ?>
                            <td><span><?= date('Y') - $result['birth_year'] ?></span></td>
                        <?php endif; ?>
                        
                        <?php foreach ($final_headers as $h): ?>
                            <td class="<?= getColClass($h) ?>">
                                <span><?= $result[$h] ?? '-' ?></span>
                            </td>
                        <?php endforeach; ?>
                        
                        <td class="<?= getColClass('final_score') ?>">
                            <span><strong><?= number_format($result['final_score'], 2) ?></strong></span>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <?php if (count($results) > 0): ?>
            <div class="mt-3">
                <small class="text-muted">
                    Total participants: <?= count($results) ?> | 
                    Scoring method: <?= ucfirst(str_replace('_', ' ', $config['scoring_method'])) ?> |
                    Heats: <?= implode(', ', $selected_heats) ?>
                </small>
            </div>
        <?php endif; ?>
    </div>
    
    <style>
    .table th, .table td {
        white-space: nowrap;
        vertical-align: middle;
        text-align: center;
    }
    
    .table th span, .table td span {
        display: block;
       
    }
    
    .angle-th {
        font-size: 0.875rem;
        writing-mode: vertical-rl;
        text-orientation: mixed;
        min-width: 40px;
    }
    
    .col-best { background-color: rgba(13, 110, 253, 0.1) !important; }
    .col-average { background-color: rgba(108, 117, 125, 0.1) !important; }
    .col-overall-best { background-color: rgba(25, 135, 84, 0.1) !important; }
    .col-highest-average { background-color: rgba(13, 202, 240, 0.1) !important; }
    .col-final-score { background-color: rgba(255, 193, 7, 0.2) !important; font-weight: bold; }
    </style>
    <?php
    return ob_get_clean();
}

/**
 * Export results to CSV format
 */
function exportResultsToCSV($config, $results) {
    $display_columns = json_decode($config['display_columns'], true) ?: [];
    $selected_heats = json_decode($config['selected_heats'], true) ?: [];
    
    // Get event settings
    $event_settings = getEventSettings($config['event_id']);
    $runs_per_heat = $event_settings['runs_per_heat'];
    
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="final_results_' . date('Y-m-d_H-i-s') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Build headers
    $headers = ['Rank'];
    if (in_array('bibnumber', $display_columns)) $headers[] = 'BIB Number';
    $headers[] = 'Name';
    if (in_array('category', $display_columns)) $headers[] = 'Category';
    if (in_array('club', $display_columns)) $headers[] = 'Club';
    if (in_array('gender', $display_columns)) $headers[] = 'Gender';
    if (in_array('fiscode', $display_columns)) $headers[] = 'FIS Code';
    if (in_array('licencecode', $display_columns)) $headers[] = 'Licence Code';
    if (in_array('age', $display_columns)) $headers[] = 'Age';
    
    // Add heat columns
    foreach ($selected_heats as $h) {
        for ($r = 1; $r <= $runs_per_heat; $r++) {
            $headers[] = "H{$h}R{$r}";
        }
        if (in_array('heatstats', $display_columns)) {
            $headers[] = "H{$h}Best";
            $headers[] = "H{$h}Average";
        }
    }
    
    if (in_array('summary', $display_columns)) {
        $headers[] = 'OverallBest';
        $headers[] = 'HighestAverage';
    }
    
    $headers[] = 'Final Score';
    
    fputcsv($output, $headers);
    
    // Write data
    foreach ($results as $result) {
        $row = [$result['rank']];
        if (in_array('bibnumber', $display_columns)) $row[] = $result['bib_number'] ?? '';
        $row[] = $result['first_name'] . ' ' . $result['last_name'];
        if (in_array('category', $display_columns)) $row[] = $result['category'] ?? '';
        if (in_array('club', $display_columns)) $row[] = $result['club'] ?? '';
        if (in_array('gender', $display_columns)) $row[] = $result['gender'] ?? '';
        if (in_array('fiscode', $display_columns)) $row[] = $result['fis_code'] ?? '';
        if (in_array('licencecode', $display_columns)) $row[] = $result['licence_code'] ?? '';
        if (in_array('age', $display_columns)) $row[] = $result['birth_year'] ? date('Y') - $result['birth_year'] : '';
        
        // Add heat data
        foreach ($selected_heats as $h) {
            for ($r = 1; $r <= $runs_per_heat; $r++) {
                $row[] = $result["H{$h}R{$r}"] ?? '';
            }
            if (in_array('heatstats', $display_columns)) {
                $row[] = $result["H{$h}Best"] ?? '';
                $row[] = $result["H{$h}Average"] ?? '';
            }
        }
        
        if (in_array('summary', $display_columns)) {
            $row[] = $result['OverallBest'] ?? '';
            $row[] = $result['HighestAverage'] ?? '';
        }
        
        $row[] = number_format($result['final_score'], 2);
        
        fputcsv($output, $row);
    }
    
    fclose($output);
    exit;
}

/**
 * Get all saved configurations for an event
 */
function getSavedConfigurations($event_id) {
    global $pdo;
    
    try {
        $stmt = $pdo->prepare("
            SELECT id, config_name, config_data, created_at, updated_at
            FROM result_configurations
            WHERE event_id = ?
            ORDER BY updated_at DESC
        ");
        $stmt->execute([$event_id]);
        $configs = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($configs as &$config) {
            $config['config_data'] = json_decode($config['config_data'], true);
        }
        
        return [
            'success' => true,
            'configurations' => $configs
        ];
    } catch (Exception $e) {
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

/**
 * Get a specific configuration by ID
 */
function getConfiguration($config_id) {
    global $pdo;
    
    try {
        $stmt = $pdo->prepare("SELECT * FROM result_configurations WHERE id = ?");
        $stmt->execute([$config_id]);
        $config = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($config) {
            $config['config_data'] = json_decode($config['config_data'], true);
            return [
                'success' => true,
                'configuration' => $config
            ];
        } else {
            return [
                'success' => false,
                'error' => 'Configuration not found'
            ];
        }
    } catch (Exception $e) {
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

/**
 * Update an existing configuration
 */
function updateConfiguration($config_id, $config_data) {
    global $pdo;
    
    try {
        $check_stmt = $pdo->prepare("SELECT id FROM result_configurations WHERE id = ?");
        $check_stmt->execute([$config_id]);
        
        if (!$check_stmt->fetch()) {
            return [
                'success' => false,
                'error' => 'Configuration not found'
            ];
        }
        
        $stmt = $pdo->prepare("
            UPDATE result_configurations 
            SET config_name = ?, config_data = ?, updated_at = NOW()
            WHERE id = ?
        ");
        
        $result = $stmt->execute([
            $config_data['config_name'],
            json_encode($config_data),
            $config_id
        ]);
        
        return [
            'success' => $result,
            'message' => $result ? 'Configuration updated successfully' : 'Failed to update configuration'
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

/**
 * Delete a configuration
 */
function deleteConfiguration($config_id) {
    global $pdo;
    
    try {
        $check_stmt = $pdo->prepare("SELECT config_name FROM result_configurations WHERE id = ?");
        $check_stmt->execute([$config_id]);
        $config = $check_stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$config) {
            return [
                'success' => false,
                'error' => 'Configuration not found'
            ];
        }
        
        $stmt = $pdo->prepare("DELETE FROM result_configurations WHERE id = ?");
        $result = $stmt->execute([$config_id]);
        
        return [
            'success' => $result,
            'message' => $result ? "Configuration '{$config['config_name']}' deleted successfully" : 'Failed to delete configuration'
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

/**
 * Duplicate a configuration with a new name
 */
function duplicateConfiguration($config_id, $new_name) {
    global $pdo;
    
    try {
        $original = getConfiguration($config_id);
        
        if (!$original['success']) {
            return $original;
        }
        
        $config_data = $original['configuration']['config_data'];
        $config_data['config_name'] = $new_name;
        
        $check_stmt = $pdo->prepare("
            SELECT id FROM result_configurations 
            WHERE event_id = ? AND config_name = ?
        ");
        $check_stmt->execute([$config_data['event_id'], $new_name]);
        
        if ($check_stmt->fetch()) {
            return [
                'success' => false,
                'error' => 'Configuration with this name already exists'
            ];
        }
        
        $stmt = $pdo->prepare("
            INSERT INTO result_configurations (event_id, config_name, config_data, created_at)
            VALUES (?, ?, ?, NOW())
        ");
        
        $result = $stmt->execute([
            $config_data['event_id'],
            $new_name,
            json_encode($config_data)
        ]);
        
        return [
            'success' => $result,
            'message' => $result ? 'Configuration duplicated successfully' : 'Failed to duplicate configuration',
            'new_id' => $result ? $pdo->lastInsertId() : null
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

/**
 * Preview configuration without running full calculation
 */
function previewConfiguration($config) {
    $preview_data = [
        'config_name' => $config['config_name'] ?? 'Unnamed Configuration',
        'event_id' => $config['event_id'],
        'selected_heats' => json_decode($config['selected_heats'], true) ?: [],
        'categories' => json_decode($config['categories'], true) ?: [],
        'genders' => json_decode($config['gender'], true) ?: [],
        'year_range' => [
            'from' => $config['year_from'] ?: 'No limit',
            'to' => $config['year_to'] ?: 'No limit'
        ],
        'scoring_method' => $config['scoring_method'],
        'scoring_options' => [],
        'display_columns' => json_decode($config['display_columns'], true) ?: [],
        'sort_by' => $config['sort_by'],
        'sort_order' => $config['sort_order']
    ];
    
    switch ($config['scoring_method']) {
        case 'best_average':
            $preview_data['scoring_options']['runs_to_average'] = $config['count_best_runs'] ?: 3;
            break;
        case 'best_x_from_n':
            $preview_data['scoring_options']['best_x_runs'] = $config['count_best_runs'] ?: 2;
            $preview_data['scoring_options']['from_n_heats'] = $config['count_from_heats'] ?: 3;
            break;
    }
    
    try {
        $participants = getFilteredParticipants($config);
        $preview_data['estimated_participants'] = count($participants);
    } catch (Exception $e) {
        $preview_data['estimated_participants'] = 'Unable to calculate';
    }
    
    return [
        'success' => true,
        'preview' => $preview_data
    ];
}

/**
 * Generate HTML preview of configuration
 */
function generateConfigurationPreviewHTML($preview_data) {
    ob_start();
    ?>
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0"><?= htmlspecialchars($preview_data['config_name']) ?></h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <h6><i class="fas fa-fire me-2"></i>Selected Heats</h6>
                    <?php if (!empty($preview_data['selected_heats'])): ?>
                        <p class="text-muted">Heats: <?= implode(', ', $preview_data['selected_heats']) ?></p>
                    <?php else: ?>
                        <p class="text-warning">No heats selected</p>
                    <?php endif; ?>
                    
                    <h6><i class="fas fa-users me-2"></i>Participants</h6>
                    <p class="text-muted">
                        Estimated participants: <strong><?= $preview_data['estimated_participants'] ?></strong>
                    </p>
                    
                    <h6><i class="fas fa-filter me-2"></i>Filters</h6>
                    <ul class="list-unstyled text-muted">
                        <?php if (!empty($preview_data['categories'])): ?>
                            <li><strong>Categories:</strong> <?= implode(', ', $preview_data['categories']) ?></li>
                        <?php endif; ?>
                        
                        <?php if (!empty($preview_data['genders'])): ?>
                            <li><strong>Genders:</strong> <?= implode(', ', $preview_data['genders']) ?></li>
                        <?php endif; ?>
                        
                        <li><strong>Birth Year:</strong> 
                            <?= $preview_data['year_range']['from'] ?> - <?= $preview_data['year_range']['to'] ?>
                        </li>
                    </ul>
                </div>
                
                <div class="col-md-6">
                    <h6><i class="fas fa-calculator me-2"></i>Scoring Method</h6>
                    <p class="text-muted">
                        <strong><?= ucfirst(str_replace('_', ' ', $preview_data['scoring_method'])) ?></strong>
                        <?php if (!empty($preview_data['scoring_options'])): ?>
                            <br>
                            <?php foreach ($preview_data['scoring_options'] as $key => $value): ?>
                                <small><?= ucfirst(str_replace('_', ' ', $key)) ?>: <?= $value ?></small><br>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </p>
                    
                    <h6><i class="fas fa-table me-2"></i>Display Options</h6>
                    <p class="text-muted">
                        <strong>Sort by:</strong> <?= ucfirst(str_replace('_', ' ', $preview_data['sort_by'])) ?> 
                        (<?= $preview_data['sort_order'] === 'ASC' ? 'Ascending' : 'Descending' ?>)
                    </p>
                    
                    <?php if (!empty($preview_data['display_columns'])): ?>
                        <p class="text-muted">
                            <strong>Columns:</strong> <?= implode(', ', array_map('ucfirst', $preview_data['display_columns'])) ?>
                        </p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' || $_SERVER['REQUEST_METHOD'] === 'GET') {
    header('Content-Type: application/json');
    
    $action = $_POST['action'] ?? $_GET['action'] ?? 'generate';
    
    if ($action === 'generate') {
        $config = [
            'event_id' => $_REQUEST['event_id'] ?? null,
            'config_name' => $_REQUEST['config_name'] ?? 'Generated Results',
            'selected_heats' => $_REQUEST['selected_heats'] ?? '[]',
            'categories' => $_REQUEST['categories'] ?? '[]',
            'gender' => $_REQUEST['gender'] ?? '[]',
            'year_from' => $_REQUEST['year_from'] ?? '',
            'year_to' => $_REQUEST['year_to'] ?? '',
            'scoring_method' => $_REQUEST['scoring_method'] ?? 'best_single',
            'count_best_runs' => $_REQUEST['count_best_runs'] ?? '',
            'count_from_heats' => $_REQUEST['count_from_heats'] ?? '',
            'display_columns' => $_REQUEST['display_columns'] ?? '[]',
            'sort_by' => $_REQUEST['sort_by'] ?? 'final_score',
            'sort_order' => $_REQUEST['sort_order'] ?? 'DESC'
        ];
        
        if (!$config['event_id']) {
            echo json_encode(['success' => false, 'error' => 'Event ID is required']);
            exit;
        }
        
        $result = generateFinalResults($config);
        
        if ($result['success']) {
            if (isset($_REQUEST['export'])) {
                exportResultsToCSV($config, $result['results']);
                exit;
            }
            
            if (isset($_REQUEST['format']) && $_REQUEST['format'] === 'html') {
                $html_table = generateResultsTable($config, $result['results']);
                echo json_encode([
                    'success' => true,
                    'html' => $html_table,
                    'count' => count($result['results'])
                ]);
            } else {
                echo json_encode([
                    'success' => true,
                    'results' => $result['results'],
                    'count' => count($result['results']),
                    'config' => $config
                ]);
            }
        } else {
            echo json_encode($result);
        }
        
    } elseif ($action === 'load_config') {
        $config_id = $_REQUEST['config_id'] ?? null;
        
        if ($config_id) {
            try {
                $stmt = $pdo->prepare("SELECT * FROM result_configurations WHERE id = ?");
                $stmt->execute([$config_id]);
                $config_row = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($config_row) {
                    $config_data = json_decode($config_row['config_data'], true);
                    $result = generateFinalResults($config_data);
                    
                    if ($result['success']) {
                        echo json_encode([
                            'success' => true,
                            'results' => $result['results'],
                            'config' => $config_data,
                            'config_name' => $config_row['config_name']
                        ]);
                    } else {
                        echo json_encode($result);
                    }
                } else {
                    echo json_encode(['success' => false, 'error' => 'Configuration not found']);
                }
            } catch (Exception $e) {
                echo json_encode(['success' => false, 'error' => $e->getMessage()]);
            }
        } else {
            echo json_encode(['success' => false, 'error' => 'Configuration ID is required']);
        }
        
    } elseif ($action === 'get_configurations') {
        $event_id = $_REQUEST['event_id'] ?? null;
        
        if ($event_id) {
            $result = getSavedConfigurations($event_id);
            echo json_encode($result);
        } else {
            echo json_encode(['success' => false, 'error' => 'Event ID is required']);
        }
        
    } elseif ($action === 'get_config') {
        $config_id = $_REQUEST['config_id'] ?? null;
        
        if ($config_id) {
            $result = getConfiguration($config_id);
            echo json_encode($result);
        } else {
            echo json_encode(['success' => false, 'error' => 'Configuration ID is required']);
        }
        
    } elseif ($action === 'update_config') {
        $config_id = $_REQUEST['config_id'] ?? null;
        
        if ($config_id) {
            $config_data = [
                'event_id' => $_REQUEST['event_id'] ?? null,
                'config_name' => $_REQUEST['config_name'] ?? 'Updated Configuration',
                'selected_heats' => $_REQUEST['selected_heats'] ?? '[]',
                'categories' => $_REQUEST['categories'] ?? '[]',
                'gender' => $_REQUEST['gender'] ?? '[]',
                'year_from' => $_REQUEST['year_from'] ?? '',
                'year_to' => $_REQUEST['year_to'] ?? '',
                'scoring_method' => $_REQUEST['scoring_method'] ?? 'best_single',
                'count_best_runs' => $_REQUEST['count_best_runs'] ?? '',
                'count_from_heats' => $_REQUEST['count_from_heats'] ?? '',
                'display_columns' => $_REQUEST['display_columns'] ?? '[]',
                'sort_by' => $_REQUEST['sort_by'] ?? 'final_score',
                'sort_order' => $_REQUEST['sort_order'] ?? 'DESC'
            ];
            
            $result = updateConfiguration($config_id, $config_data);
            echo json_encode($result);
        } else {
            echo json_encode(['success' => false, 'error' => 'Configuration ID is required']);
        }
        
    } elseif ($action === 'delete_config') {
        $config_id = $_REQUEST['config_id'] ?? null;
        
        if ($config_id) {
            $result = deleteConfiguration($config_id);
            echo json_encode($result);
        } else {
            echo json_encode(['success' => false, 'error' => 'Configuration ID is required']);
        }
        
    } elseif ($action === 'duplicate_config') {
        $config_id = $_REQUEST['config_id'] ?? null;
        $new_name = $_REQUEST['new_name'] ?? null;
        
        if ($config_id && $new_name) {
            $result = duplicateConfiguration($config_id, $new_name);
            echo json_encode($result);
        } else {
            echo json_encode(['success' => false, 'error' => 'Configuration ID and new name are required']);
        }
        
    } elseif ($action === 'preview_config') {
        $config_id = $_REQUEST['config_id'] ?? null;
        
        if ($config_id) {
            $config_result = getConfiguration($config_id);
            if ($config_result['success']) {
                $preview = previewConfiguration($config_result['configuration']['config_data']);
                
                if (isset($_REQUEST['format']) && $_REQUEST['format'] === 'html') {
                    $html = generateConfigurationPreviewHTML($preview['preview']);
                    echo json_encode([
                        'success' => true,
                        'html' => $html,
                        'preview' => $preview['preview']
                    ]);
                } else {
                    echo json_encode($preview);
                }
            } else {
                echo json_encode($config_result);
            }
        } else {
            $config = [
                'event_id' => $_REQUEST['event_id'] ?? null,
                'config_name' => $_REQUEST['config_name'] ?? 'Preview Configuration',
                'selected_heats' => $_REQUEST['selected_heats'] ?? '[]',
                'categories' => $_REQUEST['categories'] ?? '[]',
                'gender' => $_REQUEST['gender'] ?? '[]',
                'year_from' => $_REQUEST['year_from'] ?? '',
                'year_to' => $_REQUEST['year_to'] ?? '',
                'scoring_method' => $_REQUEST['scoring_method'] ?? 'best_single',
                'count_best_runs' => $_REQUEST['count_best_runs'] ?? '',
                'count_from_heats' => $_REQUEST['count_from_heats'] ?? '',
                'display_columns' => $_REQUEST['display_columns'] ?? '[]',
                'sort_by' => $_REQUEST['sort_by'] ?? 'final_score',
                'sort_order' => $_REQUEST['sort_order'] ?? 'DESC'
            ];
            
            $preview = previewConfiguration($config);
            
            if (isset($_REQUEST['format']) && $_REQUEST['format'] === 'html') {
                $html = generateConfigurationPreviewHTML($preview['preview']);
                echo json_encode([
                    'success' => true,
                    'html' => $html,
                    'preview' => $preview['preview']
                ]);
            } else {
                echo json_encode($preview);
            }
        }
        
    } else {
        echo json_encode(['success' => false, 'error' => 'Invalid action']);
    }
}
?>