<?php
/**
 * Start List API
 * 
 * Generates official start lists for events and heats
 * 
 * Example Usage:
 * - Single heat: /api/start_list_api.php?event_id=3&heat_number=1
 * - All heats: /api/start_list_api.php?event_id=3
 * - Specific format: /api/start_list_api.php?event_id=3&heat_number=1&format=json
 * 
 * 
 * Usage Examples**/
/*The API endpoint supports various use cases:

JSON Response (Default):
GET /api/start_list_api.php?event_id=3&heat_number=1
HTML Table:
GET /api/start_list_api.php?event_id=3&heat_number=1&format=html
CSV Download:
GET /api/start_list_api.php?event_id=3&heat_number=1&format=csv
All Heats:
GET /api/start_list_api.php?event_id=3
With Pagination:
GET /api/start_list_api.php?event_id=3&page=2&limit=50
Features
 * 
 */
   // Use Dompdf for PDF generation
    require_once '../includes/dompdf/autoload.inc.php';
    use Dompdf\Dompdf;
    use Dompdf\Options;
header('Content-Type: application/json; charset=utf-8');
include '../includes/db.php';

// Configuration
$config = [
    'debug_mode' => false,
    'default_format' => 'json', // json, html, csv
    'items_per_page' => 100,
    'table_classes' => [
        'table' => 'table table-striped table-hover',
        'header' => 'table-dark',
        'row_even' => 'table-light',
        'row_odd' => ''
    ]
];

// Get and validate parameters
$event_id = (int)($_GET['event_id'] ?? 0);
$heat_number = isset($_GET['heat_number']) ? (int)$_GET['heat_number'] : null;
$format = $_GET['format'] ?? $config['default_format'];
$config_name = $_GET['config_name'] ?? null;
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = min(500, max(10, (int)($_GET['limit'] ?? $config['items_per_page'])));

// Validate event exists
if (!$event_id) {
    echo json_encode([
        'success' => false,
        'message' => 'Event ID is required',
        'error_code' => 'MISSING_EVENT_ID'
    ]);
    exit;
}

// Check if event exists
$event_stmt = $pdo->prepare("SELECT id, name FROM events WHERE id = ?");
$event_stmt->execute([$event_id]);
$event = $event_stmt->fetch(PDO::FETCH_ASSOC);

if (!$event) {
    echo json_encode([
        'success' => false,
        'message' => 'Event not found',
        'error_code' => 'EVENT_NOT_FOUND'
    ]);
    exit;
}
function generatePDF($data, $event, $heat_number = null) {
 

    // Get styling (header/footer) from results_styling.php
    $styling_mode = $_GET['styling'] ?? 'full';
    $event_id = $event['id'] ?? ($_GET['event_id'] ?? null);
    $config_id = $_GET['config_id'] ?? null;

    $api_endpoint = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/v2/admin/results_styling.php';
    $post_fields = http_build_query([
        'action' => 'get_styled_header_footer',
        'event_id' => $event_id,
        'config_id' => $config_id
    ]);

    $ch = curl_init($api_endpoint);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $styling_json = curl_exec($ch);
    curl_close($ch);

    $styling_data = json_decode($styling_json, true);

    // Generate the HTML table for the PDF
    $html_table = generateHTMLTable($data, $event, $heat_number);

    // Build the full HTML for PDF
    $html = '<html>
        <head>
            <meta charset="utf-8">
            
        </head>
        <body>
            ' . ($styling_data['header_html'] ?? '') . '
            ' . $html_table . '
            ' . ($styling_data['footer_html'] ?? '') . '
        </body>
    </html>';

    // Setup Dompdf
    $options = new Options();
    
    $options->set('isHtml5ParserEnabled', true);
    $options->set('isRemoteEnabled', true);    
    $dompdf = new Dompdf($options);
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
        // Add page numbers
    $canvas = $dompdf->getCanvas();
    $font = $dompdf->getFontMetrics()->get_font("HelveticaCustom", "normal");
    $canvas->page_text(530, 822, "Page {PAGE_NUM} of {PAGE_COUNT}", $font, 6, [0,0,0]);


    // Serve PDF
    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename="start_list_event_' . $event_id . ($heat_number ? '_heat_' . $heat_number : '') . '.pdf"');
    echo $dompdf->output();
    exit;
}
// Function to generate start list data
function generateStartListData($pdo, $event_id, $heat_number = null, $page = 1, $limit = 100) {
    $offset = ($page - 1) * $limit;
    
    // Base query
    $query = "
        SELECT 
            ep.id,
            ep.heat_number,
            ep.bib_number as bib,
            ep.category,
            ep.sort_order,
            p.id as participant_id,
            p.first_name,
            p.last_name,
            p.club,
            p.gender,
            p.date_of_birth,
            ehs.heat_name,
            ehs.categories as heat_categories,
            ehs.runs_scoring_method
        FROM event_participants ep
        JOIN participants p ON ep.participant_id = p.id
        LEFT JOIN event_heat_settings ehs ON ep.event_id = ehs.event_id AND ep.heat_number = ehs.heat_number
        WHERE ep.event_id = ?
    ";
    
    $params = [$event_id];
    
    // Add heat filter if specified
    if ($heat_number !== null) {
        $query .= " AND ep.heat_number = ?";
        $params[] = $heat_number;
    }
    
    // Add gender filter if specified
    if (isset($_GET['gender']) && $_GET['gender'] !== '' && $_GET['gender'] !== 'all') {
        $query .= " AND p.gender = ?";
        $params[] = $_GET['gender'];
    }
    
    // Order by heat number and sort order
    $query .= " ORDER BY ep.heat_number ASC, ep.sort_order ASC, ep.bib_number ASC";
    
    // Add pagination - use direct concatenation for LIMIT/OFFSET to ensure integers
    $query .= " LIMIT " . (int)$limit . " OFFSET " . (int)$offset;
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $participants = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get total count for pagination
    $count_query = "
        SELECT COUNT(*) 
        FROM event_participants ep 
        WHERE ep.event_id = ?
    ";
    $count_params = [$event_id];
    
    if ($heat_number !== null) {
        $count_query .= " AND ep.heat_number = ?";
        $count_params[] = $heat_number;
    }
    
    $count_stmt = $pdo->prepare($count_query);
    $count_stmt->execute($count_params);
    $total_count = $count_stmt->fetchColumn();
    
    // Group participants by heat
    $heats = [];
    $heat_stats = [];
    
    foreach ($participants as $participant) {
        $heat_num = $participant['heat_number'];
        
        if (!isset($heats[$heat_num])) {
            $heats[$heat_num] = [
                'heat_number' => $heat_num,
                'heat_name' => $participant['heat_name'],
                'heat_categories' => $participant['heat_categories'],
                'scoring_method' => $participant['runs_scoring_method'],
                'participants' => []
            ];
            $heat_stats[$heat_num] = [
                'total_participants' => 0,
                'categories' => [],
                'clubs' => [],
                'genders' => ['M' => 0, 'F' => 0]
            ];
        }
        
        // Add participant with calculated age
        $age = null;
        if ($participant['date_of_birth']) {
            $birth_date = new DateTime($participant['date_of_birth']);
            $today = new DateTime();
            $age = $birth_date->diff($today)->y;
        }
        
        $participant['age'] = $age;
        $participant['birth_year'] = $participant['date_of_birth'] ? date('Y', strtotime($participant['date_of_birth'])) : null;
        $participant['full_name'] = trim($participant['last_name'] . ' ' . $participant['first_name']);
        
        $heats[$heat_num]['participants'][] = $participant;
        
        // Update stats
        $heat_stats[$heat_num]['total_participants']++;
        if ($participant['category']) {
            $heat_stats[$heat_num]['categories'][$participant['category']] = 
                ($heat_stats[$heat_num]['categories'][$participant['category']] ?? 0) + 1;
        }
        if ($participant['club']) {
            $heat_stats[$heat_num]['clubs'][$participant['club']] = 
                ($heat_stats[$heat_num]['clubs'][$participant['club']] ?? 0) + 1;
        }
        if ($participant['gender']) {
            $heat_stats[$heat_num]['genders'][$participant['gender']]++;
        }
    }
    
    // Calculate pagination info
    $total_pages = ceil($total_count / $limit);
    $has_next = $page < $total_pages;
    $has_prev = $page > 1;
    
    return [
        'heats' => $heats,
        'heat_stats' => $heat_stats,
        'pagination' => [
            'current_page' => $page,
            'total_pages' => $total_pages,
            'total_count' => $total_count,
            'limit' => $limit,
            'offset' => $offset,
            'has_next' => $has_next,
            'has_prev' => $has_prev
        ]
    ];
}

// Function to generate HTML table
function generateHTMLTable($data, $event, $heat_number = null) {
    global $config;
    
    $html = '';
    
    // Generate tables for each heat
    foreach ($data['heats'] as $heat) {
        $heat_num = $heat['heat_number'];
        $participants = $heat['participants'];
        
        if (empty($participants)) continue;
        
        $html .= '<div class="heat-section mb-4">';
        $html .= '<div class="heat-header mb-3">';
        $html .= '<h4 class="heat-title">Heat ' . htmlspecialchars($heat_num);
        if ($heat['heat_name']) {
            $html .= ' - ' . htmlspecialchars($heat['heat_name'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
        }
        $html .= '</h4>';
        $html .= '<div class="heat-info">';
        $html .= '<span class="badge bg-primary me-2">' . count($participants) . ' Participants</span>';
        if ($heat['scoring_method']) {
            $html .= '<span class="badge bg-info me-2">Scoring: ' . htmlspecialchars($heat['scoring_method']) . '</span>';
        }
        $html .= '</div>';
        $html .= '</div>';
        
        // Start table
        $html .= '<table class="' . $config['table_classes']['table'] . ' data-table">';
        $html .= '<thead class="' . $config['table_classes']['header'] . '">';
        $html .= '<tr>';
        $html .= '<th>#</th>';
        $html .= '<th>BIB</th>';
        $html .= '<th>Name</th>';
        $html .= '<th>Club</th>';
        $html .= '<th>Category</th>';
        $html .= '<th>Gender</th>';
        $html .= '<th>Birth Year</th>';
        $html .= '<th>Age</th>';
        $html .= '</tr>';
        $html .= '</thead>';
        $html .= '<tbody>';
        
        $position = 1;
        foreach ($participants as $p) {
            $row_class = ($position % 2 === 0) ? $config['table_classes']['row_even'] : $config['table_classes']['row_odd'];
            
            $html .= '<tr class="' . $row_class . '">';
            $html .= '<td>' . $position . '</td>';
            $html .= '<td><span class="badge bg-secondary">' . htmlspecialchars($p['bib'] ?? '-') . '</span></td>';
            $html .= '<td><strong>' . htmlspecialchars($p['full_name']) . '</strong></td>';
            $html .= '<td><small><span class="badge bg-secondary">' . htmlspecialchars($p['club'] ?? '-') . '</span></small></td>';
            $html .= '<td><small><span class="badge bg-info">' . htmlspecialchars($p['category'] ?? '-') . '</span></small></td>';
            $html .= '<td>';
            if ($p['gender']) {
                $gender_class = $p['gender'] === 'M' ? 'text-primary' : 'text-danger';
                $gender_icon = $p['gender'] === 'M' ? 'fa-male' : 'fa-female';
                $html .= '<i class="fas ' . $gender_icon . ' ' . $gender_class . ' me-1"></i>';
                $html .= htmlspecialchars($p['gender']);
            } else {
                $html .= '-';
            }
            $html .= '</td>';
            $html .= '<td>' . htmlspecialchars($p['birth_year'] ?? '-') . '</td>';
            $html .= '<td>' . htmlspecialchars($p['age'] ?? '-') . '</td>';
            $html .= '</tr>';
            
            $position++;
        }
        
        $html .= '</tbody>';
        $html .= '</table>';
        $html .= '</div>'; // end heat-section
    }
    
    return $html;
}

// Function to generate CSV data
function generateCSV($data, $event) {
    $csv_data = [];
    
    // Add header
    $csv_data[] = [
        'Heat',
        'Position',
        'BIB',
        'First Name',
        'Last Name',
        'Full Name',
        'Club',
        'Category',
        'Gender',
        'Birth Year',
        'Age',
        'Sort Order'
    ];
    
    foreach ($data['heats'] as $heat) {
        $position = 1;
        foreach ($heat['participants'] as $p) {
            $csv_data[] = [
                $heat['heat_number'],
                $position,
                $p['bib'] ?? '',
                $p['first_name'],
                $p['last_name'],
                $p['full_name'],
                $p['club'] ?? '',
                $p['category'] ?? '',
                $p['gender'] ?? '',
                $p['birth_year'] ?? '',
                $p['age'] ?? '',
                $p['sort_order'] ?? ''
            ];
            $position++;
        }
    }
    
    return $csv_data;
}

try {
    // Generate start list data
    $data = generateStartListData($pdo, $event_id, $heat_number, $page, $limit);
    
    // Determine response format
    switch ($format) {
         case 'html':
            header('Content-Type: text/html; charset=utf-8');
            

                    
                        $styling_mode = $_GET['styling'] ?? 'full';
                    
                        //$event_id = $selected_event ?? ($_GET['event_id'] ?? null);
                        $config_id = $_GET['config_id'] ?? null;

                        // Prepare API call to results_styling.php
                        $styling_api_url = dirname(__FILE__) . '/../admin/results_styling.php';
                        $api_endpoint = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/v2/admin/results_styling.php';
                        $post_fields = http_build_query([
                            'action' => 'get_styled_header_footer',
                            'event_id' => $event_id,
                            'config_id' => null,
                        ]);

                        // Use cURL to call the API
                        $ch = curl_init($api_endpoint);
                        curl_setopt($ch, CURLOPT_POST, true);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        $styling_json = curl_exec($ch);
                        curl_close($ch);
                        
                        $styling_data = json_decode($styling_json, true);
                        //print_r($config_name);
                        if ($format === 'html') {
                            header('Content-Type: text/html');
                            //echo "$config_name";
                            //echo $styling_data['header_html'] ?? '';
                            echo generateHTMLTable($data, $event, $heat_number);
                            echo $styling_data['footer_html'] ?? ''; 
                            exit;
                        }
                    
            
            break;
        case 'pdf':
            //header('Content-Type: application/pdf');
            //header('Content-Disposition: attachment; filename="start_list_event_' . $event_id . 
                 //  ($heat_number ? '_heat_' . $heat_number : '') . '_' . date('Y-m-d') . '.pdf"');
            echo generatePDF($data, $event, $heat_number, );
            break;
            
        case 'csv':
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename="start_list_event_' . $event_id . 
                   ($heat_number ? '_heat_' . $heat_number : '') . '_' . date('Y-m-d') . '.csv"');
            
            $csv_data = generateCSV($data, $event);
            $output = fopen('php://output', 'w');
            foreach ($csv_data as $row) {
                fputcsv($output, $row);
            }
            fclose($output);
            break;
            
        case 'json':
        default:
            header('Content-Type: application/json');
            
            // Build response
            $response = [
                'success' => true,
                'data' => $data,
                'event' => $event,
                'filters' => [
                    'event_id' => $event_id,
                    'heat_number' => $heat_number
                ],
                'meta' => [
                    'total_heats' => count($data['heats']),
                    'total_participants' => $data['pagination']['total_count'],
                    'generated_at' => date('Y-m-d H:i:s'),
                    'format' => $format
                ]
            ];
            
            // Add debug information if enabled
            if ($config['debug_mode']) {
                $response['debug'] = [
                    'query_params' => $_GET,
                    'pagination_details' => $data['pagination'],
                    'heat_stats' => $data['heat_stats'] ?? []
                ];
            }
            
            echo json_encode($response, JSON_PRETTY_PRINT);
            break;
    }

} catch (Exception $e) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Error generating start list: ' . $e->getMessage(),
        'error_code' => 'GENERATION_ERROR'
    ]);
}
?>