<?php
// Public Results Page - Uses same functions as admin/event_start_list.php
include 'includes/db.php';

$selected_event = $_GET['event_id'] ?? null;
$selected_heat = $_GET['heat_number'] ?? null;
$selected_heats = [];
if ($selected_heat) {
    // Support both single heat number and comma-separated multiple heats
    $selected_heats = is_array($selected_heat) ? $selected_heat : explode(',', $selected_heat);
    $selected_heats = array_filter($selected_heats); // Remove empty values
}
$view_type = $_GET['view_type'] ?? 'summary_table';

// Fetch active/public events only
$events = $pdo->query("SELECT id, name FROM events WHERE status = 'active' ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
$selected_event_name = null;
$is_bracket_event = false;
foreach ($events as $event) {
    if ($selected_event == $event['id']) {
        $selected_event_name = $event['name'];
        break;
    }
}

if ($selected_event) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM event_heat_settings WHERE event_id = ? AND (flow_type = 'elimination' OR flow_source_heat IS NOT NULL)");
    $stmt->execute([$selected_event]);
    $is_bracket_event = (int)$stmt->fetchColumn() > 0;
}

$allowed_view_types = ['summary_table', 'start_list'];
if ($is_bracket_event) {
    $allowed_view_types[] = 'brackets';
}
if (!in_array($view_type, $allowed_view_types, true)) {
    $view_type = 'summary_table';
}

// Fetch heats for selected event
$heats = [];
$categories = [];
if ($selected_event) {
    $stmt = $pdo->prepare("SELECT heat_number, heat_name FROM event_heat_settings WHERE event_id = ? ORDER BY heat_number ASC");
    $stmt->execute([$selected_event]);
    $heats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Fetch categories for the selected event
    if ($selected_event) {
        // Get participant-assigned categories for backward compatibility
        $stmt = $pdo->prepare("SELECT DISTINCT category FROM event_participants WHERE event_id = ? AND category IS NOT NULL ORDER BY category");
        $stmt->execute([$selected_event]);
        $participant_categories = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
        if ($selected_heat) {
            // Get heat-specific categories from event_heat_settings.categories column
            $stmt = $pdo->prepare("
                SELECT categories 
                FROM event_heat_settings 
                WHERE event_id = ? AND heat_number = ? 
                LIMIT 1
            ");
            $stmt->execute([$selected_event, $selected_heat]);
            $heat_categories_json = $stmt->fetchColumn();
            
            if ($heat_categories_json) {
                // Parse the JSON array of category IDs
                $heat_category_ids = json_decode($heat_categories_json, true) ?: [];
                
                if (!empty($heat_category_ids)) {
                    // Create placeholders for the IN clause
                    $placeholders = implode(',', array_fill(0, count($heat_category_ids), '?'));
                    
                    // Get category details for the heat-specific categories
                    $stmt = $pdo->prepare("
                        SELECT id, category_name, is_main_category, use_for_ranking 
                        FROM event_categories 
                        WHERE event_id = ? AND id IN ($placeholders)
                        ORDER BY is_main_category DESC, category_name
                    ");
                    
                    // Combine the parameters: first the event_id, then all category IDs
                    $params = array_merge([$selected_event], $heat_category_ids);
                    $stmt->execute($params);
                    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
                }
            }
            
            // If no categories found through heat settings, fall back to participants in the heat
            if (empty($categories)) {
                // Fallback query to find categories of participants in this heat
                $stmt = $pdo->prepare("
                    SELECT DISTINCT ec.id, ec.category_name, ec.is_main_category, ec.use_for_ranking
                    FROM event_categories ec
                    JOIN event_participants ep ON (
                        ep.event_id = ec.event_id 
                        AND (
                            ep.category_id = ec.id
                            OR (ep.matching_category_ids IS NOT NULL AND ep.matching_category_ids LIKE CONCAT('%\"',ec.id,'\"%'))
                        )
                    )
                    WHERE ec.event_id = ? AND ep.heat_number = ?
                    ORDER BY ec.is_main_category DESC, ec.category_name
                ");
                $stmt->execute([$selected_event, $selected_heat]);
                $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
            }
        } else {
            // If no heat selected, get all main + ranking categories
            $stmt = $pdo->prepare("
                SELECT id, category_name, is_main_category, use_for_ranking 
                FROM event_categories 
                WHERE event_id = ? AND (is_main_category = 1 OR use_for_ranking = 1)
                ORDER BY is_main_category DESC, category_name
            ");
            $stmt->execute([$selected_event]);
            $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        
        // Add legacy categories for backward compatibility
        foreach ($participant_categories as $cat) {
            if (!in_array($cat, array_column($categories, 'category_name'))) {
                $categories[] = [
                    'id' => null, 
                    'category_name' => $cat, 
                    'is_main_category' => 0, 
                    'use_for_ranking' => 0
                ];
            }
        }
    }
}

// Fetch saved configurations for selected event (only public ones)
$saved_configurations = [];
if ($selected_event && $view_type !== 'brackets') {
    $stmt = $pdo->prepare("
        SELECT id, name, view_type, heat_number, category, status, display_order, created_at
        FROM result_configurations 
        WHERE event_id = ? AND view_type = ? AND status = 'active'
        ORDER BY display_order ASC, name ASC
    ");
    $stmt->execute([$selected_event, $view_type]);
    $saved_configurations = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

$title_suffix = 'Summary Tables';
if ($view_type === 'start_list') {
    $title_suffix = 'Start Lists';
} elseif ($view_type === 'brackets') {
    $title_suffix = 'Elimination Brackets';
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Results - <?= htmlspecialchars($title_suffix) ?></title>
    <?php include_once 'includes/stylesheets.php'; ?>
    <style>
       
    </style>
</head>
<body>
    <header class="bg-primary text-white py-3 mb-4 shadow-sm">
        <div class="container d-flex flex-column flex-md-row align-items-md-center justify-content-between">
            <a class="navbar-brand navbar-brand-logo" href="/v2/dashboard.php">
            <img src="./assets/img/SVG/logo-ss-_2.svg" alt="Logo" class="me-2" style="
    width: 100%;
    height: 50px;
    filter: brightness(2.5);
">
        </a><h1 class="h3 mb-2 mb-md-0">Live Results</h1>
            <?php if ($selected_event_name): ?>
                <span class="badge bg-light text-primary fw-semibold px-3 py-2">Event: <?= htmlspecialchars($selected_event_name) ?></span>
            <?php else: ?>
                <span class="text-white-50">Select an event to view published results</span>
            <?php endif; ?>
        </div>
    </header>

    <div class="container-fluid p-4">
        <div class="row">
            <!-- Left Sidebar: Filters -->
            <div class="col-md-3">
                <div class="sidebar-filters">
                    <!-- View Type Tabs -->
                    <div class="card shadow-sm mb-3">
                        <div class="card-body p-3">
                            <h5 class="card-title mb-3"><i class="fas fa-eye me-2"></i>View Type</h5>
                            <div class="btn-group w-100" role="group">
                                <a href="?view_type=start_list<?= $selected_event ? '&event_id='.$selected_event : '' ?>" 
                                   class="btn btn-<?= $view_type === 'start_list' ? 'primary' : 'outline-primary' ?>">
                                    <i class="fas fa-list-ol me-1"></i>Start Lists
                                </a>
                                <a href="?view_type=summary_table<?= $selected_event ? '&event_id='.$selected_event : '' ?>" 
                                   class="btn btn-<?= $view_type === 'summary_table' ? 'primary' : 'outline-primary' ?>">
                                    <i class="fas fa-table me-1"></i>Summary
                                </a>
                                <?php if ($is_bracket_event): ?>
                                <a href="?view_type=brackets<?= $selected_event ? '&event_id='.$selected_event : '' ?>"
                                   class="btn btn-<?= $view_type === 'brackets' ? 'primary' : 'outline-primary' ?>">
                                    <i class="fas fa-project-diagram me-1"></i>Brackets
                                </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Event Selection -->
                    <div class="card shadow-sm mb-3">
                        <div class="card-body p-3">
                            <h6 class="mb-2 fw-bold text-primary"><i class="fas fa-calendar-alt me-2"></i>Event</h6>
                            <select class="form-select" id="eventSelect" onchange="selectEvent(this.value)">
                                <option value="">Select Event...</option>
                                <?php foreach ($events as $event): ?>
                                    <option value="<?= $event['id'] ?>" <?= $selected_event == $event['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($event['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <?php if ($selected_event && !empty($saved_configurations)): ?>
                    <!-- Saved Configurations -->
                    <div class="card shadow-sm">
                        <div class="card-body p-3">
                            <h6 class="mb-2 fw-bold text-success"><i class="fas fa-bookmark me-2"></i>Saved Reports</h6>
                            <div class="list-group list-group-flush">
                                <?php foreach ($saved_configurations as $config): ?>
                                    <button type="button"
                                            class="list-group-item list-group-item-action config-button d-flex justify-content-between align-items-center"
                                            data-config-id="<?= $config['id'] ?>"
                                            onclick="loadConfiguration(<?= $config['id'] ?>)"
                                            onauxclick="if(event.button === 1){event.preventDefault();openConfigInNewTab(<?= $config['id'] ?>);}" 
                                            title="Click to load, middle-click to open in new tab">
                                        <span class="me-2 text-start"><i class="fas fa-file-alt me-2"></i><?= htmlspecialchars($config['name']) ?></span>
                                        <span class="badge bg-light text-dark">#<?= $config['id'] ?></span>
                                    </button>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Main Content Area -->
            <div class="col-md-9">
                <div class="card shadow-none border-0">
                    <div class="card-body p-3">
                        <div id="contentDisplay">
                            <?php if (!$selected_event): ?>
                                <div class="alert alert-info mb-0">
                                    <i class="fas fa-info-circle me-2"></i>
                                    Please select an event from the sidebar to view results.
                                </div>
                            <?php else: ?>
                                <div class="text-center py-5">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                    <p class="mt-2 text-muted">Loading results...</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer class="border-top p-3 mt-5 d-flex flex-row align-items-center" style="
    background-color: #B0F761;
">      <div></div>
        <div class="container text-center text-primary fw-medium small">
            <span>&copy; <?= date('Y') ?> StyleScore | Live scoring powered by the official results platform</span>
        </div>
        <div> <img src="assets/img/logo-dark.png" style="max-height: 50px; width: auto;" class="img-fluid logo-footer" alt="StyleScore live sports scoring and event management system logo featuring a black stopwatch with speed lines indicating motion and timing precision for athletic competitions"></div>
    </footer>

    <script>
        const SELECTED_EVENT = <?= $selected_event ? $selected_event : 'null' ?>;
    const VIEW_TYPE = '<?= $view_type ?>';
    const SAVED_CONFIGS = <?= json_encode($saved_configurations) ?>;
    const IS_BRACKET_EVENT = <?= $is_bracket_event ? 'true' : 'false' ?>;
    const SELECTED_EVENT_NAME = <?= json_encode($selected_event_name) ?>;
        let activeConfigId = null;

        document.addEventListener('DOMContentLoaded', () => {
            if (!SELECTED_EVENT) {
                return;
            }

            if (VIEW_TYPE === 'brackets') {
                if (!IS_BRACKET_EVENT) {
                    showMessage('info', '<i class="fas fa-info-circle me-2"></i>This event does not have bracket rounds configured yet.');
                } else {
                    loadBracketView();
                }
                return;
            }

            if (!SAVED_CONFIGS.length) {
                showMessage('warning', '<i class="fas fa-exclamation-triangle me-2"></i>No saved configurations found for this event.');
                return;
            }

            loadConfiguration(SAVED_CONFIGS[0].id);
        });

        function selectEvent(eventId) {
            const url = new URL(window.location);
            if (eventId) {
                url.searchParams.set('event_id', eventId);
            } else {
                url.searchParams.delete('event_id');
            }
            url.searchParams.set('view_type', VIEW_TYPE);
            window.location.href = url.toString();
        }

        function showLoading(message = 'Loading results...') {
            const contentDisplay = document.getElementById('contentDisplay');
            if (!contentDisplay) return;
            contentDisplay.innerHTML = `
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">${message}</span>
                    </div>
                    <p class="mt-2 text-muted">${message}</p>
                </div>
            `;
        }

        function showMessage(type, message) {
            const contentDisplay = document.getElementById('contentDisplay');
            if (!contentDisplay) return;
            contentDisplay.innerHTML = `<div class="alert alert-${type} mb-0">${message}</div>`;
        }

        function setActiveConfigButton(configId) {
            document.querySelectorAll('.config-button').forEach(button => {
                const id = parseInt(button.dataset.configId, 10);
                if (id === configId) {
                    button.classList.add('active');
                } else {
                    button.classList.remove('active');
                }
            });
        }

        function loadConfiguration(rawId) {
            const configId = parseInt(rawId, 10);
            if (!configId) {
                return;
            }

            activeConfigId = configId;
            setActiveConfigButton(configId);
            showLoading('Loading configuration...');

            // Find the config to determine its view_type
            const config = SAVED_CONFIGS.find(c => parseInt(c.id, 10) === configId);
            if (!config) {
                showMessage('danger', '<i class="fas fa-exclamation-triangle me-2"></i>Configuration not found.');
                return;
            }

            // Determine which API to call based on view_type
            const apiEndpoint = config.view_type === 'start_list' 
                ? 'api/start_list_api.php' 
                : 'api/summary_table_api.php';

            fetch(`${apiEndpoint}?config_id=${configId}&format=html`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}`);
                    }
                    return response.text();
                })
                .then(html => {
                    const contentDisplay = document.getElementById('contentDisplay');
                    if (contentDisplay) {
                        contentDisplay.innerHTML = html;
                    }
                })
                .catch(error => {
                    showMessage('danger', `<i class="fas fa-exclamation-triangle me-2"></i>${error.message}`);
                });
        }

     

        function escapeHtml(value) {
            if (value === null || value === undefined) {
                return '';
            }
            return String(value)
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;');
        }

        function escapeAttribute(value) {
            return escapeHtml(value).replace(/`/g, '&#96;');
        }

        function formatScoreValue(value) {
            const numeric = parseFloat(value);
            if (Number.isFinite(numeric)) {
                return numeric.toFixed(2);
            }
            return '—';
        }

        async function loadBracketView() {
            if (!SELECTED_EVENT) {
                showMessage('warning', '<i class="fas fa-exclamation-triangle me-2"></i>No event selected.');
                return;
            }

            showLoading('Loading bracket view...');

            try {
                const response = await fetch(`api/heat_bracket_view_api.php?event_id=${SELECTED_EVENT}&compact=0`);
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }

                const data = await response.json();

                if (!data.success) {
                    showMessage('danger', `<i class="fas fa-exclamation-triangle me-2"></i>${data.error || 'Failed to load bracket'}`);
                    return;
                }

                const contentDisplay = document.getElementById('contentDisplay');
                if (!contentDisplay) return;

                // Build bracket view with header
                contentDisplay.innerHTML = `
                    <div class="bracket-view-wrapper">
                        
                        <div class="bracket-view-body">
                            ${data.html}
                        </div>
                    </div>
                `;

                // Draw connections if available
                if (data.connections && data.connections.length > 0) {
                    setTimeout(() => {
                        drawBracketConnections(data.connections);
                    }, 100);
                }
            } catch (error) {
                console.error('Error loading bracket view:', error);
                showMessage('danger', `<i class="fas fa-exclamation-triangle me-2"></i>Error loading bracket: ${error.message}`);
            }
        }

        function drawBracketConnections(connections) {
            const svg = document.querySelector('.bracket-connections');
            if (!svg) return;

            const container = svg.closest('.bracket-flow-container');
            if (!container) return;

            const containerRect = container.getBoundingClientRect();

            connections.forEach(conn => {
                const fromCard = document.querySelector(`[data-heat-id="${conn.from}"]`);
                const toCard = document.querySelector(`[data-heat-id="${conn.to}"]`);

                if (!fromCard || !toCard) return;

                const fromRect = fromCard.getBoundingClientRect();
                const toRect = toCard.getBoundingClientRect();

                const fromX = fromRect.right - containerRect.left;
                const fromY = fromRect.top + fromRect.height / 2 - containerRect.top;
                const toX = toRect.left - containerRect.left;
                const toY = toRect.top + toRect.height / 2 - containerRect.top;

                const midX = fromX + (toX - fromX) / 2;
                const pathData = `M ${fromX} ${fromY} L ${midX} ${fromY} L ${midX} ${toY} L ${toX} ${toY}`;

                const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
                path.setAttribute('d', pathData);
                path.setAttribute('class', 'connection-path');
                path.setAttribute('marker-end', 'url(#arrowhead)');

                svg.appendChild(path);
            });
        }

        async function renderSummaryConfig(config) {
            try {
                showLoading('Loading summary table...');
                // Build request with format=html from the start
                const request = buildSummaryRequest(config, { format: 'html' });
                
                // Fetch complete HTML from API (with wrappers, headers, footers)
                const response = await fetch(request.url + '&styling=partial');
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                
                const html = await response.text();
                const contentDisplay = document.getElementById('contentDisplay');
                if (contentDisplay) {
                    contentDisplay.innerHTML = html;
                }
            } catch (error) {
                showMessage('danger', `<i class="fas fa-exclamation-triangle me-2"></i>${error.message}`);
            }
        }

        async function renderStartListConfig(config) {
            try {
                showLoading('Loading start list...');
                const request = buildStartListRequest(config);
                
                // Fetch complete HTML from API (with wrappers, headers, footers)
                const url = request.url + '&styling=partial';
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                
                const html = await response.text();
                const contentDisplay = document.getElementById('contentDisplay');
                if (contentDisplay) {
                    contentDisplay.innerHTML = html;
                }
            } catch (error) {
                showMessage('danger', `<i class="fas fa-exclamation-triangle me-2"></i>${error.message}`);
            }
        }


    </script>

    <?php include_once 'includes/scripts.php'; ?>
</body>
</html>
