<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h1>RxAero Portal - File Permission Fixer</h1>";

// Define files and expected permissions
$items = [
    ['path' => 'admin/chat.php', 'perms' => 0644, 'type' => 'file'],
    ['path' => 'employee/chat.php', 'perms' => 0644, 'type' => 'file'],
    ['path' => 'chat_api.php', 'perms' => 0644, 'type' => 'file'],
    ['path' => 'admin', 'perms' => 0755, 'type' => 'dir'],
    ['path' => 'employee', 'perms' => 0755, 'type' => 'dir'],
];

$success = true;

foreach ($items as $item) {
    $path = $item['path'];
    $perms = $item['perms'];
    $type = $item['type'];
    
    echo "<strong>Checking: $path</strong><br>";
    
    if (!file_exists($path)) {
        echo "❌ $path does not exist.<br><br>";
        $success = false;
        continue;
    }
    
    // Try to change permissions
    if (chmod($path, $perms)) {
        $current = substr(sprintf('%o', fileperms($path)), -4);
        echo "✅ Permissions changed to " . decoct($perms) . " (current: $current)<br><br>";
    } else {
        echo "⚠️ Failed to change permissions on $path. You may need to do it manually via cPanel.<br>";
        echo "   Recommended: $type should be " . decoct($perms) . "<br><br>";
        $success = false;
    }
}

if ($success) {
    echo "<h2 style='color:green;'>All permissions corrected successfully!</h2>";
    echo "<p>You should now be able to access:<br>";
    echo "<a href='admin/chat.php' target='_blank'>Admin Chat</a><br>";
    echo "<a href='employee/chat.php' target='_blank'>Employee Chat</a></p>";
} else {
    echo "<h2 style='color:orange;'>Some permissions could not be fixed automatically.</h2>";
    echo "<p>Please manually set the following using cPanel File Manager:<br>";
    echo "<strong>Files: 644 (rw-r--r--)</strong><br>";
    echo "<strong>Folders: 755 (rwxr-xr-x)</strong></p>";
    echo "<p>After manual fix, <a href='admin/chat.php'>click here to test admin chat</a></p>";
}

// Additional tip
echo "<hr><p><strong>If you still get 403 errors, check for .htaccess files in the admin/ or employee/ folders and rename them temporarily.</strong></p>";
?>