<?php
require_once '../includes/db.php';
require_once 'publish_generators.php';

echo "<h2>Event 3 Photo Test</h2>";

$event_id = 3;
echo "<p><strong>Testing specifically with Event ID: $event_id</strong></p>";

// Check event details
try {
    $event_stmt = $pdo->prepare("SELECT * FROM events WHERE id = ?");
    $event_stmt->execute([$event_id]);
    $event = $event_stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($event) {
        echo "<p>Event: {$event['name']}</p>";
    } else {
        echo "<p style='color: red;'>Event ID $event_id not found!</p>";
        exit;
    }
} catch (Exception $e) {
    echo "<p style='color: red;'>Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    exit;
}

// Check participants with photos for this event
echo "<h3>Participants with Photos in Event 3</h3>";
try {
    $stmt = $pdo->prepare("
        SELECT p.id, p.photo, p.first_name, p.last_name, ep.bib_number
        FROM participants p
        INNER JOIN event_participants ep ON p.id = ep.participant_id
        WHERE ep.event_id = ? AND p.photo IS NOT NULL AND p.photo != ''
    ");
    $stmt->execute([$event_id]);
    $participants = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<p>Found " . count($participants) . " participants with photos</p>";
    
    if (count($participants) > 0) {
        echo "<table border='1' style='width: 100%;'>";
        echo "<tr><th>BIB</th><th>Name</th><th>Photo File</th><th>File Exists</th><th>Location</th></tr>";
        
        foreach ($participants as $participant) {
            echo "<tr>";
            echo "<td>{$participant['bib_number']}</td>";
            echo "<td>{$participant['first_name']} {$participant['last_name']}</td>";
            echo "<td>" . htmlspecialchars($participant['photo']) . "</td>";
            
            // Check if file exists in profile_stills directory
            $profile_stills_path = dirname(__DIR__) . '/uploads/profile_stills/' . $participant['photo'];
            $real_path = realpath($profile_stills_path);
            
            if ($real_path && file_exists($real_path)) {
                echo "<td style='color: green;'>✓ YES</td>";
                echo "<td>" . htmlspecialchars($real_path) . "</td>";
            } else {
                echo "<td style='color: red;'>✗ NO</td>";
                echo "<td>Not found at: " . htmlspecialchars($profile_stills_path) . "</td>";
            }
            
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "<p style='color: orange;'>No participants with photos found in Event 3</p>";
    }
    
} catch (Exception $e) {
    echo "<p style='color: red;'>Error: " . htmlspecialchars($e->getMessage()) . "</p>";
}

// Test photo copying for Event 3
echo "<h3>Testing Photo Copy for Event 3</h3>";

$test_dir = sys_get_temp_dir() . '/event3_photo_test_' . time();
if (!is_dir($test_dir)) {
    mkdir($test_dir, 0777, true);
}

echo "<p>Test directory: $test_dir</p>";

try {
    $start_time = microtime(true);
    $photo_files = copyParticipantPhotos($event_id, $test_dir, $pdo);
    $end_time = microtime(true);
    $duration = round(($end_time - $start_time) * 1000, 2);
    
    echo "<p>Function completed in ${duration}ms</p>";
    echo "<p style='font-size: 1.2em; font-weight: bold;'>Returned " . count($photo_files) . " photo files</p>";
    
    if (count($photo_files) > 0) {
        echo "<div style='background: #d4edda; padding: 15px; border: 1px solid #c3e6cb; border-radius: 5px;'>";
        echo "<h4>✅ SUCCESS: Photos copied!</h4>";
        echo "<p>The photo copy function is working correctly.</p>";
        echo "</div>";
        
        echo "<h4>Photo Files Generated:</h4>";
        echo "<table border='1' style='width: 100%;'>";
        echo "<tr><th>Remote Path</th><th>Local Path</th><th>Exists</th><th>Size</th></tr>";
        
        foreach ($photo_files as $file) {
            $exists = file_exists($file['local']);
            $size = $exists ? filesize($file['local']) : 0;
            
            echo "<tr>";
            echo "<td>" . htmlspecialchars($file['remote']) . "</td>";
            echo "<td>" . htmlspecialchars($file['local']) . "</td>";
            echo "<td style='color: " . ($exists ? 'green' : 'red') . ";'>" . ($exists ? "✓" : "✗") . "</td>";
            echo "<td>" . $size . " bytes</td>";
            echo "</tr>";
        }
        echo "</table>";
        
        echo "<h4>Next Steps:</h4>";
        echo "<ul>";
        echo "<li>✅ Photos are being copied correctly</li>";
        echo "<li>🚀 Now test the complete publish process</li>";
        echo "<li>📁 Check if photos upload to your FTP server</li>";
        echo "</ul>";
        
    } else {
        echo "<div style='background: #fff3cd; padding: 15px; border: 1px solid #ffeaa7; border-radius: 5px;'>";
        echo "<h4>⚠️ No photos copied</h4>";
        echo "<p>Check the error log for detailed debugging information.</p>";
        echo "</div>";
    }
    
} catch (Exception $e) {
    echo "<p style='color: red;'>Exception: " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
}

// Check photos directory
$photos_dir = $test_dir . '/photos';
if (file_exists($photos_dir)) {
    echo "<h4>Photos Directory Contents:</h4>";
    $files_in_dir = glob($photos_dir . '/*');
    echo "<p>Files found: " . count($files_in_dir) . "</p>";
    
    if (count($files_in_dir) > 0) {
        echo "<ul>";
        foreach ($files_in_dir as $file) {
            echo "<li>" . basename($file) . " (" . filesize($file) . " bytes)</li>";
        }
        echo "</ul>";
    }
}

// Test complete publish process
echo "<h3>Test Complete Publish Process</h3>";
echo "<p>Now that we've confirmed photos are copying correctly, let's test the complete HTML dashboard generation:</p>";

try {
    $publish_start = microtime(true);
    $all_files = generateHTMLDashboard($event_id, $test_dir, $pdo);
    $publish_end = microtime(true);
    $publish_duration = round(($publish_end - $publish_start) * 1000, 2);
    
    echo "<p>Complete publish took ${publish_duration}ms</p>";
    echo "<p>Generated " . count($all_files) . " total files</p>";
    
    // Count different file types
    $file_types = [];
    foreach ($all_files as $file) {
        $ext = pathinfo($file['remote'], PATHINFO_EXTENSION);
        $file_types[$ext] = ($file_types[$ext] ?? 0) + 1;
    }
    
    echo "<h4>File Types Generated:</h4>";
    echo "<ul>";
    foreach ($file_types as $ext => $count) {
        echo "<li>.$ext: $count files</li>";
    }
    echo "</ul>";
    
    // Check specifically for photos
    $photo_files_in_publish = array_filter($all_files, function($file) {
        return strpos($file['remote'], 'photos/') === 0;
    });
    
    echo "<h4>Photos in Publish:</h4>";
    if (count($photo_files_in_publish) > 0) {
        echo "<p style='color: green; font-weight: bold;'>✅ " . count($photo_files_in_publish) . " photo files included in publish!</p>";
        echo "<ul>";
        foreach ($photo_files_in_publish as $photo) {
            echo "<li>" . htmlspecialchars($photo['remote']) . "</li>";
        }
        echo "</ul>";
    } else {
        echo "<p style='color: red; font-weight: bold;'>❌ No photo files in publish</p>";
    }
    
} catch (Exception $e) {
    echo "<p style='color: red;'>Error in complete publish: " . htmlspecialchars($e->getMessage()) . "</p>";
}

// Clean up
if (is_dir($test_dir)) {
    // Remove files first
    $files = glob($test_dir . '/*');
    foreach ($files as $file) {
        if (is_file($file)) {
            unlink($file);
        }
    }
    
    // Remove subdirectories
    $subdirs = glob($test_dir . '/*', GLOB_ONLYDIR);
    foreach ($subdirs as $subdir) {
        $subfiles = glob($subdir . '/*');
        foreach ($subfiles as $subfile) {
            if (is_file($subfile)) {
                unlink($subfile);
            }
        }
        rmdir($subdir);
    }
    
    rmdir($test_dir);
    echo "<p>✅ Cleaned up test directory</p>";
}

echo "<div style='background: #e7f3ff; padding: 15px; border: 1px solid #bee5eb; border-radius: 5px; margin-top: 20px;'>";
echo "<h3>🎯 Summary</h3>";
echo "<p>This test specifically checks Event ID 3 and the <code>v2/uploads/profile_stills</code> directory.</p>";
echo "<p>If photos are copying correctly here, they should now upload properly through the publish system!</p>";
echo "<p><strong>Next step:</strong> <a href='publish_servers.php'>Test actual FTP upload via Publish Servers</a></p>";
echo "</div>";
?>
