<?php
/**
 * Fix File Permissions Script
 * Run this once after extracting zip files to fix permissions
 * Access: yourdomain.com/fix_permissions.php
 */

// Security: Change this password before running
define('ADMIN_PASSWORD', 'your_secure_password_here');

// Check password
if (!isset($_GET['password']) || $_GET['password'] !== ADMIN_PASSWORD) {
    die('Access denied. Add ?password=your_secure_password_here to URL');
}

echo "<h2>Fixing File Permissions...</h2>";
echo "<pre>";

$rootPath = __DIR__;
$errors = [];
$success = [];

/**
 * Recursively fix permissions
 */
function fixPermissions($dir, &$success, &$errors) {
    $items = scandir($dir);
    
    foreach ($items as $item) {
        if ($item == '.' || $item == '..') continue;
        
        $path = $dir . DIRECTORY_SEPARATOR . $item;
        
        if (is_dir($path)) {
            // Set directory permissions to 755
            if (@chmod($path, 0755)) {
                $success[] = "DIR: $path → 755";
            } else {
                $errors[] = "Failed to chmod DIR: $path";
            }
            
            // Recursively fix subdirectories
            fixPermissions($path, $success, $errors);
            
        } else {
            // Set file permissions to 644
            if (@chmod($path, 0644)) {
                $success[] = "FILE: $path → 644";
            } else {
                $errors[] = "Failed to chmod FILE: $path";
            }
        }
    }
}

// Start fixing
echo "Starting permission fix...\n\n";
fixPermissions($rootPath, $success, $errors);

// Show results
echo "\n=== RESULTS ===\n";
echo "Success: " . count($success) . " items\n";
echo "Errors: " . count($errors) . " items\n\n";

if (!empty($errors)) {
    echo "\n=== ERRORS ===\n";
    foreach ($errors as $error) {
        echo $error . "\n";
    }
}

echo "\n=== DONE ===\n";
echo "File permissions have been fixed!\n";
echo "You can now delete this file for security.\n";

echo "</pre>";

// Show delete button
echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '?password=' . ADMIN_PASSWORD . '&delete=1">';
echo '<button type="submit" style="padding:10px 20px; background:red; color:white; border:none; cursor:pointer;">Delete This Script</button>';
echo '</form>';

// Handle self-delete
if (isset($_GET['delete']) && $_GET['delete'] == '1') {
    if (@unlink(__FILE__)) {
        die('Script deleted successfully!');
    } else {
        die('Could not delete script. Please delete manually: ' . __FILE__);
    }
}
?>
