<?php
/**
 * Fix Log File Permissions
 * Run this to set correct permissions on log files
 */

echo "<h1>Fixing Log File Permissions</h1>";

// Define paths
$log_dir = __DIR__ . '/logs';
$log_files = [
    $log_dir . '/app.log',
    $log_dir . '/audit.log'
];

// Create logs directory if it doesn't exist
if (!file_exists($log_dir)) {
    echo "<p>Creating logs directory...</p>";
    mkdir($log_dir, 0777, true);
    echo "<p style='color: green;'>✓ Logs directory created</p>";
}

// Set permissions on directory
echo "<p>Setting permissions on logs directory...</p>";
chmod($log_dir, 0777);
echo "<p style='color: green;'>✓ Logs directory permissions set to 777</p>";

// Create and set permissions on log files
foreach ($log_files as $file) {
    if (!file_exists($file)) {
        echo "<p>Creating $file...</p>";
        file_put_contents($file, "[" . date('Y-m-d H:i:s') . "] Log file created\n");
    }
    
    echo "<p>Setting permissions on " . basename($file) . "...</p>";
    chmod($file, 0666);
    echo "<p style='color: green;'>✓ " . basename($file) . " permissions set to 666</p>";
}

// Test write permissions
echo "<h2>Testing Write Permissions</h2>";

foreach ($log_files as $file) {
    $test_message = "[" . date('Y-m-d H:i:s') . "] [TEST] Write test\n";
    $result = file_put_contents($file, $test_message, FILE_APPEND);
    
    if ($result !== false) {
        echo "<p style='color: green;'>✓ Can write to " . basename($file) . "</p>";
    } else {
        echo "<p style='color: red;'>✗ Cannot write to " . basename($file) . "</p>";
    }
}

echo "<h2>Current User Information</h2>";
echo "<ul>";
echo "<li><strong>Script owner:</strong> " . function_exists('posix_getpwuid') ? posix_getpwuid(fileowner(__FILE__))['name'] : 'N/A' . "</li>";
echo "<li><strong>Web server user:</strong> " . get_current_user() . "</li>";
echo "<li><strong>PHP user:</strong> " . (function_exists('posix_geteuid') ? posix_getpwuid(posix_geteuid())['name'] : 'N/A') . "</li>";
echo "</ul>";