<?php
/**
 * Fix All Issues Script
 * Run this to fix permissions and database issues
 */

echo "<h1>🔧 Fixing All Issues</h1>";

// Fix 1: Log file permissions
echo "<h2>1. Fixing Log File Permissions</h2>";

$log_dir = dirname(__DIR__) . '/logs';
$app_log = $log_dir . '/app.log';
$audit_log = $log_dir . '/audit.log';

// Create logs directory
if (!is_dir($log_dir)) {
    mkdir($log_dir, 0777, true);
    echo "✓ Created logs directory<br>";
}

// Create log files
if (!file_exists($app_log)) {
    file_put_contents($app_log, '');
    echo "✓ Created app.log<br>";
}
if (!file_exists($audit_log)) {
    file_put_contents($audit_log, '');
    echo "✓ Created audit.log<br>";
}

// Set permissions
chmod($log_dir, 0777);
chmod($app_log, 0666);
chmod($audit_log, 0666);

echo "✓ Set permissions to 777 for directory, 666 for files<br>";

// Try to set ownership (may not work on all systems)
if (function_exists('posix_getpwuid')) {
    $www_user = posix_getpwuid(posix_getuid());
    echo "Current user: " . $www_user['name'] . "<br>";
}

echo "<p style='color: green;'>✅ Log files fixed</p>";

// Fix 2: Test database connection
echo "<h2>2. Testing Database Connection</h2>";

try {
    require_once dirname(__DIR__) . '/config/database.php';
    $pdo = get_db_connection();
    echo "✓ Database connected successfully<br>";
    
    // Test a simple query
    $result = $pdo->query("SELECT 1")->fetch();
    echo "✓ Test query executed<br>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>❌ Database error: " . $e->getMessage() . "</p>";
}

// Fix 3: Test login function
echo "<h2>3. Testing Login Function</h2>";

try {
    require_once dirname(__DIR__) . '/config/auth.php';
    
    $test_user = 'admin';
    $test_pass = 'Admin@123';
    
    $user = db_fetch_one("SELECT * FROM users WHERE username = ?", [$test_user]);
    
    if ($user) {
        echo "✓ User found: " . $user['username'] . "<br>";
        
        if (password_verify($test_pass, $user['password_hash'])) {
            echo "✓ Password correct<br>";
            
            // Test the update function directly
            $update_result = db_update('users', 
                ['last_login' => date('Y-m-d H:i:s')], 
                'user_id = :user_id', 
                ['user_id' => $user['user_id']]
            );
            
            if ($update_result !== false) {
                echo "✓ Update function works<br>";
            } else {
                echo "❌ Update function failed<br>";
            }
            
        } else {
            echo "❌ Password incorrect<br>";
        }
    } else {
        echo "❌ User not found<br>";
    }
    
} catch (Exception $e) {
    echo "<p style='color: red;'>❌ Login test error: " . $e->getMessage() . "</p>";
    echo "<pre>" . $e->getTraceAsString() . "</pre>";
}

// Fix 4: Alternative simple update test
echo "<h2>4. Testing Simple Update</h2>";

try {
    $pdo = get_db_connection();
    
    // Get a user ID
    $user_id = $pdo->query("SELECT user_id FROM users WHERE username = 'admin'")->fetchColumn();
    
    if ($user_id) {
        // Try a simple update with positional parameters
        $stmt = $pdo->prepare("UPDATE users SET last_login = ? WHERE user_id = ?");
        $result = $stmt->execute([date('Y-m-d H:i:s'), $user_id]);
        
        if ($result) {
            echo "✓ Simple positional update works<br>";
        } else {
            echo "❌ Simple positional update failed<br>";
        }
        
        // Try with named parameters
        $stmt = $pdo->prepare("UPDATE users SET last_login = :last_login WHERE user_id = :user_id");
        $result = $stmt->execute(['last_login' => date('Y-m-d H:i:s'), 'user_id' => $user_id]);
        
        if ($result) {
            echo "✓ Named parameter update works<br>";
        } else {
            echo "❌ Named parameter update failed<br>";
        }
        
    } else {
        echo "❌ Could not find admin user<br>";
    }
    
} catch (Exception $e) {
    echo "<p style='color: red;'>❌ Simple update error: " . $e->getMessage() . "</p>";
}

echo "<hr>";
echo "<h3 style='color: green;'>✅ Fixes applied! Try logging in now:</h3>";
echo "<p><a href='login.php' style='display: inline-block; padding: 10px 20px; background: #28a745; color: white; text-decoration: none; border-radius: 5px;'>Go to Login Page</a></p>";