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

echo "<h1>Photo Upload Diagnostic & Fix</h1>";

echo "<h2>Problem Analysis</h2>";
echo "<p>You mentioned that only logo files are uploading but participant photos are not. Let's identify and fix the issue.</p>";

echo "<h3>Step 1: Check if participants have photos</h3>";
try {
    $stmt = $pdo->query("
        SELECT 
            COUNT(*) as total,
            COUNT(CASE WHEN photo IS NOT NULL AND photo != '' THEN 1 END) as with_photos
        FROM participants
    ");
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    echo "<p><strong>Total participants:</strong> {$stats['total']}</p>";
    echo "<p><strong>Participants with photos:</strong> {$stats['with_photos']}</p>";
    
    if ($stats['with_photos'] == 0) {
        echo "<div style='background: #fff3cd; padding: 15px; border: 1px solid #ffeaa7; border-radius: 5px;'>";
        echo "<h4>🟡 Issue Found: No Photos in Database</h4>";
        echo "<p>There are no participant photos in the database. This is why photos aren't uploading.</p>";
        echo "<p><strong>Solution:</strong> Add participant photos through the StyleScore admin interface first.</p>";
        echo "</div>";
    } else {
        echo "<div style='background: #d4edda; padding: 15px; border: 1px solid #c3e6cb; border-radius: 5px;'>";
        echo "<h4>✅ Photos exist in database</h4>";
        echo "<p>Found {$stats['with_photos']} participants with photos. Let's check file locations...</p>";
        echo "</div>";
        
        // Check file locations
        echo "<h3>Step 2: Check photo file locations</h3>";
        $stmt = $pdo->query("
            SELECT photo 
            FROM participants 
            WHERE photo IS NOT NULL AND photo != '' 
            LIMIT 3
        ");
        $sample_photos = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
        $photos_found = 0;
        $photo_locations = [];
        
        foreach ($sample_photos as $photo) {
            $possible_paths = [
                dirname(__DIR__) . '/uploads/' . $photo,
                dirname(__DIR__) . '/uploads/participants/' . $photo,
                dirname(__DIR__) . '/uploads/profile_stills/' . $photo,
                dirname(dirname(__DIR__)) . '/uploads/' . $photo,
                $_SERVER['DOCUMENT_ROOT'] . '/uploads/' . $photo,
                $_SERVER['DOCUMENT_ROOT'] . '/v2/uploads/' . $photo,
                $_SERVER['DOCUMENT_ROOT'] . '/stylescore2025/htdocs/v2/uploads/' . $photo
            ];
            
            foreach ($possible_paths as $path) {
                if (file_exists($path) && is_readable($path)) {
                    $photos_found++;
                    $photo_locations[] = dirname($path);
                    echo "<p style='color: green;'>✅ Found: $photo at $path</p>";
                    break;
                }
            }
        }
        
        if ($photos_found == 0) {
            echo "<div style='background: #f8d7da; padding: 15px; border: 1px solid #f5c6cb; border-radius: 5px;'>";
            echo "<h4>🔴 Issue Found: Photo Files Not Found</h4>";
            echo "<p>Photo filenames exist in database but actual files are missing.</p>";
            echo "<p><strong>Solutions:</strong></p>";
            echo "<ul>";
            echo "<li>Upload participant photos to the correct directory</li>";
            echo "<li>Check if photos are in a different directory structure</li>";
            echo "<li>Verify file permissions on upload directories</li>";
            echo "</ul>";
            echo "</div>";
        } else {
            echo "<div style='background: #d4edda; padding: 15px; border: 1px solid #c3e6cb; border-radius: 5px;'>";
            echo "<h4>✅ Photo files found</h4>";
            echo "<p>Found $photos_found photos. Common locations:</p>";
            echo "<ul>";
            foreach (array_unique($photo_locations) as $location) {
                echo "<li>$location</li>";
            }
            echo "</ul>";
            echo "</div>";
        }
    }
    
} catch (Exception $e) {
    echo "<div style='background: #f8d7da; padding: 15px; border: 1px solid #f5c6cb; border-radius: 5px;'>";
    echo "<h4>🔴 Database Error</h4>";
    echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>";
    echo "</div>";
}

echo "<h3>Step 3: Check publish system configuration</h3>";

// Check if there are any publish servers configured
try {
    $servers_stmt = $pdo->query("SELECT COUNT(*) FROM publish_servers");
    $server_count = $servers_stmt->fetchColumn();
    
    if ($server_count == 0) {
        echo "<div style='background: #fff3cd; padding: 15px; border: 1px solid #ffeaa7; border-radius: 5px;'>";
        echo "<h4>🟡 No Publish Servers Configured</h4>";
        echo "<p>You need to configure a publish server first.</p>";
        echo "<p><a href='publish_servers.php' class='btn btn-primary'>Configure Publish Servers</a></p>";
        echo "</div>";
    } else {
        echo "<div style='background: #d4edda; padding: 15px; border: 1px solid #c3e6cb; border-radius: 5px;'>";
        echo "<h4>✅ Found $server_count publish server(s)</h4>";
        echo "</div>";
    }
    
} catch (Exception $e) {
    echo "<div style='background: #fff3cd; padding: 15px; border: 1px solid #ffeaa7; border-radius: 5px;'>";
    echo "<h4>🟡 Publish servers table may not exist</h4>";
    echo "<p>This is normal if you haven't set up publish servers yet.</p>";
    echo "</div>";
}

echo "<h3>Step 4: Test photo copy function</h3>";

// Test with a real event
try {
    $event_stmt = $pdo->query("SELECT id, name FROM events ORDER BY id DESC LIMIT 1");
    $event = $event_stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($event) {
        echo "<p>Testing with event: {$event['name']} (ID: {$event['id']})</p>";
        
        // Test the photo copy function
        $test_dir = sys_get_temp_dir() . '/photo_test_' . time();
        mkdir($test_dir, 0777, true);
        
        // Include the function
        require_once 'publish_generators.php';
        
        $photo_files = copyParticipantPhotos($event['id'], $test_dir, $pdo);
        
        echo "<p>Photo copy function returned " . count($photo_files) . " files</p>";
        
        if (count($photo_files) > 0) {
            echo "<div style='background: #d4edda; padding: 15px; border: 1px solid #c3e6cb; border-radius: 5px;'>";
            echo "<h4>✅ Photos copied successfully</h4>";
            echo "<p>The photo copy function is working. Photos should upload with the next publish.</p>";
            echo "</div>";
            
            echo "<h4>Copied files:</h4>";
            echo "<ul>";
            foreach ($photo_files as $file) {
                $size = file_exists($file['local']) ? filesize($file['local']) : 0;
                echo "<li>{$file['remote']} ($size bytes)</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>This means either:</p>";
            echo "<ul>";
            echo "<li>No participants in this event have photos</li>";
            echo "<li>Photo files are not found in expected locations</li>";
            echo "<li>There's an issue with the photo copy function</li>";
            echo "</ul>";
            echo "</div>";
        }
        
        // Clean up
        if (is_dir($test_dir)) {
            $files = glob($test_dir . '/*');
            foreach ($files as $file) {
                if (is_file($file)) {
                    unlink($file);
                }
            }
            $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);
        }
        
    } else {
        echo "<div style='background: #f8d7da; padding: 15px; border: 1px solid #f5c6cb; border-radius: 5px;'>";
        echo "<h4>🔴 No events found</h4>";
        echo "<p>Create an event first to test photo uploading.</p>";
        echo "</div>";
    }
    
} catch (Exception $e) {
    echo "<div style='background: #f8d7da; padding: 15px; border: 1px solid #f5c6cb; border-radius: 5px;'>";
    echo "<h4>🔴 Error testing photo copy</h4>";
    echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>";
    echo "</div>";
}

echo "<h2>Quick Fixes & Next Steps</h2>";

echo "<div style='background: #e7f3ff; padding: 15px; border: 1px solid #bee5eb; border-radius: 5px;'>";
echo "<h3>💡 Recommended Actions</h3>";

echo "<h4>1. If no participants have photos:</h4>";
echo "<ul>";
echo "<li>Go to StyleScore admin → Participants</li>";
echo "<li>Upload photos for participants</li>";
echo "<li>Make sure photos are saved in the participants table</li>";
echo "</ul>";

echo "<h4>2. If photos exist but aren't found:</h4>";
echo "<ul>";
echo "<li>Check if photos are in <code>v2/uploads/</code> directory</li>";
echo "<li>Verify file permissions (should be readable by web server)</li>";
echo "<li>Check if photo filenames in database match actual files</li>";
echo "</ul>";

echo "<h4>3. If photos are copied but not uploaded:</h4>";
echo "<ul>";
echo "<li>Check FTP connection settings in publish servers</li>";
echo "<li>Verify FTP credentials and permissions</li>";
echo "<li>Check the publish server logs for upload errors</li>";
echo "</ul>";

echo "<h4>4. Test the complete publish process:</h4>";
echo "<ul>";
echo "<li><a href='publish_servers.php'>Go to Publish Servers</a></li>";
echo "<li>Try publishing HTML files (should include photos)</li>";
echo "<li>Check the remote server to see if photos directory was created</li>";
echo "</ul>";
echo "</div>";

echo "<p><strong>Debug logs:</strong> Check your PHP error log for detailed photo copy debugging information.</p>";
?>
