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

echo "<h2>Photo Copy Test</h2>";

// Get first available event
try {
    $events_stmt = $pdo->query("SELECT id, name FROM events ORDER BY id ASC LIMIT 1");
    $event = $events_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$event) {
        echo "<p style='color: red;'>No events found!</p>";
        exit;
    }
    
    $event_id = $event['id'];
    echo "<p><strong>Testing with Event: {$event['name']} (ID: $event_id)</strong></p>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    exit;
}

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

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

echo "<h3>Testing Photo Copy Function</h3>";

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>Returned " . count($photo_files) . " photo files</p>";
    
    if (count($photo_files) > 0) {
        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>" . ($exists ? "✓" : "✗") . "</td>";
            echo "<td>" . $size . " bytes</td>";
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "<p style='color: orange;'>No photo files were generated.</p>";
    }
    
} catch (Exception $e) {
    echo "<p style='color: red;'>Exception: " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
}

echo "<h3>Check Error Log</h3>";
echo "<p>Check your PHP error log for detailed debugging information. The log should contain detailed information about:</p>";
echo "<ul>";
echo "<li>How many participants with photos were found</li>";
echo "<li>Which paths were tried for each photo</li>";
echo "<li>Whether photos were found and copied successfully</li>";
echo "<li>Any errors during the copy process</li>";
echo "</ul>";

// Check if photos directory was created
$photos_dir = $test_dir . '/photos';
if (file_exists($photos_dir)) {
    echo "<p style='color: green;'>✓ Photos directory was created: $photos_dir</p>";
    
    $files_in_dir = glob($photos_dir . '/*');
    echo "<p>Files in photos directory: " . 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>";
    }
} else {
    echo "<p style='color: red;'>✗ Photos directory was not created</p>";
}

// Manual photo check
echo "<h3>Manual Photo Check</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 != ''
        LIMIT 3
    ");
    $stmt->execute([$event_id]);
    $participants = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<p>Sample participants with photos:</p>";
    foreach ($participants as $participant) {
        echo "<h4>{$participant['first_name']} {$participant['last_name']}</h4>";
        echo "<p>Photo: " . htmlspecialchars($participant['photo']) . "</p>";
        
        // Test paths manually
        $test_paths = [
            dirname(__DIR__) . '/uploads/' . $participant['photo'],
            dirname(__DIR__) . '/uploads/participants/' . $participant['photo'],
            dirname(__DIR__) . '/uploads/profile_stills/' . $participant['photo']
        ];
        
        foreach ($test_paths as $path) {
            $real_path = realpath($path);
            if ($real_path && file_exists($real_path)) {
                echo "<p style='color: green;'>✓ Found at: $path</p>";
                echo "<p>Real path: $real_path</p>";
                echo "<p>File size: " . filesize($real_path) . " bytes</p>";
                break;
            } else {
                echo "<p style='color: red;'>✗ Not at: $path</p>";
            }
        }
    }
    
} catch (Exception $e) {
    echo "<p style='color: red;'>Error checking participants: " . 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>";
}
?>
