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

header('Content-Type: application/json');

$event_id = $_POST['event_id'] ?? 3;

echo "Testing save_styling action...\n\n";

// Prepare test data
$styling_data = [
    'header_content' => '<h2>Test Event Header</h2>',
    'footer_content' => '<p>Test Footer Content</p>',
    'logo_url' => 'uploads/logos/test.png',
    'logo_position' => 'left',
    'logo_size' => 'medium',
    'font_family' => 'Arial',
    'font_size' => '12',
    'primary_color' => '#0d6efd',
    'secondary_color' => '#6c757d',
    'table_style' => 'striped',
    'page_margins' => 'normal',
    'show_event_info' => '1',
    'show_generation_date' => '1',
    'custom_css' => '',
    'watermark_text' => '',
    'watermark_opacity' => '0.1'
];

try {
    // Check if styling already exists
    $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()) {
        echo "Updating existing styling...\n";
        $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 {
        echo "Inserting new styling...\n";
        $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 "✓ Styling saved successfully!\n";
    echo "Event ID: $event_id\n";
    echo "Styling Data: " . json_encode($styling_data, JSON_PRETTY_PRINT) . "\n";
    
    // Verify it was saved
    $verify_stmt = $pdo->prepare("SELECT * FROM result_styling WHERE event_id = ? AND config_id IS NULL");
    $verify_stmt->execute([$event_id]);
    $saved = $verify_stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($saved) {
        echo "\n✓ Verification: Found in database\n";
        echo "ID: " . $saved['id'] . "\n";
        echo "Created: " . $saved['created_at'] . "\n";
        $saved_styling = json_decode($saved['styling_data'], true);
        echo "Header Content: " . $saved_styling['header_content'] . "\n";
    } else {
        echo "\n✗ ERROR: Not found in database after save!\n";
    }
    
    echo json_encode(['success' => true, 'message' => 'Test save completed']);
} catch (Exception $e) {
    echo "\n✗ ERROR: " . $e->getMessage() . "\n";
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
