<?php
echo "<h2>Upload Diagnostic</h2>";
echo "<b>Current User:</b> " . get_current_user() . "<br>";
echo "<b>Upload Max Filesize:</b> " . ini_get('upload_max_filesize') . "<br>";
echo "<b>Post Max Size:</b> " . ini_get('post_max_size') . "<br>";
echo "<b>File Uploads Enabled:</b> " . ini_get('file_uploads') . "<br>";

$dir = __DIR__ . '/uploads/templates';
echo "<b>Target Directory:</b> $dir<br>";

if (!file_exists($dir)) {
    echo "Directory does not exist. Attempting to create... ";
    if (mkdir($dir, 0777, true)) {
        echo "Created!<br>";
    } else {
        echo "<span style='color:red'>Failed to create! Check permissions.</span><br>";
    }
} else {
    echo "Directory exists.<br>";
}

if (is_writable($dir)) {
    echo "<span style='color:green'>Directory is writable.</span><br>";
} else {
    echo "<span style='color:red'>Directory is NOT writable.</span><br>";
}

echo "<h3>Test Upload</h3>";
echo '<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="test_file">
<button type="submit">Test Upload</button>
</form>';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['test_file'])) {
    echo "<pre>";
    print_r($_FILES['test_file']);
    echo "</pre>";

    $target = $dir . '/test_' . basename($_FILES['test_file']['name']);
    if (move_uploaded_file($_FILES['test_file']['tmp_name'], $target)) {
        echo "<h3 style='color:green'>Upload Successful! File saved to: $target</h3>";
        unlink($target); // Cleanup
    } else {
        echo "<h3 style='color:red'>Upload Failed!</h3>";
        $error = error_get_last();
        if ($error) print_r($error);
    }
}
?>
