<?php
/**
 * Login System Diagnostic Script
 * This script checks if all login components are working correctly
 */

// Set paths
define('FCPATH', __DIR__ . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR);
define('APPPATH', __DIR__ . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR);
define('WRITEPATH', __DIR__ . DIRECTORY_SEPARATOR . 'writable' . DIRECTORY_SEPARATOR);
define('ROOTPATH', __DIR__ . DIRECTORY_SEPARATOR);

// Load .env file if exists
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;
        list($name, $value) = explode('=', $line, 2);
        $name = trim($name);
        $value = trim($value);
        if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
            putenv(sprintf('%s=%s', $name, $value));
            $_ENV[$name] = $value;
            $_SERVER[$name] = $value;
        }
    }
}

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

echo "=== FLEX MARKET LOGIN DIAGNOSTIC ===\n\n";

// 1. Database connection
echo "1. Testing database connection...\n";
echo "   Host: {$host}\n";
echo "   Database: {$database}\n";
echo "   Username: {$username}\n";

if (empty($database)) {
    echo "   ✗ Database name not configured in .env file\n";
    echo "   Please set database.default.database in your .env file\n";
    exit(1);
}

try {
    $conn = new mysqli($host, $username, $password, $database);
    
    if ($conn->connect_error) {
        echo "   ✗ Connection failed: " . $conn->connect_error . "\n";
        exit(1);
    }
    
    echo "   ✓ Database connection successful\n";
} catch (Exception $e) {
    echo "   ✗ Connection failed: " . $e->getMessage() . "\n";
    exit(1);
}

// 2. Check if users table exists
echo "\n2. Checking users table...\n";
$result = $conn->query("SHOW TABLES LIKE 'users'");
if ($result && $result->num_rows > 0) {
    echo "   ✓ Users table exists\n";
    
    // Check table structure
    $columns = $conn->query("SHOW COLUMNS FROM users");
    $fieldNames = [];
    echo "   Columns: ";
    while ($col = $columns->fetch_assoc()) {
        $fieldNames[] = $col['Field'];
    }
    echo implode(', ', $fieldNames) . "\n";
    
    // Check for required columns
    $requiredColumns = ['id', 'name', 'email', 'password', 'user_type', 'role', 'is_verified'];
    $missingColumns = array_diff($requiredColumns, $fieldNames);
    
    if (empty($missingColumns)) {
        echo "   ✓ All required columns present\n";
    } else {
        echo "   ✗ Missing columns: " . implode(', ', $missingColumns) . "\n";
        echo "   Please run the create_dummy_users.sql script\n";
    }
} else {
    echo "   ✗ Users table does NOT exist\n";
    echo "   Please create the users table first\n";
    exit(1);
}

// 3. Check dummy users
echo "\n3. Checking dummy users...\n";
$dummyUsers = [
    'superadmin@flex.com' => ['role' => 'super_admin', 'password' => 'Super@123'],
    'admin@flex.com' => ['role' => 'admin', 'password' => 'Admin@123'],
    'seller@flex.com' => ['role' => 'seller', 'password' => 'Seller@123'],
    'delivery@flex.com' => ['role' => 'delivery', 'password' => 'Delivery@123'],
    'buyer@flex.com' => ['role' => 'buyer', 'password' => 'Buyer@123']
];

foreach ($dummyUsers as $email => $data) {
    $stmt = $conn->prepare("SELECT id, name, email, user_type, role, is_verified, password FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($user = $result->fetch_assoc()) {
        echo "   ✓ {$email} exists\n";
        echo "      - ID: {$user['id']}\n";
        echo "      - Name: {$user['name']}\n";
        echo "      - Role: " . ($user['role'] ?? 'NOT SET') . "\n";
        echo "      - User Type: " . ($user['user_type'] ?? 'NOT SET') . "\n";
        echo "      - Verified: " . ($user['is_verified'] ? 'Yes' : 'No') . "\n";
        echo "      - Password Set: " . (!empty($user['password']) ? 'Yes' : 'No') . "\n";
        
        // Test password verification
        if (!empty($user['password'])) {
            if (password_verify($data['password'], $user['password'])) {
                echo "      - Password Test: ✓ PASS (password '{$data['password']}' works)\n";
            } else {
                echo "      - Password Test: ✗ FAIL (password '{$data['password']}' doesn't match)\n";
                echo "      - Need to update password hash\n";
            }
        } else {
            echo "      - Password Test: ✗ FAIL (no password set)\n";
        }
    } else {
        echo "   ✗ {$email} NOT found\n";
        echo "      Please run create_dummy_users.sql to create this user\n";
    }
}

// 4. Check routes file
echo "\n4. Checking routes configuration...\n";
if (file_exists(APPPATH . 'Config/Routes.php')) {
    echo "   ✓ Routes.php exists\n";
    $routesContent = file_get_contents(APPPATH . 'Config/Routes.php');
    
    $requiredRoutes = [
        '/auth/login' => 'Auth login page',
        '/auth/process-password-login' => 'Password login processing',
        '/dashboard' => 'Dashboard redirect'
    ];
    
    foreach ($requiredRoutes as $route => $description) {
        if (strpos($routesContent, $route) !== false) {
            echo "   ✓ {$route} configured\n";
        } else {
            echo "   ✗ {$route} NOT found\n";
        }
    }
} else {
    echo "   ✗ Routes.php NOT found\n";
}

// 5. Check Auth controller
echo "\n5. Checking Auth controller...\n";
if (file_exists(APPPATH . 'Controllers/Auth.php')) {
    echo "   ✓ Auth.php exists\n";
    $authContent = file_get_contents(APPPATH . 'Controllers/Auth.php');
    
    if (strpos($authContent, 'processPasswordLogin') !== false) {
        echo "   ✓ processPasswordLogin method exists\n";
    } else {
        echo "   ✗ processPasswordLogin method NOT found\n";
    }
} else {
    echo "   ✗ Auth.php NOT found\n";
}

// 6. Check AuthFilter
echo "\n6. Checking AuthFilter...\n";
if (file_exists(APPPATH . 'Filters/AuthFilter.php')) {
    echo "   ✓ AuthFilter.php exists\n";
} else {
    echo "   ✗ AuthFilter.php NOT found\n";
}

// 7. Check writable directory
echo "\n7. Checking writable directories...\n";
$writableDirs = ['session', 'logs', 'cache'];
foreach ($writableDirs as $dir) {
    $path = WRITEPATH . $dir;
    if (is_dir($path) && is_writable($path)) {
        echo "   ✓ {$dir} directory is writable\n";
    } else {
        echo "   ✗ {$dir} directory not writable or doesn't exist\n";
    }
}

$conn->close();

echo "\n=== DIAGNOSTIC COMPLETE ===\n";
echo "\nIf all checks pass, you should be able to login at:\n";
echo "http://localhost:8080/login\n\n";
echo "Test with:\n";
echo "- Email: superadmin@flex.com\n";
echo "- Password: Super@123\n";
echo "\nFor complete list of test credentials, see DUMMY_USERS.md\n";

