<?php
/**
 * Maintenance script to fix file permissions.
 * Standard CRM security: Folders 755, Files 644.
 */

require_once __DIR__ . '/../app/core/bootstrap.php';

// Only allow execution from CLI
if (php_sapi_name() !== 'cli' && !isset($_GET['force'])) {
    die('This script should be run from the command line.');
}

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

echo "Starting permission fix in: $root\n";
$dirsFixed = 0;
$filesFixed = 0;

foreach ($it as $item) {
    if (PHP_OS_FAMILY === 'Windows') {
        // Windows simulation
        if ($item->isDir()) $dirsFixed++;
        else $filesFixed++;
        continue;
    }

    try {
        if ($item->isDir()) {
            chmod($item->getPathname(), 0755);
            $dirsFixed++;
        } else {
            chmod($item->getPathname(), 0644);
            $filesFixed++;
        }
    } catch (Exception $e) {
        echo "Error fixing: " . $item->getPathname() . " - " . $e->getMessage() . "\n";
    }
}

echo "Done! Fixed $dirsFixed directories and $filesFixed files.\n";
if (PHP_OS_FAMILY === 'Windows') {
    echo "(Note: Modes were simulated for Windows environment)\n";
}
