<?php
/**
 * Create General Summary Table Configuration for Event 6
 * 
 * This script creates a general (all heats) summary table configuration
 * based on the existing config 74, but with heat_number set to NULL
 * so it appears in the "General Reports" section.
 */

include 'includes/db.php';

$event_id = 6;
$source_config_id = 74;

try {
    // Check if a general summary table already exists for this event
    $stmt = $pdo->prepare("
        SELECT id, name 
        FROM result_configurations 
        WHERE event_id = ? 
        AND view_type = 'summary_table' 
        AND (heat_number IS NULL OR heat_number = '')
        AND status = 'public'
    ");
    $stmt->execute([$event_id]);
    $existing = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($existing) {
        echo "✓ General summary table configuration already exists:\n";
        echo "  ID: {$existing['id']}\n";
        echo "  Name: {$existing['name']}\n";
        exit(0);
    }
    
    // Fetch the source configuration
    $stmt = $pdo->prepare("
        SELECT * 
        FROM result_configurations 
        WHERE id = ?
    ");
    $stmt->execute([$source_config_id]);
    $source = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$source) {
        echo "✗ Source configuration {$source_config_id} not found!\n";
        exit(1);
    }
    
    echo "Source configuration found:\n";
    echo "  ID: {$source['id']}\n";
    echo "  Name: {$source['name']}\n";
    echo "  Heat Number: {$source['heat_number']}\n";
    echo "\n";
    
    // Create new configuration with heat_number = NULL
    $new_name = "Summary Table - SNOWFEST Festival - General Report";
    
    $stmt = $pdo->prepare("
        INSERT INTO result_configurations 
        (event_id, name, view_type, heat_number, category, status, display_order, configuration, created_by, created_at, updated_at)
        VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?, NOW(), NOW())
    ");
    
    $stmt->execute([
        $source['event_id'],
        $new_name,
        $source['view_type'],
        $source['category'],
        'public',  // Make it public so it shows on dashboard
        0,  // Display first
        $source['configuration'],
        $source['created_by']  // Use same creator as source config
    ]);
    
    $new_id = $pdo->lastInsertId();
    
    echo "✓ Created new general summary table configuration:\n";
    echo "  ID: {$new_id}\n";
    echo "  Name: {$new_name}\n";
    echo "  Heat Number: NULL (all heats)\n";
    echo "  Status: public\n";
    echo "  Display Order: 0\n";
    echo "\n";
    echo "✓ This configuration will now appear in the 'General Reports - Summary Table' section\n";
    echo "  on the public event dashboard!\n";
    
} catch (PDOException $e) {
    echo "✗ Database error: " . $e->getMessage() . "\n";
    exit(1);
}
