<?php
echo "<h1>🔧 Fix Directory Permissions</h1>";
echo "<style>body{font-family:Arial,sans-serif;margin:20px;} .success{color:green;font-weight:bold;} .error{color:red;font-weight:bold;} .info{color:blue;}</style>";

$dirs = [
    '../storage',
    '../storage/logs',
    '../storage/framework',
    '../storage/framework/cache',
    '../storage/framework/sessions',
    '../storage/framework/views',
    '../bootstrap/cache'
];

echo "<h2>Checking and Fixing Permissions</h2>";

foreach ($dirs as $dir) {
    echo "<h3>$dir</h3>";

    if (!is_dir($dir)) {
        echo "<p class='error'>Directory does not exist, creating...</p>";
        if (mkdir($dir, 0755, true)) {
            echo "<p class='success'>✅ Directory created</p>";
        } else {
            echo "<p class='error'>❌ Failed to create directory</p>";
            continue;
        }
    }

    $currentPerms = substr(sprintf('%o', fileperms($dir)), -4);
    echo "<p>Current permissions: $currentPerms</p>";

    if (is_writable($dir)) {
        echo "<p class='success'>✅ Directory is writable</p>";
    } else {
        echo "<p class='error'>❌ Directory is NOT writable, attempting to fix...</p>";

        // Try to change permissions
        if (chmod($dir, 0755)) {
            echo "<p class='success'>✅ Permissions changed to 0755</p>";
        } else {
            echo "<p class='error'>❌ Failed to change permissions</p>";
            echo "<p class='info'>Manual fix required: Right-click folder → Properties → Security → Give write permissions</p>";
        }
    }
}

echo "<h2>Creating Test Files</h2>";
$testFiles = [
    '../storage/logs/laravel.log' => 'Test log entry',
    '../storage/framework/cache/.gitkeep' => '',
    '../storage/framework/sessions/.gitkeep' => '',
    '../storage/framework/views/.gitkeep' => '',
    '../bootstrap/cache/.gitkeep' => ''
];

foreach ($testFiles as $file => $content) {
    $dir = dirname($file);
    if (is_writable($dir)) {
        if (file_put_contents($file, $content)) {
            echo "<p class='success'>✅ Created $file</p>";
        } else {
            echo "<p class='error'>❌ Failed to create $file</p>";
        }
    } else {
        echo "<p class='warning'>⚠️ Skipping $file (directory not writable)</p>";
    }
}

echo "<h2>Final Status</h2>";
echo "<p class='info'>Permissions fix completed. Try accessing your Laravel application again.</p>";
echo "<p><a href='debug_500.php'>← Back to Debug Page</a></p>";
?>
