<?php
/**
 * Script to fix and verify directory permissions for GoPools CRM.
 * Run this from your browser: http://localhost/gopools/public/api/fix_permissions.php
 */
require_once __DIR__ . '/../../app/core/bootstrap.php';
auth_require_login();
$pdo = crm_pdo();

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

$dirs = [
    __DIR__ . '/../uploads',
    __DIR__ . '/../uploads/photos',
    __DIR__ . '/../uploads/project_offers',
    __DIR__ . '/../uploads/receipts',
    __DIR__ . '/../uploads/signatures',
];

echo "<h1>GoPools Permissions Fixer</h1>";
echo "<pre>";

foreach ($dirs as $dir) {
    echo "Checking: $dir ... ";
    if (!file_exists($dir)) {
        if (mkdir($dir, 0777, true)) {
            echo "CREATED SUCCESS\n";
        } else {
            echo "FAILED TO CREATE\n";
        }
    } else {
        if (is_writable($dir)) {
            echo "WRITABLE ✅\n";
        } else {
            // Attempt chmod (mostly effective on Linux, but safe to try)
            if (@chmod($dir, 0777)) {
                echo "CHMOD 777 SUCCESS\n";
            } else {
                echo "NOT WRITABLE ❌ (Check Windows Folder Properties)\n";
            }
        }
    }
}

echo "\n--- System Checks ---\n";
echo "PHP User: " . get_current_user() . "\n";
echo "Upload Max Size: " . ini_get('upload_max_filesize') . "\n";
echo "Post Max Size: " . ini_get('post_max_size') . "\n";
echo "--- Done ---\n";
echo "</pre>";
