<?php
require_once __DIR__ . '/includes/config.php';

echo "<h2>Diagnostică Upload</h2>";

// Check login
if (!isLoggedIn()) {
    echo "<p style='color:red'>❌ Nu ești logat</p>";
    exit;
}

$user = getCurrentUser();
echo "<p>User: " . htmlspecialchars($user['name']) . " | Role: " . $user['role'] . "</p>";

if ($user['role'] !== 'admin') {
    echo "<p style='color:red'>❌ Nu ești admin</p>";
    exit;
}

// Check UPLOAD_DIR
echo "<h3>Folder Upload</h3>";
echo "<p><strong>UPLOAD_DIR:</strong> " . UPLOAD_DIR . "</p>";

if (is_dir(UPLOAD_DIR)) {
    echo "<p style='color:green'>✓ Folderul există</p>";
} else {
    echo "<p style='color:red'>❌ Folderul NU există</p>";
    if (mkdir(UPLOAD_DIR, 0755, true)) {
        echo "<p style='color:green'>✓ Folderul a fost creat</p>";
    }
}

if (is_writable(UPLOAD_DIR)) {
    echo "<p style='color:green'>✓ Folderul are permisiuni de scriere</p>";
} else {
    echo "<p style='color:red'>❌ Folderul NU are permisiuni de scriere</p>";
    echo "<p>Permisiuni: " . substr(sprintf('%o', fileperms(UPLOAD_DIR)), -4) . "</p>";
}

// Check PHP upload settings
echo "<h3>Setări PHP Upload</h3>";
echo "<ul>";
echo "<li><strong>upload_max_filesize:</strong> " . ini_get('upload_max_filesize') . "</li>";
echo "<li><strong>post_max_size:</strong> " . ini_get('post_max_size') . "</li>";
echo "<li><strong>max_file_uploads:</strong> " . ini_get('max_file_uploads') . "</li>";
echo "<li><strong>memory_limit:</strong> " . ini_get('memory_limit') . "</li>";
echo "</ul>";

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['test_file'])) {
    $file = $_FILES['test_file'];
    echo "<p><strong>File info:</strong></p>";
    echo "<ul>";
    echo "<li>Name: " . htmlspecialchars($file['name']) . "</li>";
    echo "<li>Type: " . htmlspecialchars($file['type']) . "</li>";
    echo "<li>Size: " . $file['size'] . " bytes</li>";
    echo "<li>Error: " . $file['error'] . "</li>";
    echo "<li>Tmp: " . htmlspecialchars($file['tmp_name']) . "</li>";
    echo "</ul>";
    
    if ($file['error'] === UPLOAD_ERR_OK) {
        $test_path = UPLOAD_DIR . 'test_' . time() . '.jpg';
        if (move_uploaded_file($file['tmp_name'], $test_path)) {
            echo "<p style='color:green'>✓ Test upload reușit!</p>";
            unlink($test_path);
        } else {
            echo "<p style='color:red'>❌ Test upload eșuat - nu se poate muta fișierul</p>";
        }
    } else {
        echo "<p style='color:red'>❌ Eroare upload: " . $file['error'] . "</p>";
    }
}

echo "<hr>";
echo "<a href='admin/products.php'>← Înapoi</a>";
?>
