<?php
/**
 * Login Debug Script - Test session and login functionality
 */

// Start session manually
session_start();

echo "=== LOGIN DEBUG SCRIPT ===\n\n";

// Test 1: Check if sessions work
echo "1. Testing PHP Session:\n";
$_SESSION['test'] = 'Session works!';
if (isset($_SESSION['test'])) {
    echo "   ✓ Sessions are working\n";
    echo "   Session ID: " . session_id() . "\n";
    echo "   Session save path: " . session_save_path() . "\n";
} else {
    echo "   ✗ Sessions NOT working\n";
}

// Test 2: Check writable directory
echo "\n2. Checking writable/session directory:\n";
$sessionPath = __DIR__ . '/writable/session';
if (is_dir($sessionPath)) {
    echo "   ✓ Directory exists\n";
    if (is_writable($sessionPath)) {
        echo "   ✓ Directory is writable\n";
    } else {
        echo "   ✗ Directory is NOT writable\n";
        echo "   Run: chmod 777 writable/session\n";
    }
} else {
    echo "   ✗ Directory does NOT exist\n";
}

// Test 3: Check database connection and verify a user
echo "\n3. Testing database and password verification:\n";

// Load .env
if (file_exists(__DIR__ . '/.env')) {
    $lines = file(__DIR__ . '/.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        if (strpos($line, '=') === false) continue;
        list($name, $value) = explode('=', $line, 2);
        putenv(trim($name) . '=' . trim($value));
    }
}

$host = getenv('database.default.hostname') ?: 'localhost';
$database = getenv('database.default.database') ?: 'flex_market';
$username = getenv('database.default.username') ?: 'root';
$password = getenv('database.default.password') ?: '';

$conn = new mysqli($host, $username, $password, $database);

if ($conn->connect_error) {
    die("   ✗ Database connection failed\n");
}
echo "   ✓ Database connected\n";

// Test login for superadmin
$email = 'superadmin@flex.com';
$testPassword = 'Super@123';

$stmt = $conn->prepare("SELECT id, name, email, password, role, user_type, is_verified FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

if ($user = $result->fetch_assoc()) {
    echo "   ✓ User found: {$user['name']}\n";
    echo "   - Role: {$user['role']}\n";
    echo "   - Verified: " . ($user['is_verified'] ? 'Yes' : 'No') . "\n";
    
    if (password_verify($testPassword, $user['password'])) {
        echo "   ✓ Password verification: PASS\n";
    } else {
        echo "   ✗ Password verification: FAIL\n";
    }
} else {
    echo "   ✗ User NOT found\n";
}

// Test 4: Check session configuration in CI4
echo "\n4. Checking CodeIgniter Session Config:\n";
$sessionConfigFile = __DIR__ . '/app/Config/Session.php';
if (file_exists($sessionConfigFile)) {
    echo "   ✓ Session.php config exists\n";
    
    $content = file_get_contents($sessionConfigFile);
    
    // Check driver
    if (preg_match("/public string \\\$driver = '([^']+)'/", $content, $matches)) {
        echo "   Driver: {$matches[1]}\n";
    }
    
    // Check save path
    if (preg_match("/public string \\\$savePath = ([^;]+);/", $content, $matches)) {
        echo "   Save Path: {$matches[1]}\n";
    }
} else {
    echo "   ✗ Session.php config NOT found\n";
}

// Test 5: Check CSRF token
echo "\n5. Checking CSRF Configuration:\n";
$securityConfigFile = __DIR__ . '/app/Config/Security.php';
if (file_exists($securityConfigFile)) {
    $content = file_get_contents($securityConfigFile);
    
    if (preg_match("/public string \\\$tokenName = '([^']+)'/", $content, $matches)) {
        echo "   CSRF Token Name: {$matches[1]}\n";
    }
    
    if (preg_match("/public bool \\\$regenerate = (true|false)/", $content, $matches)) {
        echo "   CSRF Regenerate: {$matches[1]}\n";
    }
}

echo "\n=== RECOMMENDATIONS ===\n";
echo "1. Clear your browser cache and cookies\n";
echo "2. Try in incognito/private window\n";
echo "3. Check browser console for errors (F12)\n";
echo "4. Check writable/logs for errors\n";
echo "5. Make sure writable/session has 777 permissions\n";

$conn->close();
