<?php
/**
 * Direct test of photo download - bypasses Auth
 * Delete this file after testing!
 */
error_reporting(E_ALL);

// Test with one of the working URLs from debug output
$testUrl = $_GET['url'] ?? 'https://live.staticflickr.com/65535/54995003092_7cfd04e2ba_b.jpg';

echo "<h2>Testing Download: $testUrl</h2>";

// Fetch the image
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $testUrl,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_MAXREDIRS => 5,
    CURLOPT_TIMEOUT => 60,
    CURLOPT_CONNECTTIMEOUT => 15,
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_HTTPHEADER => [
        'Accept: image/*, */*',
        'Referer: https://www.flickr.com/',
    ],
]);

$content = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$error = curl_error($ch);
curl_close($ch);

echo "<p>HTTP Status: <b>$httpCode</b></p>";
echo "<p>Content-Type: <b>$contentType</b></p>";
echo "<p>Content Size: <b>" . strlen($content) . "</b> bytes</p>";

if ($error) {
    echo "<p style='color:red'>cURL Error: $error</p>";
}

// Check magic bytes
$magicBytes = substr($content, 0, 16);
echo "<p>First 16 bytes (hex): <code>" . bin2hex($magicBytes) . "</code></p>";

$isJpeg = (substr($content, 0, 2) === "\xFF\xD8");
$isPng = (substr($content, 0, 4) === "\x89PNG");

echo "<p>Is JPEG: <b>" . ($isJpeg ? 'YES' : 'NO') . "</b></p>";
echo "<p>Is PNG: <b>" . ($isPng ? 'YES' : 'NO') . "</b></p>";

if ($httpCode === 200 && ($isJpeg || $isPng)) {
    echo "<h3 style='color:green'>✓ Image fetched successfully!</h3>";

    // Save test file
    $testFile = sys_get_temp_dir() . '/flickr_test_' . time() . '.jpg';
    file_put_contents($testFile, $content);

    // Verify with getimagesize
    $imgInfo = @getimagesize($testFile);
    if ($imgInfo) {
        echo "<p>Image verified: <b>{$imgInfo[0]}x{$imgInfo[1]}</b> - {$imgInfo['mime']}</p>";
        echo "<p>Test file saved to: $testFile</p>";
    } else {
        echo "<p style='color:red'>getimagesize() failed on saved file!</p>";
    }

    // Show preview
    echo "<h3>Preview (base64):</h3>";
    echo "<img src='data:image/jpeg;base64," . base64_encode($content) . "' style='max-width:500px'>";

    // Download link
    echo "<h3>Test Download:</h3>";
    echo "<p><a href='?action=download&url=" . urlencode($testUrl) . "'>Click to test download</a></p>";

    @unlink($testFile);
} else {
    echo "<h3 style='color:red'>✗ Failed to fetch valid image</h3>";
    if (strlen($content) < 500) {
        echo "<p>Response content:</p><pre>" . htmlspecialchars($content) . "</pre>";
    }
}

// Handle download action
if (($_GET['action'] ?? '') === 'download') {
    $url = $_GET['url'] ?? '';
    if (!$url) die('No URL');

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_USERAGENT => 'Mozilla/5.0',
        CURLOPT_HTTPHEADER => ['Accept: image/*', 'Referer: https://www.flickr.com/'],
    ]);
    $content = curl_exec($ch);
    curl_close($ch);

    // Clear ALL output
    while (ob_get_level()) ob_end_clean();

    header('Content-Type: image/jpeg');
    header('Content-Length: ' . strlen($content));
    header('Content-Disposition: attachment; filename="test_photo.jpg"');
    echo $content;
    exit;
}
