<?php
/**
 * check_upload.php — Debug tool สำหรับตรวจสอบ PHP config บน hosting
 * ⚠️ ลบไฟล์นี้ออกหลังจากใช้งานเสร็จ!
 */

// Simple password protect
$pass = $_GET['key'] ?? '';
if ($pass !== 'shop39debug') {
    http_response_code(403);
    die('Forbidden. Use ?key=shop39debug');
}

$uploadDir = __DIR__ . '/public/uploads/products/';
$variantDir = __DIR__ . '/public/uploads/products/variants/';
$avatarDir = __DIR__ . '/public/uploads/avatars/';
$shopDir = __DIR__ . '/public/uploads/shops/';

function checkDir(string $path): array {
    return [
        'path'     => $path,
        'exists'   => is_dir($path),
        'writable' => is_writable($path),
        'perms'    => is_dir($path) ? substr(sprintf('%o', fileperms($path)), -4) : 'N/A',
    ];
}

header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html>
<head>
    <title>Upload Debug — Shop39</title>
    <style>
        body { font-family: monospace; padding: 20px; background: #1a1a2e; color: #eee; }
        h2 { color: #00d4ff; }
        table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
        th, td { border: 1px solid #444; padding: 8px 12px; text-align: left; }
        th { background: #0f3460; color: #fff; }
        .ok { color: #00ff88; }
        .fail { color: #ff4444; }
        .warn { color: #ffaa00; }
        pre { background: #0d0d1a; padding: 15px; border-radius: 8px; overflow-x: auto; }
    </style>
</head>
<body>
<h2>🔍 Shop39 Upload Debug Tool</h2>
<p style="color:#ff4444">⚠️ ลบไฟล์นี้ออกหลังใช้งาน!</p>

<h3>📁 Upload Directories</h3>
<table>
    <tr><th>Directory</th><th>Exists</th><th>Writable</th><th>Permissions</th></tr>
    <?php foreach ([
        $uploadDir, $variantDir, $avatarDir, $shopDir
    ] as $dir):
        $info = checkDir($dir);
    ?>
    <tr>
        <td><?= htmlspecialchars(str_replace(__DIR__, '.', $info['path'])) ?></td>
        <td class="<?= $info['exists'] ? 'ok' : 'fail' ?>"><?= $info['exists'] ? '✅ Yes' : '❌ No' ?></td>
        <td class="<?= $info['writable'] ? 'ok' : 'fail' ?>"><?= $info['writable'] ? '✅ Yes' : '❌ No' ?></td>
        <td><?= $info['perms'] ?></td>
    </tr>
    <?php endforeach; ?>
</table>

<h3>⚙️ PHP Configuration</h3>
<table>
    <tr><th>Setting</th><th>Value</th><th>Status</th></tr>
    <?php
    $checks = [
        'upload_max_filesize' => ['ini' => ini_get('upload_max_filesize'), 'need' => '10M+'],
        'post_max_size'       => ['ini' => ini_get('post_max_size'), 'need' => '12M+'],
        'max_file_uploads'    => ['ini' => ini_get('max_file_uploads'), 'need' => '15+'],
        'max_execution_time'  => ['ini' => ini_get('max_execution_time'), 'need' => '60+'],
        'memory_limit'        => ['ini' => ini_get('memory_limit'), 'need' => '64M+'],
        'PHP Version'         => ['ini' => PHP_VERSION, 'need' => '8.0+'],
        'GD Extension'        => ['ini' => extension_loaded('gd') ? 'enabled' : 'DISABLED', 'need' => 'enabled'],
        'session.save_path'   => ['ini' => ini_get('session.save_path'), 'need' => 'writable path'],
        'SITE_ROOT'           => ['ini' => defined('SITE_ROOT') ? SITE_ROOT : 'undefined', 'need' => 'absolute path'],
        'APP_URL'             => ['ini' => defined('APP_URL') ? APP_URL : 'undefined', 'need' => 'https://...'],
    ];
    foreach ($checks as $label => $data):
        $isOk = !empty($data['ini']);
    ?>
    <tr>
        <td><?= htmlspecialchars($label) ?></td>
        <td><?= htmlspecialchars($data['ini'] ?: 'empty') ?></td>
        <td class="<?= $isOk ? 'ok' : 'warn' ?>"><?= $isOk ? '✅' : '⚠️' ?> (need: <?= $data['need'] ?>)</td>
    </tr>
    <?php endforeach; ?>
</table>

<h3>🧪 Test mkdir()</h3>
<?php
$testDir = $uploadDir . 'test_' . time() . '/';
$created = @mkdir($testDir, 0755, true);
if ($created) {
    echo '<p class="ok">✅ mkdir() works — สร้างโฟลเดอร์ใหม่ได้</p>';
    @rmdir($testDir);
} else {
    echo '<p class="fail">❌ mkdir() ล้มเหลว — hosting อาจไม่ให้สิทธิ์ ต้องสร้างโฟลเดอร์ manually ผ่าน FileZilla แล้วตั้ง permission 755</p>';
}
?>

<h3>📄 PHP SAPI</h3>
<pre><?= php_sapi_name() . ' (ถ้าเป็น fpm-fcgi = PHP-FPM, .user.ini ต้องใช้แทน .htaccess php_value)' ?></pre>

<h3>📋 $_SERVER dump (relevant)</h3>
<pre><?php
$keys = ['SERVER_SOFTWARE','DOCUMENT_ROOT','SCRIPT_FILENAME','HTTP_HOST','SERVER_NAME','REQUEST_URI','SCRIPT_NAME'];
foreach ($keys as $k) {
    echo $k . ' = ' . htmlspecialchars($_SERVER[$k] ?? 'N/A') . "\n";
}
?></pre>

<hr>
<p style="color:#888">⚠️ <strong>ลบไฟล์ check_upload.php ออกจาก server ทันทีหลังใช้งาน</strong></p>
</body>
</html>
