<?php
include '../includes/auth.php';
include '../includes/db.php';


    if (isset($_POST['action']) && $_POST['action'] === 'get_styled_header_footer') {
    try {header('Content-Type: application/json');
        $event_id = $_POST['event_id'] ?? null;
        $config_id = $_POST['config_id'] ?? null;
        $config_name = $_POST['config_name'] ?? null;
        $stmt = $pdo->prepare("SELECT name FROM result_configurations WHERE id = ?");
$stmt->execute([$config_id]);
$config = $stmt->fetch(PDO::FETCH_ASSOC);

  echo $config_id;
        $result = getStyledHeaderFooter($pdo, $event_id, $config_name);
        echo json_encode(['success' => true] + $result);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}
function pt_to_em($pt, $base_pt = 12) {
    return $pt / $base_pt;
}
// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax'])) {
    header('Content-Type: application/json');
    



    if (isset($_POST['action']) && $_POST['action'] === 'save_styling') {
        try {
            $event_id = $_POST['event_id'] ?? null;
            $config_id = $_POST['config_id'] ?? null; // Optional - for specific config styling
            
            $styling_data = [
                'header_content' => $_POST['header_content'] ?? '',
                'footer_content' => $_POST['footer_content'] ?? '',
                'logo_url' => $_POST['logo_url'] ?? '',
                'logo_position' => $_POST['logo_position'] ?? 'left',
                'logo_size' => $_POST['logo_size'] ?? 'medium',
                'font_family' => $_POST['font_family'] ?? 'Arial',
                'font_size' => $_POST['font_size'] ?? '12',
                'primary_color' => $_POST['primary_color'] ?? '#0d6efd',
                'secondary_color' => $_POST['secondary_color'] ?? '#6c757d',
                'table_style' => $_POST['table_style'] ?? 'striped',
                'page_margins' => $_POST['page_margins'] ?? 'normal',
                'show_event_info' => $_POST['show_event_info'] ?? '1',
                'show_generation_date' => $_POST['show_generation_date'] ?? '1',
                'custom_css' => $_POST['custom_css'] ?? '',
                'watermark_text' => $_POST['watermark_text'] ?? '',
                'watermark_opacity' => $_POST['watermark_opacity'] ?? '0.1'
            ];
            
            // Check if styling already exists
            if ($config_id) {
                // Config-specific styling
                $check_stmt = $pdo->prepare("SELECT id FROM result_styling WHERE config_id = ?");
                $check_stmt->execute([$config_id]);
            } else {
                // Event-wide styling
                $check_stmt = $pdo->prepare("SELECT id FROM result_styling WHERE event_id = ? AND config_id IS NULL");
                $check_stmt->execute([$event_id]);
            }
            
            if ($check_stmt->fetch()) {
    // Update existing
    if ($config_id) {
        $stmt = $pdo->prepare("UPDATE result_styling SET styling_data = ?, updated_at = NOW() WHERE config_id = ?");
        $stmt->execute([json_encode($styling_data), $config_id]);
    } else {
        $stmt = $pdo->prepare("UPDATE result_styling SET styling_data = ?, updated_at = NOW() WHERE event_id = ? AND config_id IS NULL");
        $stmt->execute([json_encode($styling_data), $event_id]);
    }
} else {
    // Insert new - handle NULL config_id properly
    if ($config_id) {
        $stmt = $pdo->prepare("INSERT INTO result_styling (event_id, config_id, styling_data, created_at) VALUES (?, ?, ?, NOW())");
        $stmt->execute([$event_id, $config_id, json_encode($styling_data)]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO result_styling (event_id, config_id, styling_data, created_at) VALUES (?, NULL, ?, NOW())");
        $stmt->execute([$event_id, json_encode($styling_data)]);
    }
}
            
            echo json_encode(['success' => true, 'message' => 'Styling saved successfully']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        exit;
    }
    
    if (isset($_POST['action']) && $_POST['action'] === 'load_styling') {
        try {
            $event_id = $_POST['event_id'] ?? null;
            $config_id = $_POST['config_id'] ?? null;
            
            if ($config_id) {
                // Load config-specific styling first, then fall back to event styling
                $stmt = $pdo->prepare("SELECT styling_data FROM result_styling WHERE config_id = ?");
                $stmt->execute([$config_id]);
                $styling = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if (!$styling && $event_id) {
                    // Fall back to event styling
                    $stmt = $pdo->prepare("SELECT styling_data FROM result_styling WHERE event_id = ? AND config_id IS NULL");
                    $stmt->execute([$event_id]);
                    $styling = $stmt->fetch(PDO::FETCH_ASSOC);
                }
            } else {
                // Load event styling
                $stmt = $pdo->prepare("SELECT styling_data FROM result_styling WHERE event_id = ? AND config_id IS NULL");
                $stmt->execute([$event_id]);
                $styling = $stmt->fetch(PDO::FETCH_ASSOC);
            }
            
            if ($styling) {
                echo json_encode(['success' => true, 'styling' => json_decode($styling['styling_data'], true)]);
            } else {
                echo json_encode(['success' => true, 'styling' => null]);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        exit;
    }
    
    if (isset($_POST['action']) && $_POST['action'] === 'upload_logo') {
        try {
            if (!isset($_FILES['logo']) || $_FILES['logo']['error'] !== UPLOAD_ERR_OK) {
                throw new Exception('No file uploaded or upload error');
            }
            
            $uploadDir = '../uploads/logos/';
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            $file = $_FILES['logo'];
            $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $allowedTypes = ['jpg', 'jpeg', 'png', 'gif', 'svg'];
            
            if (!in_array($extension, $allowedTypes)) {
                throw new Exception('Invalid file type. Allowed: JPG, PNG, GIF, SVG');
            }
            
            if ($file['size'] > 5 * 1024 * 1024) { // 5MB limit
                throw new Exception('File too large. Maximum size: 5MB');
            }
            
            $filename = 'logo_' . time() . '_' . uniqid() . '.' . $extension;
            $filepath = $uploadDir . $filename;
            
            if (move_uploaded_file($file['tmp_name'], $filepath)) {
                $url = '../uploads/logos/' . $filename;
                echo json_encode(['success' => true, 'url' => $url]);
            } else {
                throw new Exception('Failed to save uploaded file');
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        exit;
    }
    
    if (isset($_POST['action']) && $_POST['action'] === 'preview_styling') {
        try {
            $styling_data = [
                'header_content' => $_POST['header_content'] ?? '',
                'footer_content' => $_POST['footer_content'] ?? '',
                'logo_url' => $_POST['logo_url'] ?? '',
                'logo_position' => $_POST['logo_position'] ?? 'left',
                'logo_size' => $_POST['logo_size'] ?? 'medium',
                'font_family' => $_POST['font_family'] ?? 'Arial',
                'font_size' => $_POST['font_size'] ?? '12',
                'primary_color' => $_POST['primary_color'] ?? '#0d6efd',
                'secondary_color' => $_POST['secondary_color'] ?? '#6c757d',
                'table_style' => $_POST['table_style'] ?? 'striped',
                'page_margins' => $_POST['page_margins'] ?? 'normal',
                'show_event_info' => $_POST['show_event_info'] ?? '1',
                'show_generation_date' => $_POST['show_generation_date'] ?? '1',
                'custom_css' => $_POST['custom_css'] ?? '',
                'watermark_text' => $_POST['watermark_text'] ?? '',
                'watermark_opacity' => $_POST['watermark_opacity'] ?? '0.1'
            ];
            
            $preview_html = generateStyledPreview($styling_data);
            echo json_encode(['success' => true, 'html' => $preview_html]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        exit;
    }
}
        function getAbsoluteLogoUrl($logo_url) {
    if (!$logo_url) return '';
    // Remove leading '../' if present
    $logo_url = preg_replace('#^\.\./#', '', $logo_url);
    // Build absolute URL
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    return $protocol . '://' . $host . '/v2/' . ltrim($logo_url, '/');
}
function getStyledHeaderFooter($pdo, $event_id, $config_id = null, $cofnfig_name = null) {
    $styling = null;
    if ($config_id) {
        $stmt = $pdo->prepare("SELECT styling_data FROM result_styling WHERE config_id = 14");
        $stmt->execute([$config_id]);
        $styling = $stmt->fetchColumn();
        if (!$styling && $event_id) {
            $stmt = $pdo->prepare("SELECT styling_data FROM result_styling WHERE event_id = ?");
            $stmt->execute([$event_id]);
            $styling = $stmt->fetchColumn();
        }
    } elseif ($event_id) {
        $stmt = $pdo->prepare("SELECT styling_data FROM result_styling WHERE event_id = ?");
        $stmt->execute([$event_id]);
        $styling = $stmt->fetchColumn();
    }
    $styling = $styling ? json_decode($styling, true) : [];
    if (!isset($event_name) || !isset($event_date) || !isset($event_location)) {
    $stmt = $pdo->prepare("SELECT name, date, location FROM events WHERE id = ?");
    $stmt->execute([$event_id]);
    $event = $stmt->fetch(PDO::FETCH_ASSOC);
    $event_name = $event['name'] ?? '';
    $event_date = $event['date'] ?? '';
    $event_location = $event['location'] ?? '';
}
    // Prepare header and footer HTML
    $logo_sizes = [
        'small' => '50px',
        'medium' => '80px',
        'large' => '120px'
    ];
    $logo_size = $logo_sizes[$styling['logo_size'] ?? 'medium'] ?? '80px';
    $logo_url = $styling['logo_url'] ?? '';
    $logo_position = $styling['logo_position'] ?? 'left';
    $logo_absolute_url = getAbsoluteLogoUrl($styling['logo_url']);
    // Header HTML

    function table_style($style) {
    $styles = [
        'plain' => '
            table.data-table\ {
                border-collapse: collapse;
                width: 100%;
            }
            .data-table th, .data-table  td {

                vertical-align: middle;
                border: none;
            }
        ',
        'bordered' => '
            table.table_style {
                border-collapse: collapse;
                width: 100%;
                border: 1px solid #000;
            }
            .table_style th, .table_style td {
                border: 1px solid #000;
                
                vertical-align: middle;
            }
        ',
        'striped' => '
            table.data-table {
                border-collapse: collapse;
                width: 100%;
            }
            .data-table th, .data-table td {

                vertical-align: middle;
                
            }
            .data-table tr:nth-child(even) {
                background-color: #eae9e9ff;
            }
        '
    ];

    return $styles[$style] ?? $styles['plain'];
}

    ob_start();

    ?>

 <link href="http://localhost/v2/assets/css/bootstrap.min.css" rel="stylesheet">

 <style>
    @font-face {
    font-family: 'HelveticaCustom';
    src: url('<?=get_base_url()?>fonts/Helvetica.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: 'HelveticaCustom';
    src: url('<?=get_base_url()?>fonts/Helvetica-Oblique.ttf') format('truetype');
    font-weight: normal;
    font-style: italic;
}

@font-face {
    font-family: 'HelveticaCustom';
    src: url('<?=get_base_url()?>fonts/Helvetica-Bold.ttf') format('truetype');
    font-weight: bold;
    font-style: normal;
}

@font-face {
    font-family: 'HelveticaCustom';
    src: url('<?=get_base_url()?>fonts/Helvetica-BoldOblique.ttf') format('truetype');
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: 'HelveticaCustom';
    src: url('<?=get_base_url()?>/fonts/helvetica-light-587ebe5a59211.ttf') format('truetype');
    font-weight: 300; /* Light weight */
    font-style: normal;
}
    h1, h2, h3, h4, h5, h6 {
    all: unset; /* resets all inherited and default styles */
    display: block; /* keep them block-level */    
    font-weight: bold;
   
}
            pre {
                all: unset;
                    display: block;
    font-family: 'DejaVu Sans Mono' !important;
    unicode-bidi: isolate;
    white-space: pre;
    
            }
  :root{
    /* Tune these to your design */
    --header-h: 30mm;
    --footer-h: 15mm;
    --page-side: 10mm;
  }
body {
                margin-top: var(--header-h);
                margin-left: var(--page-side);
                margin-right: var(--page-side);
                margin-bottom: var(--footer-h);
                font-size: <?= pt_to_em(htmlspecialchars($styling['font_size'])) ?>em;

}


.logo {max-width: <?=$logo_size?>; max-height: var(--header-h); max-width: 100%;}
  /* PRINT RULES */
  @page {
    size: A4;
    /* These margins RESERVE SPACE for header & footer on every page */
    margin: 0cm 0cm;
   
  }

    .content {
      /* No extra padding needed in print; @page margins handle spacing */
      padding: 0;
      
    }

    .page-numbers::after {
      content: "Page " counter(page) " of " counter(pages);
    }
  
  table {
    width: 100%;   
  }

.table th {
    background-color: #343a40 !important;
    color: white !important;
    border-color: #454d55 !important;
    white-space: nowrap;
    position: sticky;
    top: 0;
    z-index: 10;
    
}
 td.col-best {
    background-color: <?= htmlspecialchars($styling['primary_color']) ?> !important;
}
.table th {
    font-size: .8em;
    background-color: <?= htmlspecialchars($styling['primary_color']) ?> !important;}
table, tr, td, th {
    border-collapse: collapse; /* optional if you want tight borders */
    vertical-align: middle;
}
  .col-best {
    text-align: center;
}

            header {
                width: 100%;
                position: fixed;
                top: 0cm;
                height: var(--header-h);
                
            }


            footer {
                position: fixed; 
                bottom: 0cm; 
                left: 0cm;
                height: var(--footer-h);
                padding-left:var(--page-side); 
                padding-right:var(--page-side); 
                right: 0cm;
                padding-bottom: 0.3cm;
                font-size: 0.8em;
               
            }
            body, h1, h2, h3, h4, h5, h6, p{
    font-family: "<?= htmlspecialchars($styling['font_family']) ?>" !important;
}
 td.col-figures {
    font-size: .6em !important;
    margin: 0;
    padding: 0;
    line-height: 1em;
}
.col-figures {width: 10% !important;}
.td{ padding: 5px 0;}
<?php echo table_style(htmlspecialchars($styling['table_style'])) ?>
</style>


    <?php if ($styling['watermark_text']): ?>      
            <style>.rotingtxt {
                -webkit-transform: rotate(331deg);
                -moz-transform: rotate(331deg);
                -o-transform: rotate(331deg);
                transform: rotate(331deg);
                font-size: 5em;
                color: <?= htmlspecialchars($styling['primary_color']) ?>;
                position: absolute;
                font-family: 'Denk One', sans-serif;
                text-transform: uppercase;
                padding-left: 10%;
                bottom: 50%;
                opacity: <?= htmlspecialchars($styling['watermark_opacity']) ?>;
            }
                </style>
        <p class="rotingtxt"  opacity=<?= htmlspecialchars($styling['watermark_opacity']) ?> fill='<?= htmlspecialchars($styling['primary_color']) ?>'><?= htmlspecialchars($styling['watermark_text']) ?></p>
        
 <?php endif; ?>

<header>
    
    <table width="100%" style="margin-top:2mm; border-bottom:1px solid <?= htmlspecialchars($styling['primary_color']) ?>; padding-bottom:2mm;">
        <tr>
            <?php if ($styling['logo_url'] && $styling['logo_position'] === 'left'): ?>
                <td width="<?= $logo_size ?>" style="vertical-align:top;">
                    <img src="<?= htmlspecialchars(getAbsoluteLogoUrl($styling['logo_url'])) ?>" alt="Logo" style="padding-right: 20px;"  class="logo-left logo">
                </td>
            <?php endif; ?>

            <td style="text-align:<?= $styling['logo_position'] === 'center' ? 'center' : 'left' ?>; vertical-align:top; padding: 1mm;">
                <?php if ($styling['logo_url'] && $styling['logo_position'] === 'center'): ?>
                    <img src="<?= htmlspecialchars(getAbsoluteLogoUrl($styling['logo_url'])) ?>" alt="Logo" style="margin-bottom: 15px;" class="logo-center logo">
                    <br>
                <?php endif; ?>

                <div><?= $styling['header_content'] ?></div>

                <?php if ($styling['show_event_info']): ?>
                    <div style="color:<?= htmlspecialchars($styling['secondary_color']) ?>; padding-bottom: 2mm;">
                        <strong><?= htmlspecialchars($event_name ?? 'Event') ?></strong>,
                        <?= date('F d, Y', strtotime($event_date ?? date('Y-m-d'))) ?>,
                        <strong> <?= htmlspecialchars($event_location ?? 'Location') ?></strong>
                    </div>
                <?php endif; ?>
            </td>

            <?php if ($styling['logo_url'] && $styling['logo_position'] === 'right'): ?>
                <td width="<?= $logo_size ?>" style="vertical-align:top; text-align:right;">
                    <img src="<?= htmlspecialchars(getAbsoluteLogoUrl($styling['logo_url'])) ?>" alt="Logo" style="padding-left: 20px;" class="logo-right logo">
                </td>
            <?php endif; ?>
        </tr>
    </table>
</header>
   <footer>
   <!-- Footer Section -->
        <div class="footer-section" style="position: relative; margin-top: 0px; border-top: 1px solid <?= htmlspecialchars($styling['secondary_color']) ?>; padding-top: 0px; color: <?= htmlspecialchars($styling['secondary_color']) ?>;">
            <div><?= $styling['footer_content'] ?></div>
            
            <?php if ($styling['show_generation_date']): ?>
                <div style="position: absolute; bottom: 16mm; left: 0mm; margin-top: 0px; font-size: 7px; text-align: left;">
                <img src="<?=get_base_url()?>/assets/img/SVG/logo-ss-_1.svg" alt="Logo" style="height: 5mm;">
            </div>
                <div style="position: absolute; bottom: 0mm; left: 0mm; margin-top: 0px; font-size: 7px; text-align: left; color: black">
                    Generated on <?= date('F d, Y \a\t H:i') ?> | StyleScore.com Results System
                </div>
            <?php endif; ?>
        </div>
</footer>     
  <main class="content">
                  <?php
                
                $header_html = ob_get_clean();

                // Footer HTML
                ob_start();
            ?>
            
        </div>
                    </main>

  

 <?php if ($styling['custom_css']): ?>
            <style><?= htmlspecialchars($styling['custom_css']) ?></style>
        <?php endif; ?>


<?php
    $footer_html = ob_get_clean();

    return [
        'header_html' => $header_html,
        'footer_html' => $footer_html,
        'custom_css' => $styling['custom_css'] ?? '',
        'styling' => $styling
    ];
}


            function generateStyledPreview($styling) {
                $logo_sizes = [
                    'small' => '50px',
                    'medium' => '80px',
                    'large' => '120px'
                ];
                
                $margin_styles = [
                    'narrow' => '10mm',
                    'normal' => '20mm',
                    'wide' => '30mm'
                ];
                
                $logo_size = $logo_sizes[$styling['logo_size']] ?? '80px';
                $margins = $margin_styles[$styling['page_margins']] ?? '20mm';
                
                ob_start();
                ?>
                <div class="styled-preview">
 <style>
  :root{
    /* Tune these to your design */
    --header-h: 30mm;
    --footer-h: 15mm;
    --page-side: 10mm;
    
  }


    .content {
      /* No extra padding needed in print; @page margins handle spacing */
      padding: 0;
      
    }

    .page-numbers::after {
      content: "Page " counter(page) " of " counter(pages);
    }
  
  table {
    width: 100%;   
  }

.table th {
    background-color: #343a40 !important;
    color: white !important;
    border-color: #454d55 !important;
    white-space: nowrap;
    position: sticky;
    top: 0;
    z-index: 10;
    
}
 td.col-best {
    background-color: var(--bs-table-bg) !important;
}
  .col-best {
    text-align: center;
}
            header {
                width: 100%;
                position: fixed;
                top: 0cm;
                height: var(--header-h);
                background-color: silver;
            }

       
            footer {
                position: fixed; 
                bottom: 0cm; 
                left: 0cm;
                padding-left:var(--page-side); 
                padding-right:var(--page-side); 
                right: 0cm;
                padding-bottom: 0.3cm;
                background-color: silver;
            }
.col-figures td {
    font-size: .6em;
}
.col-figures {width: 10% !important;}
           
</style> 
            <?php if ($styling['watermark_text']): ?>
                        
            <style>.rotingtxt {
                -webkit-transform: rotate(331deg);
                -moz-transform: rotate(331deg);
                -o-transform: rotate(331deg);
                transform: rotate(331deg);
                font-size: 5em;
                color: <?= htmlspecialchars($styling['primary_color']) ?>;
                position: absolute;
                font-family: 'Denk One', sans-serif;
                text-transform: uppercase;
                padding-left: 10%;
                bottom: 50%;
                opacity: <?= htmlspecialchars($styling['watermark_opacity']) ?>;
            }
                </style>
                    <p class="rotingtxt"  opacity=<?= htmlspecialchars($styling['watermark_opacity']) ?> fill='<?= htmlspecialchars($styling['primary_color']) ?>'><?= htmlspecialchars($styling['watermark_text']) ?></p>
                    
            <?php endif; ?>
                    <!-- Header Section -->
            <div class="header-section" style="margin-bottom: 30px; border-bottom: 1px solid <?= htmlspecialchars($styling['primary_color']) ?>; padding-bottom: 20px;">
                        <div style="display: flex; align-items: center; <?= $styling['logo_position'] === 'center' ? 'justify-content: center; flex-direction: column;' : ($styling['logo_position'] === 'right' ? 'justify-content: flex-end;' : '') ?>">
                            <?php if ($styling['logo_url'] && $styling['logo_position'] !== 'center'): ?>
                                <img src="<?= htmlspecialchars($styling['logo_url']) ?>" alt="Logo" style="height: <?= $logo_size ?>; margin-<?= $styling['logo_position'] === 'right' ? 'left' : 'right' ?>: 20px;">
                            <?php endif; ?>
                            
                            <div style="<?= $styling['logo_position'] === 'center' ? 'text-align: center;' : 'flex: 1;' ?>">
                                <?php if ($styling['logo_url'] && $styling['logo_position'] === 'center'): ?>
                                    <img src="<?= htmlspecialchars($styling['logo_url']) ?>" alt="Logo" style="height: <?= $logo_size ?>; margin-bottom: 15px;">
                                <?php endif; ?>
                                
                                <div><?= $styling['header_content'] ?></div>
                                
                                <?php if ($styling['show_event_info']): ?>
                                    <div style="margin-top: 10px; color: <?= htmlspecialchars($styling['secondary_color']) ?>; font-size: 14px;">
                                        <strong>Event:</strong> Sample Championship 2025<br>
                                        <strong>Date:</strong> <?= date('F d, Y') ?><br>
                                        <strong>Location:</strong> Alpine Resort
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Sample Results Table -->
                    <div class="results-section">
                        <h3 style="color: <?= htmlspecialchars($styling['primary_color']) ?>; margin-bottom: 20px;">Final Results - Sample Category</h3>
                        
                        <table style="
                            width: 100%;
                            border-collapse: collapse;
                            margin: 20px 0;
                            <?= $styling['table_style'] === 'bordered' ? 'border: 1px solid #dee2e6;' : '' ?>
                        ">
                            <thead>
                                <tr style="background-color: <?= htmlspecialchars($styling['primary_color']) ?>; color: white;">
                                    <th style="padding: 12px; text-align: center; border: 1px solid rgba(255,255,255,0.2);">Rank</th>
                                    <th style="padding: 12px; text-align: left; border: 1px solid rgba(255,255,255,0.2);">Participant</th>
                                    <th style="padding: 12px; text-align: center; border: 1px solid rgba(255,255,255,0.2);">Club</th>
                                    <th style="padding: 12px; text-align: center; border: 1px solid rgba(255,255,255,0.2);">H1R1</th>
                                    <th style="padding: 12px; text-align: center; border: 1px solid rgba(255,255,255,0.2);">H1R2</th>
                                    <th style="padding: 12px; text-align: center; border: 1px solid rgba(255,255,255,0.2);">Final Score</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $sample_results = [
                                    ['1', '123 - John Smith', 'Alpine Club', '89.75', '91.25', '91.25'],
                                    ['2', '456 - Sarah Johnson', 'Mountain Team', '87.50', '89.00', '89.00'],
                                    ['3', '789 - Mike Wilson', 'Snow Sports', '85.25', '86.75', '86.75']
                                ];
                                
                                foreach ($sample_results as $i => $result): 
                                    $row_style = '';
                                    if ($styling['table_style'] === 'striped' && $i % 2 === 1) {
                                        $row_style = 'background-color: #f8f9fa;';
                                    }
                                    if ($i === 0) { // First place highlighting
                                        $row_style .= 'background-color: #fff3cd; font-weight: bold;';
                                    }
                                ?>
                                    <tr style="<?= $row_style ?>">
                                        <td style="padding: 10px; text-align: center; border: 1px solid #dee2e6;"><?= $result[0] ?></td>
                                        <td style="padding: 10px; border: 1px solid #dee2e6;"><?= $result[1] ?></td>
                                        <td style="padding: 10px; text-align: center; border: 1px solid #dee2e6;"><?= $result[2] ?></td>
                                        <td style="padding: 10px; text-align: center; border: 1px solid #dee2e6;"><?= $result[3] ?></td>
                                        <td style="padding: 10px; text-align: center; border: 1px solid #dee2e6;"><?= $result[4] ?></td>
                                        <td style="padding: 10px; text-align: center; border: 1px solid #dee2e6; font-weight: bold; color: <?= htmlspecialchars($styling['primary_color']) ?>;"><?= $result[5] ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Footer Section -->
                    <div class="footer-section" style="margin-top: 0px; border-top: 1px solid <?= htmlspecialchars($styling['secondary_color']) ?>; padding-top: 2mm; color: <?= htmlspecialchars($styling['secondary_color']) ?>;">
                        <div><?= $styling['footer_content'] ?></div>
                        
                        <?php if ($styling['show_generation_date']): ?>
                            <div style="margin-top: 10px; font-size: 12px; text-align: left;">
                                Generated on <?= date('F d, Y \a\t g:i A') ?> | StyleScore Results System
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <?php if ($styling['custom_css']): ?>
                        <style><?= htmlspecialchars($styling['custom_css']) ?></style>
                    <?php endif; ?>
                </div>
                <?php
                return ob_get_clean();
            }

// Get events and configurations for dropdowns
$events_stmt = $pdo->prepare("SELECT id, name, date FROM events ORDER BY date DESC, name");
$events_stmt->execute();
$events = $events_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Results Styling Configuration</title>
    <!-- style skin holder -->
<link id="bootswatch-theme"
      href="/v2/assets/bootswatch/<?= btTheme('nameCode') ?>/bootstrap.min.css"
      rel="stylesheet">
<link rel="stylesheet" href="/v2/assets/css/backgrounds.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">

    
    
    <!-- TinyMCE Editor -->
    <script src="https://cdn.tiny.cloud/1/v920kn6bxjd5o45dgai9xea1eq438vw3s7684j5l9n64cl10/tinymce/8/tinymce.min.js" referrerpolicy="origin" crossorigin="anonymous"></script>


    <style>
        .color-preview {
            width: 30px;
            height: 30px;
            border: 1px solid #ccc;
            border-radius: 4px;
            display: inline-block;
            margin-left: 10px;
            vertical-align: middle;
        }
        
        .logo-preview {
            max-width: 200px;
            max-height: 100px;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 5px;
            background: #f8f9fa;
        }
        
        .styled-preview {
            border: 1px solid #ddd;
            border-radius: 8px;
            overflow: hidden;
             font-family: "<?= htmlspecialchars($styling['font_family']) ?>" !important;
        }
        
        .upload-area {
            border: 2px dashed #ddd;
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            background: #f8f9fa;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .upload-area:hover {
            border-color: #0d6efd;
            background: #e7f1ff;
        }
        
        .upload-area.dragover {
            border-color: #0d6efd;
            background: #e7f1ff;
        }
.col-figures td {
    font-size: .6em !important;
}
.col-figures {width: 10% !important;}
    </style>
</head>

<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    
    <div class="container mt-4">
            <!-- event action menu. -->
<div class="row mb-3">
    <div class="col-12">
        <?php       
        $use_localStorage = true;
        $show_header = false;
        //$show_public_view = false;
        include 'event_actions_menu.php'; 
        ?>
    </div>
</div>
        <!-- Header -->
        <div class="card bg-gradient-primary mb-3">
            <div class="card-header py-2">
                <h5 class="card-title mb-0">
                    <i class="fas fa-palette me-2"></i>Results Styling Configuration
                </h5>
            </div>
            <div class="card-body py-2">
                <div class="row g-2">
                    <div class="col-md-6">
                        <label class="form-label mb-1 small">Select Event</label>
                        <select class="form-select form-select-sm" id="eventSelect">
                            <option value="">Choose an event</option>
                            <?php foreach ($events as $event): ?>
                                <option value="<?= $event['id'] ?>">
                                    <?= htmlspecialchars($event['name']) ?> 
                                    (<?= date('M d, Y', strtotime($event['date'])) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-6">
                        <label class="form-label mb-1 small">Configuration (Optional)</label>
                        <select class="form-select form-select-sm" id="configSelect" disabled>
                            <option value="">Event-wide styling (default)</option>
                        </select>
                        <small class="text-light opacity-75 d-block mt-1">Choose a specific configuration or leave blank for event-wide styling</small>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-lg-8">
                <!-- Logo Section -->
                <div class="card mb-3">
                    <div class="card-header py-2">
                        <h6 class="mb-0"><i class="fas fa-image me-2"></i>Logo Configuration</h6>
                    </div>
                    <div class="card-body py-2">
                        <div class="row g-2">
                            <div class="col-md-6">
                                <label class="form-label mb-1 small">Upload Logo</label>
                                <div class="upload-area" id="logoUploadArea" style="padding: 20px;">
                                    <i class="fas fa-cloud-upload-alt fa-2x text-muted mb-2"></i>
                                    <h6 class="small">Drag & drop logo or click to browse</h6>
                                    <p class="text-muted mb-0 small">JPG, PNG, GIF, SVG (max 5MB)</p>
                                    <input type="file" id="logoInput" accept="image/*" style="display: none;">
                                </div>
                                
                                <div id="logoPreview" class="mt-2" style="display: none;">
                                    <img id="logoImage" class="logo-preview" src="" alt="Logo preview">
                                    <button class="btn btn-sm btn-outline-danger mt-1" onclick="removeLogo()">
                                        <i class="fas fa-trash me-1"></i>Remove Logo
                                    </button>
                                </div>
                                
                                <input type="hidden" id="logoUrl" value="">
                            </div>
                            
                            <div class="col-md-6">
                                <div class="mb-2">
                                    <label class="form-label mb-1 small">Logo Position</label>
                                    <select class="form-select form-select-sm" id="logoPosition">
                                        <option value="left">Left</option>
                                        <option value="center">Center</option>
                                        <option value="right">Right</option>
                                    </select>
                                </div>
                                
                                <div class="mb-2">
                                    <label class="form-label mb-1 small">Logo Size</label>
                                    <select class="form-select form-select-sm" id="logoSize">
                                        <option value="small">Small (50px)</option>
                                        <option value="medium" selected>Medium (80px)</option>
                                        <option value="large">Large (120px)</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Header Section -->
                <div class="card mb-3">
                    <div class="card-header py-2">
                        <h6 class="mb-0"><i class="fas fa-heading me-2"></i>Header Configuration</h6>
                    </div>
                    <div class="card-body py-2">
                        <label class="form-label mb-1 small">Header Content</label>
                        <textarea id="headerContent" class="form-control form-control-sm" style="height: 120px;">
                            <h1 style="margin: 0; color: #0d6efd;">Championship Results</h1>
                            <p style="margin: 10px 0 0 0; font-size: 18px;">Official Final Results</p>
                        </textarea>
                        
                        <div class="form-check mt-2">
                            <input class="form-check-input" type="checkbox" id="showEventInfo" checked>
                            <label class="form-check-label small" for="showEventInfo">
                                Show Event Information (Name, Date, Location)
                            </label>
                        </div>
                    </div>
                </div>
                
               
                <!-- Footer Section -->
                <div class="card mb-3">
                    <div class="card-header py-2">
                        <h6 class="mb-0"><i class="fas fa-window-minimize me-2"></i>Footer Configuration</h6>
                    </div>
                    <div class="card-body py-2">
                        <label class="form-label mb-1 small">Footer Content</label>
                        <textarea id="footerContent" class="form-control form-control-sm" style="height: 120px;">
                            <p style="margin: 0; text-align: center;">
                                <strong>Official Results</strong><br>
                                For questions or corrections, please contact the event organizers.<br>
                                <em>Results are final and official</em>
                            </p>
                        </textarea>
                        
                        <div class="form-check mt-2">
                            <input class="form-check-input" type="checkbox" id="showGenerationDate" checked>
                            <label class="form-check-label small" for="showGenerationDate">
                                Show Generation Date and Time
                            </label>
                        </div>
                    </div>
                </div>
                
                <!-- Styling Options -->
                <div class="card mb-3">
                    <div class="card-header py-2">
                        <h6 class="mb-0"><i class="fas fa-paint-brush me-2"></i>Visual Styling</h6>
                    </div>
                    <div class="card-body py-2">
                        <div class="row g-2">
                            <div class="col-md-6">
                                <label class="form-label mb-1 small">Font Family</label>
                                <select class="form-select form-select-sm" id="fontFamily">
                                    <option value="DejaVu Sans">DejaVu Sans</option>
                                    <option value="DejaVu Serif">DejaVu Serif</option>
                                    <option value="DejaVu Sans Mono">DejaVu Sans Mono</option>
                                    <option value="HelveticaCustom">Helvetica</option>
                                    <option value="Times Roman">Times Roman</option>
                                    <option value="Courier">Courier</option>                                   
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label mb-1 small">Font Size (pt)</label>
                                <input type="number" class="form-control form-control-sm" id="fontSize" default="12" value="12" min="8" max="24">
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label mb-1 small">Primary Color</label>
                                <div class="input-group input-group-sm">
                                    <input type="color" class="form-control form-control-color" id="primaryColor" value="#0d6efd">
                                    <input type="text" class="form-control" id="primaryColorText" value="#0d6efd">
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label mb-1 small">Secondary Color</label>
                                <div class="input-group input-group-sm">
                                    <input type="color" class="form-control form-control-color" id="secondaryColor" value="#6c757d">
                                    <input type="text" class="form-control" id="secondaryColorText" value="#6c757d">
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label mb-1 small">Table Style</label>
                                <select class="form-select form-select-sm" id="tableStyle">
                                    <option value="striped">Striped Rows</option>
                                    <option value="bordered">Bordered</option>
                                    <option value="plain">Plain</option>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label mb-1 small">Page Margins</label>
                                <select class="form-select form-select-sm" id="pageMargins">
                                    <option value="narrow">Narrow (10mm)</option>
                                    <option value="normal" selected>Normal (20mm)</option>
                                    <option value="wide">Wide (30mm)</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Watermark Section -->
                <div class="card mb-3">
                    <div class="card-header py-2">
                        <h6 class="mb-0"><i class="fas fa-stamp me-2"></i>Watermark (Optional)</h6>
                    </div>
                    <div class="card-body py-2">
                        <div class="row g-2">
                            <div class="col-md-8">
                                <label class="form-label mb-1 small">Watermark Text</label>
                                <input type="text" class="form-control form-control-sm" id="watermarkText" placeholder="e.g., OFFICIAL, PRELIMINARY, CONFIDENTIAL">
                            </div>
                            
                            <div class="col-md-4">
                                <label class="form-label mb-1 small">Opacity</label>
                                <input type="range" class="form-range" id="watermarkOpacity" min="0.05" max="0.3" step="0.05" value="0.1">
                                <small class="text-muted">Current: <span id="opacityValue">0.1</span></small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Custom CSS -->
                <div class="card mb-3">
                    <div class="card-header py-2">
                        <h6 class="mb-0"><i class="fas fa-code me-2"></i>Custom CSS (Advanced)</h6>
                    </div>
                    <div class="card-body py-2">
                        <label class="form-label mb-1 small">Custom CSS Rules</label>
                        <textarea class="form-control form-control-sm" id="customCss" rows="4" placeholder="/* Add custom CSS rules here */
.first-place {
    background-color: #fff3cd !important;
    font-weight: bold;
}

.table th {
    font-weight: bold;
    text-transform: uppercase;
}"></textarea>
                        <small class="text-muted small">Advanced users can add custom CSS to further customize the appearance</small>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-4">
                <!-- Actions -->
                <div class="card mb-3">
                    <div class="card-header py-2">
                        <h6 class="mb-0"><i class="fas fa-cogs me-2"></i>Actions</h6>
                    </div>
                    <div class="card-body py-2">
                        <div class="d-grid gap-1">
                            <button class="btn btn-primary btn-sm" id="previewStylingBtn">
                                <i class="fas fa-eye me-1"></i>Preview Styling
                            </button>
                            
                            <button class="btn btn-success btn-sm" id="saveStylingBtn">
                                <i class="fas fa-save me-1"></i>Save Styling
                            </button>
                            
                            <button class="btn btn-info btn-sm" id="loadStylingBtn">
                                <i class="fas fa-download me-1"></i>Load Existing Styling
                            </button>
                            
                            <button class="btn btn-warning btn-sm" id="resetStylingBtn">
                                <i class="fas fa-undo me-1"></i>Reset to Defaults
                            </button>
                            
                            <hr class="my-2">
                            
                            <button class="btn btn-outline-secondary btn-sm" onclick="copyFromEvent()">
                                <i class="fas fa-copy me-1"></i>Copy from Another Event
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Quick Presets -->
                <div class="card mb-3">
                    <div class="card-header py-2">
                        <h6 class="mb-0"><i class="fas fa-magic me-2"></i>Quick Presets</h6>
                    </div>
                    <div class="card-body py-2">
                        <div class="d-grid gap-1">
                            <button class="btn btn-outline-primary btn-sm" onclick="applyPreset('professional')">
                                <i class="fas fa-briefcase me-1"></i>Professional
                            </button>
                            <button class="btn btn-outline-info btn-sm" onclick="applyPreset('sport')">
                                <i class="fas fa-medal me-1"></i>Sports Event
                            </button>
                            <button class="btn btn-outline-success btn-sm" onclick="applyPreset('elegant')">
                                <i class="fas fa-gem me-1"></i>Elegant
                            </button>
                            <button class="btn btn-outline-warning btn-sm" onclick="applyPreset('minimal')">
                                <i class="fas fa-minus me-1"></i>Minimal
                            </button>
                            <button class="btn btn-outline-warning btn-sm" onclick="applyPreset('consolas')">
                                <i class="fas fa-minus me-1"></i>Consolas
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Tips -->
                <div class="card">
                    <div class="card-header py-2">
                        <h6 class="mb-0"><i class="fas fa-lightbulb me-2"></i>Styling Tips</h6>
                    </div>
                    <div class="card-body py-2">
                        <ul class="list-unstyled small mb-0">
                            <li class="mb-1"><i class="fas fa-check text-success me-2"></i>Use high-resolution logos for better print quality</li>
                            <li class="mb-1"><i class="fas fa-check text-success me-2"></i>Keep font sizes 10-14pt for optimal readability</li>
                            <li class="mb-1"><i class="fas fa-check text-success me-2"></i>Use contrasting colors for headers and text</li>
                            <li class="mb-1"><i class="fas fa-check text-success me-2"></i>Test print preview before finalizing</li>
                            <li class="mb-1"><i class="fas fa-check text-success me-2"></i>Event-wide styling applies to all configurations</li>
                            <li class="mb-0"><i class="fas fa-check text-success me-2"></i>Config-specific styling overrides event styling</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Preview Modal -->
    <div class="modal fade" id="previewModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Styling Preview</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="previewContent">
                    <!-- Preview content will be loaded here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="window.print()">
                        <i class="fas fa-print me-2"></i>Print Preview
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentEventId = null;
        let currentConfigId = null;
        
        document.addEventListener('DOMContentLoaded', function() {
            initializeTinyMCE();
            setupEventHandlers();
            setupColorInputs();
            setupFileUpload();
            updateOpacityDisplay();
        });
        


        function initializeTinyMCE() {
            tinymce.init({
                selector: '#headerContent, #footerContent',
                height: 200,
                menubar: false,
                plugins: [
                    'advlist', 'autolink', 'lists', 'link', 'charmap', 'preview',
                    'searchreplace', 'visualblocks', 'code', 'fullscreen',
                    'insertdatetime', 'table', 'wordcount'
                ],
                toolbar: 'undo redo | blocks | bold italic forecolor backcolor | ' +
                         'alignleft aligncenter alignright alignjustify | ' +
                         'bullist numlist outdent indent | removeformat | code',
                content_style: 'body { font-family: Arial, sans-serif; font-size: 14px }'
            });
        }
        
        function setupEventHandlers() {
            document.getElementById('eventSelect').addEventListener('change', function() {
                currentEventId = this.value;
                if (currentEventId) {
                    loadConfigurations(currentEventId);
                    enableStylingForm();
                } else {
                    disableStylingForm();
                }
            });
            
            document.getElementById('configSelect').addEventListener('change', function() {
                currentConfigId = this.value || null;
            });
            
            document.getElementById('previewStylingBtn').addEventListener('click', previewStyling);
            document.getElementById('saveStylingBtn').addEventListener('click', saveStyling);
            document.getElementById('loadStylingBtn').addEventListener('click', loadStyling);
            document.getElementById('resetStylingBtn').addEventListener('click', resetStyling);
            
            document.getElementById('watermarkOpacity').addEventListener('input', updateOpacityDisplay);
        }
        
        function setupColorInputs() {
            const primaryColor = document.getElementById('primaryColor');
            const primaryColorText = document.getElementById('primaryColorText');
            const secondaryColor = document.getElementById('secondaryColor');
            const secondaryColorText = document.getElementById('secondaryColorText');
            
            primaryColor.addEventListener('change', function() {
                primaryColorText.value = this.value;
            });
            
            primaryColorText.addEventListener('change', function() {
                primaryColor.value = this.value;
            });
            
            secondaryColor.addEventListener('change', function() {
                secondaryColorText.value = this.value;
            });
            
            secondaryColorText.addEventListener('change', function() {
                secondaryColor.value = this.value;
            });
        }
        
        function setupFileUpload() {
            const uploadArea = document.getElementById('logoUploadArea');
            const fileInput = document.getElementById('logoInput');
            
            uploadArea.addEventListener('click', () => fileInput.click());
            uploadArea.addEventListener('dragover', handleDragOver);
            uploadArea.addEventListener('dragleave', handleDragLeave);
            uploadArea.addEventListener('drop', handleDrop);
            
            fileInput.addEventListener('change', handleFileSelect);
        }
        
        function handleDragOver(e) {
            e.preventDefault();
            e.currentTarget.classList.add('dragover');
        }
        
        function handleDragLeave(e) {
            e.preventDefault();
            e.currentTarget.classList.remove('dragover');
        }
        
        function handleDrop(e) {
            e.preventDefault();
            e.currentTarget.classList.remove('dragover');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                uploadLogo(files[0]);
            }
        }
        
        function handleFileSelect(e) {
            const files = e.target.files;
            if (files.length > 0) {
                uploadLogo(files[0]);
            }
        }
        
        function uploadLogo(file) {
            const formData = new FormData();
            formData.append('logo', file);
            formData.append('ajax', '1');
            formData.append('action', 'upload_logo');
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showLogoPreview(data.url);
                    document.getElementById('logoUrl').value = data.url;
                } else {
                    alert('Error uploading logo: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Upload error:', error);
                alert('Error uploading logo');
            });
        }
        
        function showLogoPreview(url) {
            document.getElementById('logoImage').src = url;
            document.getElementById('logoPreview').style.display = 'block';
        }
        
        function removeLogo() {
            document.getElementById('logoPreview').style.display = 'none';
            document.getElementById('logoUrl').value = '';
            document.getElementById('logoInput').value = '';
        }
        
        function updateOpacityDisplay() {
            const opacity = document.getElementById('watermarkOpacity').value;
            document.getElementById('opacityValue').textContent = opacity;
        }
        
        function loadConfigurations(eventId) {
            // In a real implementation, this would load configurations for the event
            // For now, we'll just enable the config select
            document.getElementById('configSelect').disabled = false;
        }
        
        function enableStylingForm() {
            // Enable all form elements
            document.querySelectorAll('#headerContent, #footerContent, select, input').forEach(el => {
                el.disabled = false;
            });
        }
        
        function disableStylingForm() {
            // Disable all form elements
            document.querySelectorAll('#headerContent, #footerContent, select, input').forEach(el => {
                el.disabled = true;
            });
        }
        
        function gatherStylingData() {
            return {
                event_id: currentEventId,
                config_id: currentConfigId,
                header_content: tinymce.get('headerContent').getContent(),
                footer_content: tinymce.get('footerContent').getContent(),
                logo_url: document.getElementById('logoUrl').value,
                logo_position: document.getElementById('logoPosition').value,
                logo_size: document.getElementById('logoSize').value,
                font_family: document.getElementById('fontFamily').value,
                font_size: document.getElementById('fontSize').value,
                primary_color: document.getElementById('primaryColor').value,
                secondary_color: document.getElementById('secondaryColor').value,
                table_style: document.getElementById('tableStyle').value,
                page_margins: document.getElementById('pageMargins').value,
                show_event_info: document.getElementById('showEventInfo').checked ? '1' : '0',
                show_generation_date: document.getElementById('showGenerationDate').checked ? '1' : '0',
                custom_css: document.getElementById('customCss').value,
                watermark_text: document.getElementById('watermarkText').value,
                watermark_opacity: document.getElementById('watermarkOpacity').value
            };
        }
        
        function previewStyling() {
            if (!currentEventId) {
                alert('Please select an event first');
                return;
            }
            
            const stylingData = gatherStylingData();
            
            fetch(window.location.href, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    ajax: '1',
                    action: 'preview_styling',
                    ...stylingData
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('previewContent').innerHTML = data.html;
                    const modal = new bootstrap.Modal(document.getElementById('previewModal'));
                    modal.show();
                } else {
                    alert('Error generating preview: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Preview error:', error);
                alert('Error generating preview');
            });
        }
        
        function saveStyling() {
            if (!currentEventId) {
                alert('Please select an event first');
                return;
            }
            
            const stylingData = gatherStylingData();
            
            fetch(window.location.href, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    ajax: '1',
                    action: 'save_styling',
                    ...stylingData
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Styling saved successfully!');
                } else {
                    alert('Error saving styling: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Save error:', error);
                alert('Error saving styling');
            });
        }
        
        function loadStyling() {
            if (!currentEventId) {
                alert('Please select an event first');
                return;
            }
            
            fetch(window.location.href, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    ajax: '1',
                    action: 'load_styling',
                    event_id: currentEventId,
                    config_id: currentConfigId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.styling) {
                    loadStylingIntoForm(data.styling);
                    alert('Styling loaded successfully!');
                } else if (data.success && !data.styling) {
                    alert('No existing styling found for this event/configuration');
                } else {
                    alert('Error loading styling: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Load error:', error);
                alert('Error loading styling');
            });
        }
        
        function loadStylingIntoForm(styling) {
            // Load basic styling data
            if (styling.logo_url) {
                document.getElementById('logoUrl').value = styling.logo_url;
                showLogoPreview(styling.logo_url);
            }
            
            document.getElementById('logoPosition').value = styling.logo_position || 'left';
            document.getElementById('logoSize').value = styling.logo_size || 'medium';
            document.getElementById('fontFamily').value = styling.font_family || 'Arial';
            document.getElementById('fontSize').value = styling.font_size || '12';
            document.getElementById('primaryColor').value = styling.primary_color || '#0d6efd';
            document.getElementById('primaryColorText').value = styling.primary_color || '#0d6efd';
            document.getElementById('secondaryColor').value = styling.secondary_color || '#6c757d';
            document.getElementById('secondaryColorText').value = styling.secondary_color || '#6c757d';
            document.getElementById('tableStyle').value = styling.table_style || 'striped';
            document.getElementById('pageMargins').value = styling.page_margins || 'normal';
            document.getElementById('showEventInfo').checked = styling.show_event_info === '1';
            document.getElementById('showGenerationDate').checked = styling.show_generation_date === '1';
            document.getElementById('customCss').value = styling.custom_css || '';
            document.getElementById('watermarkText').value = styling.watermark_text || '';
            document.getElementById('watermarkOpacity').value = styling.watermark_opacity || '0.1';
            
            // Load editor content
            setTimeout(() => {
                tinymce.get('headerContent').setContent(styling.header_content || '');
                tinymce.get('footerContent').setContent(styling.footer_content || '');
            }, 100);
            
            updateOpacityDisplay();
        }
        
        function resetStyling() {
            if (!confirm('Are you sure you want to reset all styling to defaults? This will lose any unsaved changes.')) {
                return;
            }
            
            // Reset all form fields to defaults
            document.getElementById('logoUrl').value = '';
            document.getElementById('logoPreview').style.display = 'none';
            document.getElementById('logoPosition').value = 'left';
            document.getElementById('logoSize').value = 'medium';
            document.getElementById('fontFamily').value = 'Arial';
            document.getElementById('fontSize').value = '12';
            document.getElementById('primaryColor').value = '#0d6efd';
            document.getElementById('primaryColorText').value = '#0d6efd';
            document.getElementById('secondaryColor').value = '#6c757d';
            document.getElementById('secondaryColorText').value = '#6c757d';
            document.getElementById('tableStyle').value = 'striped';
            document.getElementById('pageMargins').value = 'normal';
            document.getElementById('showEventInfo').checked = true;
            document.getElementById('showGenerationDate').checked = true;
            document.getElementById('customCss').value = '';
            document.getElementById('watermarkText').value = '';
            document.getElementById('watermarkOpacity').value = '0.1';
            
            // Reset editor content
            tinymce.get('headerContent').setContent('<h1 style="margin: 0; color: #0d6efd;">Championship Results</h1><p style="margin: 10px 0 0 0; font-size: 18px;">Official Final Results</p>');
            tinymce.get('footerContent').setContent('<p style="margin: 0; text-align: center;"><strong>Official Results</strong><br>For questions or corrections, please contact the event organizers.<br><em>Results are final and official</em></p>');
            
            updateOpacityDisplay();
        }
        
        function applyPreset(presetName) {
            const presets = {
                professional: {
                    primary_color: '#1f2937',
                    secondary_color: '#6b7280',
                    font_family: 'Times New Roman',
                    table_style: 'bordered',
                    header_content: '<h1 style="margin: 0; color: #1f2937; font-weight: bold; text-align: center;">OFFICIAL RESULTS</h1><p style="margin: 10px 0 0 0; font-size: 16px; text-align: center; font-weight: 600;">Championship Competition</p>',
                    footer_content: '<p style="margin: 0; text-align: center; font-size: 12px;"><strong>CERTIFIED OFFICIAL RESULTS</strong><br>This document contains the official results as certified by the competition committee.<br><em>Any protests must be submitted within 24 hours of publication</em></p>'
                },
                sport: {
                    primary_color: '#dc2626',
                    secondary_color: '#991b1b',
                    font_family: 'Arial',
                    table_style: 'striped',
                    header_content: '<h1 style="margin: 0; color: #dc2626; font-weight: bold;">🏆 COMPETITION RESULTS</h1><p style="margin: 10px 0 0 0; font-size: 18px; color: #991b1b;">Final Rankings</p>',
                    footer_content: '<p style="margin: 0; text-align: center;"><strong>🎖️ Congratulations to all participants! 🎖️</strong><br>Results verified by official judges<br><em>Great competition, see you next time!</em></p>'
                },
                elegant: {
                    primary_color: '#7c3aed',
                    secondary_color: '#a855f7',
                    font_family: 'Georgia',
                    table_style: 'plain',
                    header_content: '<div style="text-align: center;"><h1 style="margin: 0; color: #7c3aed; font-family: Georgia; font-style: italic;">Championship Results</h1><div style="margin: 15px 0; height: 2px; background: linear-gradient(to right, #7c3aed, #a855f7, #7c3aed);"></div><p style="margin: 0; font-size: 16px; color: #a855f7;">Official Final Rankings</p></div>',
                    footer_content: '<div style="text-align: center; font-family: Georgia;"><div style="margin: 15px 0; height: 1px; background: #a855f7;"></div><p style="margin: 0; font-style: italic;">Official competition results</p><p style="margin: 5px 0 0 0; font-size: 12px;">Verified and approved by competition officials</p></div>'
                },
                minimal: {
                    primary_color: '#000000',
                    secondary_color: '#666666',
                    font_family: 'Helvetica',
                    table_style: 'plain',
                    header_content: '<h1 style="margin: 0; color: #000000; font-weight: normal;">Results</h1>',
                    footer_content: '<p style="margin: 0; color: #666666; font-size: 12px;">Official results</p>'
                },
                consolas: {
                    primary_color: '#000000',
                    secondary_color: '#666666',
                    font_family: 'monospace',
                    table_style: 'plain',
                    header_content: '<h2 style="margin: 0; color: #000000; font-weight: normal;">Results</h2>',
                    footer_content: '<p style="margin: 0; color: #666666; font-size: 10px;">Official results</p>'
                }
            };
            
            const preset = presets[presetName];
            if (!preset) return;
            
            // Apply preset values
            document.getElementById('primaryColor').value = preset.primary_color;
            document.getElementById('primaryColorText').value = preset.primary_color;
            document.getElementById('secondaryColor').value = preset.secondary_color;
            document.getElementById('secondaryColorText').value = preset.secondary_color;
            document.getElementById('fontFamily').value = preset.font_family;
            document.getElementById('tableStyle').value = preset.table_style;
            
            // Apply editor content
            tinymce.get('headerContent').setContent(preset.header_content);
            tinymce.get('footerContent').setContent(preset.footer_content);
            
            alert(`Applied ${presetName} preset!`);
        }
        
        function copyFromEvent() {
            // This would open a modal to select another event and copy its styling
            alert('Copy from another event functionality would be implemented here');
        }
    </script>
</body>
</html>