<?php
/**
 * Debug Upload Script - Test Single & Bulk Uploads
 * Access via: http://localhost/gostudios/debug_upload.php
 */

echo "<h1>📁 Upload Debug - Single & Bulk Upload Test</h1>";

// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo "<h2>📨 POST Data:</h2>";
    echo "<pre>";
    print_r($_POST);
    echo "</pre>";
    
    echo "<h2>📄 FILES Data:</h2>";
    echo "<pre>";
    print_r($_FILES);
    echo "</pre>";
    
    // Test Python service connection
    echo "<h2>🐍 Python Service Test:</h2>";
    test_python_service();
    
    // Test actual upload to Python service
    if (isset($_FILES['files']) || isset($_FILES['file'])) {
        echo "<h2>🚀 Testing Python Service Upload:</h2>";
        test_python_upload();
    }
    
    exit;
}

function test_python_service() {
    $url = 'http://127.0.0.1:5000/health';
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 5,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($http_code === 200) {
        echo "<div style='color: green; padding: 10px; background: #d4edda; border-radius: 5px;'>✅ Python Service is RUNNING</div>";
        echo "<pre>Response: " . htmlspecialchars($response) . "</pre>";
    } else {
        echo "<div style='color: red; padding: 10px; background: #f8d7da; border-radius: 5px;'>❌ Python Service is OFFLINE - HTTP $http_code</div>";
        echo "<div>Error: $error</div>";
    }
}

function test_python_upload() {
    echo "<h3>Testing Direct Python Service Upload...</h3>";
    
    // Test single file upload
    if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
        echo "<h4>🔍 Testing Single File Upload:</h4>";
        test_single_upload($_FILES['file']);
    }
    
    // Test bulk file upload
    if (isset($_FILES['files']) && is_array($_FILES['files']['name'])) {
        echo "<h4>🔍 Testing Bulk File Upload:</h4>";
        test_bulk_upload($_FILES['files']);
    }
}

function test_single_upload($file) {
    $post_data = [
        'file' => new CURLFile($file['tmp_name'], $file['type'], $file['name'])
    ];
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => 'http://127.0.0.1:5000/process-single-pdf',
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $post_data,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
    ]);
    
    echo "<div style='background: #f8f9fa; padding: 15px; border-radius: 5px;'>";
    echo "<strong>Single Upload to:</strong> http://127.0.0.1:5000/process-single-pdf<br>";
    echo "<strong>File:</strong> {$file['name']} ({$file['size']} bytes)<br>";
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($http_code === 200) {
        echo "<div style='color: green; margin-top: 10px;'>✅ SINGLE UPLOAD SUCCESS - HTTP $http_code</div>";
        echo "<pre>Response: " . htmlspecialchars($response) . "</pre>";
    } else {
        echo "<div style='color: red; margin-top: 10px;'>❌ SINGLE UPLOAD FAILED - HTTP $http_code</div>";
        echo "<div>Error: $error</div>";
        echo "<pre>Response: " . htmlspecialchars($response) . "</pre>";
    }
    echo "</div>";
}

function test_bulk_upload($files) {
    $post_data = [];
    $valid_files = 0;
    
    echo "<div style='background: #f8f9fa; padding: 15px; border-radius: 5px;'>";
    echo "<strong>Bulk Upload to:</strong> http://127.0.0.1:5000/process-batch-pdfs<br>";
    
    // Try different field name strategies
    $field_strategies = [
        'pdf_files' => 'pdf_files',  // Simple field name
        'files' => 'files',          // Standard field name
    ];
    
    foreach ($field_strategies as $field_name => $post_field) {
        echo "<h4>Testing field name: '{$field_name}'</h4>";
        
        $post_data = [];
        $valid_files = 0;
        
        foreach ($files['name'] as $index => $filename) {
            if ($files['error'][$index] === UPLOAD_ERR_OK && !empty($filename)) {
                $post_data["{$post_field}[{$index}]"] = new CURLFile(
                    $files['tmp_name'][$index], 
                    $files['type'][$index], 
                    $filename
                );
                $valid_files++;
            }
        }
        
        if ($valid_files === 0) {
            echo "<div style='color: orange;'>⚠️ No valid files for strategy '{$field_name}'</div>";
            continue;
        }
        
        echo "<strong>Valid files:</strong> $valid_files file(s)<br>";
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => 'http://127.0.0.1:5000/process-batch-pdfs',
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => $post_data,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ]);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($http_code === 200) {
            echo "<div style='color: green; margin-top: 10px;'>✅ SUCCESS with field '{$field_name}' - HTTP $http_code</div>";
            $result = json_decode($response, true);
            echo "<pre>Response: " . json_encode($result, JSON_PRETTY_PRINT) . "</pre>";
            echo "</div>";
            return; // Stop on first success
        } else {
            echo "<div style='color: red; margin-top: 10px;'>❌ FAILED with field '{$field_name}' - HTTP $http_code</div>";
            echo "<div>Error: $error</div>";
            echo "<pre>Response: " . htmlspecialchars($response) . "</pre>";
        }
    }
    
    echo "<div style='color: red; margin-top: 10px;'>❌ All field name strategies failed</div>";
    echo "</div>";
}

?>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 20px 0;">
    <div style="padding: 20px; background: #e8f4fd; border-radius: 8px;">
        <h3>📄 Single File Upload Test</h3>
        <form method="post" enctype="multipart/form-data">
            <div style="margin: 10px 0;">
                <input type="file" name="file" accept=".pdf" required 
                       style="padding: 8px; border: 2px dashed #007bff; border-radius: 4px; width: 100%;">
            </div>
            <button type="submit" style="padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">
                Test Single Upload
            </button>
        </form>
    </div>

    <div style="padding: 20px; background: #f0f8ff; border-radius: 8px;">
        <h3>📁 Bulk File Upload Test</h3>
        <form method="post" enctype="multipart/form-data">
            <div style="margin: 10px 0;">
                <input type="file" name="files[]" multiple accept=".pdf" required 
                       style="padding: 8px; border: 2px dashed #28a745; border-radius: 4px; width: 100%;">
            </div>
            <button type="submit" style="padding: 10px 20px; background: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer;">
                Test Bulk Upload
            </button>
        </form>
    </div>
</div>

<div style="margin-top: 30px; padding: 15px; background: #fff3cd; border-radius: 5px;">
    <h3>🔧 Instructions:</h3>
    <ol>
        <li><strong>Single Upload Test:</strong> Upload one PDF file using the left form</li>
        <li><strong>Bulk Upload Test:</strong> Upload multiple PDF files using the right form</li>
        <li><strong>Check Results:</strong> See the detailed response from Python service</li>
        <li><strong>Debug Info:</strong> All POST and FILES data will be displayed</li>
    </ol>
</div>

<div style="margin-top: 20px; padding: 15px; background: #d1ecf1; border-radius: 5px;">
    <h3>📊 Expected Results:</h3>
    <ul>
        <li>✅ Python Service: Should show "RUNNING"</li>
        <li>✅ Single Upload: Should return HTTP 200 with processing results</li>
        <li>✅ Bulk Upload: Should return HTTP 200 with batch processing results</li>
        <li>❌ If any fail: Detailed error messages will be shown</li>
    </ul>
</div>