<?php
/**
 * File Permissions Fixer for cPanel
 * 
 * Sets directory permissions to 0755 and file permissions to 0644.
 * Instructions:
 * 1. Upload this file to your public_html or website directory (e.g., walterstoursafaris.co.tz/site/).
 * 2. Visit https://walterstoursafaris.co.tz/site/fix-permissions.php in your browser.
 * 3. Delete this file immediately for security!
 */
header('Content-Type: text/plain; charset=utf-8');
echo "Starting permission fix...\n";

$target = __DIR__;

function fixPermissions($path) {
    if (!file_exists($path)) {
        return;
    }

    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );

    $fixed_dirs = 0;
    $fixed_files = 0;
    $failed_dirs = 0;
    $failed_files = 0;

    foreach ($iterator as $item) {
        $itemPath = $item->getPathname();
        
        // Skip hidden git folders or cpanel_build directories if present
        if (strpos($itemPath, '/.git') !== false || strpos($itemPath, '/cpanel_build') !== false) {
            continue;
        }

        if ($item->isDir()) {
            if (@chmod($itemPath, 0755)) {
                $fixed_dirs++;
            } else {
                $failed_dirs++;
            }
        } else {
            // Do not restrict this script itself while running
            if (basename($itemPath) === basename(__FILE__)) {
                continue;
            }
            if (@chmod($itemPath, 0644)) {
                $fixed_files++;
            } else {
                $failed_files++;
            }
        }
    }

    // Also fix the target directory itself
    @chmod($path, 0755);

    echo "Completed!\n";
    echo "Directories fixed: $fixed_dirs (failed: $failed_dirs)\n";
    echo "Files fixed: $fixed_files (failed: $failed_files)\n";
}

fixPermissions($target);
?>
