<?php
/**
 * Recursive Permissions Fixer
 * Sets 755 for directories and 644 for files.
 * Note: On Windows, chmod() has limited effect (mostly toggling Read-Only).
 */
require_once __DIR__ . '/../../app/core/bootstrap.php';
auth_require_login();
$pdo = crm_pdo();

if (!gp_can_manage_project_access($pdo)) {
    die("Access denied.");
}

$root = realpath(__DIR__ . '/../../');
echo "<h1>Recursive Permissions Fixer</h1>";
echo "Root: $root <br><pre>";

$it = new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST);

$countDirs = 0;
$countFiles = 0;

foreach ($files as $file) {
    $path = $file->getRealPath();
    
    // Skip the vendor directory if it exists to save time/prevent issues
    if (strpos($path, DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR) !== false) continue;
    if (strpos($path, DIRECTORY_SEPARATOR . '.git' . DIRECTORY_SEPARATOR) !== false) continue;

    if ($file->isDir()) {
        if (@chmod($path, 0755)) {
            $countDirs++;
        }
    } else {
        if (@chmod($path, 0644)) {
            $countFiles++;
        }
    }
}

echo "Finished.\n";
echo "Directories updated (755): $countDirs\n";
echo "Files updated (644): $countFiles\n";
echo "</pre>";
?>
