<?php
/**
 * GoPools Upload Diagnostics
 * Run ONCE on server to diagnose upload issues, then DELETE.
 */
$root = dirname(__DIR__, 1); // public/
$uploadBase = $root . '/uploads';

$dirs = [
    'project_photos',
    'job_photos',
    'project_offers',
    'photos',
    'missing_parts',
    'avatars',
    'inbox',
];

echo "<!DOCTYPE html><html><head><meta charset='utf-8'><title>Upload Diagnostics</title>";
echo "<style>body{font-family:monospace;background:#0f1117;color:#e2e8f0;padding:24px;font-size:13px;}
.ok{color:#10b981;}.fail{color:#ef4444;}.warn{color:#f59e0b;}
h2{color:#fff;margin:16px 0 6px;border-bottom:1px solid #334;padding-bottom:4px;}
pre{background:#1e2433;padding:12px;border-radius:8px;overflow:auto;}
</style></head><body>";

echo "<h1 style='color:#fff'>🔍 GoPools Upload Diagnostics</h1>";
echo "<p style='color:#64748b'>Server: " . $_SERVER['SERVER_SOFTWARE'] . " | PHP " . PHP_VERSION . " | " . date('d/m/Y H:i') . "</p>";

// ── 1. PHP upload settings ──────────────────────────────────────────────────
echo "<h2>📋 PHP Upload Settings</h2><pre>";
$settings = ['file_uploads','upload_max_filesize','post_max_size','max_file_uploads','upload_tmp_dir'];
foreach ($settings as $s) {
    $v = ini_get($s);
    $ok = ($s === 'file_uploads') ? ($v == '1') : (!empty($v));
    $cls = $ok ? 'ok' : 'fail';
    echo "<span class='$cls'>$s = $v</span>\n";
}
echo "</pre>";

// ── 2. Upload directory checks ──────────────────────────────────────────────
echo "<h2>📁 Upload Directories</h2><pre>";
echo "Base path: $uploadBase\n";
echo "Base exists: " . (is_dir($uploadBase) ? "<span class='ok'>YES</span>" : "<span class='fail'>NO</span>") . "\n";
echo "Base writable: " . (is_writable($uploadBase) ? "<span class='ok'>YES</span>" : "<span class='fail'>NO — run chmod 755</span>") . "\n\n";

foreach ($dirs as $d) {
    $path = $uploadBase . '/' . $d;
    $exists = is_dir($path);
    $writable = $exists && is_writable($path);

    if (!$exists) {
        $made = @mkdir($path, 0755, true);
        echo "<span class='" . ($made ? 'ok' : 'fail') . "'>";
        echo ($made ? "✅ CREATED: " : "❌ FAILED TO CREATE: ") . $path;
        echo "</span>\n";
    } else {
        echo "<span class='" . ($writable ? 'ok' : 'fail') . "'>";
        echo ($writable ? "✅ OK:  " : "❌ NOT WRITABLE: ") . $path;
        echo " [" . substr(sprintf('%o', fileperms($path)), -4) . "]";
        echo "</span>\n";
    }
}
echo "</pre>";

// ── 3. Write test ───────────────────────────────────────────────────────────
echo "<h2>✏️ Write Test</h2><pre>";
$testFile = $uploadBase . '/project_photos/_test_' . time() . '.txt';
$written = @file_put_contents($testFile, 'test');
if ($written !== false) {
    @unlink($testFile);
    echo "<span class='ok'>✅ Can write to project_photos/ — upload should work</span>\n";
} else {
    echo "<span class='fail'>❌ Cannot write to project_photos/ — check permissions</span>\n";
    echo "Run on server via SSH:\n";
    echo "  chmod -R 755 " . $uploadBase . "\n";
    echo "  chown -R nobody:nobody " . $uploadBase . "  (or your cPanel user)\n";
}
echo "</pre>";

// ── 4. URL detection ────────────────────────────────────────────────────────
echo "<h2>🌐 URL Detection</h2><pre>";
$scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
$pos = strpos($scriptName, '/public/');
$appBase = ($pos !== false) ? substr($scriptName, 0, $pos) : '';
$detectedUrl = rtrim($appBase, '/') . '/public/uploads/project_photos/example.jpg';
echo "SCRIPT_NAME: $scriptName\n";
echo "Detected app base: " . ($appBase ?: '(root)') . "\n";
echo "<span class='ok'>Upload URL will be: $detectedUrl</span>\n";
echo "</pre>";

// ── 5. .htaccess check ──────────────────────────────────────────────────────
echo "<h2>⚙️ .htaccess</h2><pre>";
$htDir  = $uploadBase . '/.htaccess';
$htPub  = $root . '/.htaccess';
echo ".htaccess in uploads/: " . (file_exists($htDir) ? "<span class='warn'>EXISTS — check it doesn't block files</span>" : "<span class='ok'>Not present (OK)</span>") . "\n";
echo ".htaccess in public/: "  . (file_exists($htPub)  ? "<span class='ok'>EXISTS</span>" : "<span class='warn'>Missing</span>") . "\n";
if (file_exists($htPub)) {
    $ht = file_get_contents($htPub);
    echo "\nContent:\n" . htmlspecialchars(substr($ht, 0, 600)) . "\n";
}
echo "</pre>";

echo "<div style='margin-top:24px;padding:16px;background:rgba(16,185,129,.1);border:1px solid #10b981;border-radius:8px;color:#10b981;font-weight:700'>
✅ Diagnostics complete. DELETE this file after use: public/api/diag_upload.php
</div></body></html>";
