<?php
// Ultimate Debug Login - Save as debug_auth_login.php
// This will help us identify exactly where the login process is failing

session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Include database connection
require_once 'layouts/dbconn.php';

echo "<h1>🔧 Ultimate Login Debug Tool</h1>";
echo "<p>This will show every step of the login process in real-time.</p>";

// Check if this is a POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    
    echo "<div style='background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;'>";
    echo "<h2>🚀 Login Process Started</h2>";
    
    // Step 1: Form Data Check
    echo "<h3>Step 1: Form Data Validation</h3>";
    echo "✅ Email: " . htmlspecialchars($email) . "<br>";
    echo "✅ Password Length: " . strlen($password) . " characters<br>";
    echo "✅ Form Method: " . $_SERVER['REQUEST_METHOD'] . "<br>";
    echo "✅ Form Submit Button: " . (isset($_POST['login']) ? 'Present' : 'Missing') . "<br><br>";
    
    if (empty($email) || empty($password)) {
        echo "❌ <strong>STOP: Missing email or password</strong><br>";
        echo "</div>";
        goto show_form;
    }
    
    // Step 2: Database Connection Check
    echo "<h3>Step 2: Database Connection</h3>";
    if (!$conn || $conn->connect_error) {
        echo "❌ <strong>STOP: Database connection failed</strong><br>";
        echo "Error: " . ($conn->connect_error ?? 'Unknown') . "<br>";
        echo "</div>";
        goto show_form;
    }
    echo "✅ Database connected successfully<br><br>";
    
    // Step 3: User Lookup
    echo "<h3>Step 3: User Lookup</h3>";
    try {
        $stmt = $conn->prepare("
            SELECT u.user_id, u.username, u.email, u.full_name, u.password, u.role_id, u.status, ur.role_name 
            FROM users u
            LEFT JOIN user_roles ur ON u.role_id = ur.role_id
            WHERE u.email = ?
        ");
        
        if (!$stmt) {
            echo "❌ <strong>STOP: Failed to prepare statement</strong><br>";
            echo "Error: " . $conn->error . "<br>";
            echo "</div>";
            goto show_form;
        }
        
        $stmt->bind_param("s", $email);
        
        if (!$stmt->execute()) {
            echo "❌ <strong>STOP: Failed to execute query</strong><br>";
            echo "Error: " . $stmt->error . "<br>";
            echo "</div>";
            goto show_form;
        }
        
        $result = $stmt->get_result();
        
        if (!$result) {
            echo "❌ <strong>STOP: Failed to get result</strong><br>";
            echo "</div>";
            goto show_form;
        }
        
        $user = $result->fetch_assoc();
        
        if (!$user) {
            echo "❌ <strong>STOP: User not found</strong><br>";
            echo "No user exists with email: " . htmlspecialchars($email) . "<br>";
            echo "</div>";
            goto show_form;
        }
        
        echo "✅ User found in database<br>";
        echo "- User ID: {$user['user_id']}<br>";
        echo "- Username: {$user['username']}<br>";
        echo "- Email: {$user['email']}<br>";
        echo "- Role: {$user['role_name']}<br>";
        echo "- Status: {$user['status']}<br>";
        echo "- Password Hash: " . substr($user['password'], 0, 30) . "...<br><br>";
        
        $stmt->close();
        
    } catch (Exception $e) {
        echo "❌ <strong>STOP: Exception during user lookup</strong><br>";
        echo "Error: " . $e->getMessage() . "<br>";
        echo "</div>";
        goto show_form;
    }
    
    // Step 4: Account Status Check
    echo "<h3>Step 4: Account Status Check</h3>";
    if ($user['status'] !== 'ACTIVE') {
        echo "❌ <strong>STOP: Account not active</strong><br>";
        echo "Status: {$user['status']}<br>";
        echo "</div>";
        goto show_form;
    }
    echo "✅ Account status is ACTIVE<br><br>";
    
    // Step 5: Password Verification
    echo "<h3>Step 5: Password Verification</h3>";
    echo "Testing password verification...<br>";
    echo "Entered password: '" . htmlspecialchars($password) . "'<br>";
    echo "Hash from DB: " . substr($user['password'], 0, 50) . "...<br>";
    
    // Check if password hash looks correct
    if (!preg_match('/^\$2[ayb]\$/', $user['password'])) {
        echo "⚠️ <strong>WARNING: Password hash format looks incorrect</strong><br>";
        echo "Expected bcrypt format starting with \$2y\$, \$2a\$, or \$2b\$<br>";
        echo "Actual format: " . substr($user['password'], 0, 10) . "...<br>";
        
        // Try direct comparison (in case passwords are stored as plain text)
        if ($password === $user['password']) {
            echo "⚠️ Password matches as plain text (security issue!)<br>";
            $password_verified = true;
        } else {
            echo "❌ Password does not match as plain text either<br>";
            $password_verified = false;
        }
    } else {
        $password_verified = password_verify($password, $user['password']);
        echo ($password_verified ? "✅" : "❌") . " password_verify() result: " . ($password_verified ? 'SUCCESS' : 'FAILED') . "<br>";
    }
    
    if (!$password_verified) {
        echo "❌ <strong>STOP: Password verification failed</strong><br>";
        echo "</div>";
        goto show_form;
    }
    echo "✅ Password verified successfully<br><br>";
    
    // Step 6: Session Management
    echo "<h3>Step 6: Session Management</h3>";
    echo "Current session status: " . (session_status() === PHP_SESSION_ACTIVE ? 'Active' : 'Inactive') . "<br>";
    echo "Session ID before: " . session_id() . "<br>";
    
    // Clear and restart session
    session_unset();
    session_destroy();
    session_start();
    session_regenerate_id(true);
    
    echo "Session ID after regeneration: " . session_id() . "<br>";
    
    // Set session variables
    $_SESSION['user'] = $user['username'];
    $_SESSION['user_id'] = (int)$user['user_id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['email'] = $user['email'];
    $_SESSION['full_name'] = $user['full_name'];
    $_SESSION['role_id'] = (int)$user['role_id'];
    $_SESSION['role_name'] = $user['role_name'] ?? 'Customer';
    $_SESSION['login_time'] = time();
    $_SESSION['logged_in'] = true;
    
    echo "✅ Session variables set:<br>";
    foreach ($_SESSION as $key => $value) {
        echo "- {$key}: " . htmlspecialchars($value) . "<br>";
    }
    echo "<br>";
    
    // Step 7: Redirect Logic
    echo "<h3>Step 7: Redirect Logic</h3>";
    $role_name = $_SESSION['role_name'] ?? 'Customer';
    
    if (in_array($role_name, ['Administrator', 'Support Agent', 'Sales Manager', 'Developer'])) {
        $redirect_url = 'index.php';
        echo "✅ Admin user detected, should redirect to: {$redirect_url}<br>";
    } else {
        $redirect_url = 'dashboard.php';
        echo "✅ Customer user detected, should redirect to: {$redirect_url}<br>";
    }
    
    // Check if file exists
    if (file_exists($redirect_url)) {
        echo "✅ Target file exists: {$redirect_url}<br>";
    } else {
        echo "❌ <strong>WARNING: Target file does not exist: {$redirect_url}</strong><br>";
    }
    
    // Step 8: Header Check
    echo "<h3>Step 8: Header Check</h3>";
    if (headers_sent($file, $line)) {
        echo "❌ <strong>PROBLEM: Headers already sent!</strong><br>";
        echo "Headers sent in file: {$file} on line: {$line}<br>";
        echo "This prevents PHP redirects from working.<br>";
    } else {
        echo "✅ Headers not sent yet, redirect should work<br>";
    }
    
    echo "<br>";
    echo "<h2>🎯 LOGIN SUCCESS!</h2>";
    echo "<p>All steps completed successfully. You should be redirected now.</p>";
    echo "<p>If redirect doesn't work automatically, click the link below:</p>";
    echo "<p><a href='{$redirect_url}' style='background: #28a745; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>Go to {$redirect_url}</a></p>";
    
    echo "</div>";
    
    // Try the redirect
    if (!headers_sent()) {
        echo "<script>
            console.log('Attempting redirect to: {$redirect_url}');
            setTimeout(function() {
                window.location.href = '{$redirect_url}';
            }, 3000);
        </script>";
        
        // Also try PHP header
        header("Location: {$redirect_url}");
        exit();
    }
    
} else {
    // Not a POST request, show the form
    show_form:
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Ultimate Debug Login</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            margin: 20px; 
            background: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group { 
            margin: 15px 0; 
        }
        input { 
            width: 100%; 
            padding: 12px; 
            margin: 5px 0; 
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }
        button { 
            background: #007bff; 
            color: white; 
            padding: 12px 30px; 
            border: none; 
            border-radius: 4px;
            cursor: pointer; 
            font-size: 16px;
            width: 100%;
        }
        button:hover {
            background: #0056b3;
        }
        .info {
            background: #e3f2fd;
            padding: 15px;
            border-radius: 4px;
            margin: 20px 0;
        }
        .test-accounts {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            margin: 20px 0;
        }
        .quick-fill {
            background: #28a745;
            color: white;
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
            font-size: 14px;
        }
        .debug-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
            border-left: 4px solid #007bff;
        }
        h3 {
            color: #495057;
            border-bottom: 2px solid #dee2e6;
            padding-bottom: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 Ultimate Login Debug Tool</h1>
        
        <div class="info">
            <h3>📋 Pre-Login Checks</h3>
            <p><strong>Current PHP Session Status:</strong> <?php echo session_status() === PHP_SESSION_ACTIVE ? '✅ Active' : '❌ Inactive'; ?></p>
            <p><strong>Database Connection:</strong> <?php echo (!$conn || $conn->connect_error) ? '❌ Failed' : '✅ Connected'; ?></p>
            <p><strong>Current Time:</strong> <?php echo date('Y-m-d H:i:s'); ?></p>
            <p><strong>Server:</strong> <?php echo $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown'; ?></p>
            <p><strong>PHP Version:</strong> <?php echo PHP_VERSION; ?></p>
        </div>

        <div class="debug-section">
            <h2>🔐 Test Login</h2>
            
            <form method="POST" style="margin-bottom: 20px;">
                <div class="form-group">
                    <label>Email Address:</label>
                    <input type="email" name="email" id="email" value="hi@myne.co.ke" required>
                </div>
                
                <div class="form-group">
                    <label>Password:</label>
                    <input type="password" name="password" id="password" value="admin123" required>
                </div>
                
                <button type="submit" name="login">🚀 Start Debug Login Process</button>
            </form>
            
            <div class="test-accounts">
                <h4>Quick Fill Test Accounts:</h4>
                <button class="quick-fill" onclick="fillLogin('hi@myne.co.ke', 'admin123')">Admin Account</button>
                <button class="quick-fill" onclick="fillLogin('customer@test.com', 'password123')">Customer Account</button>
            </div>
        </div>

        <div class="debug-section">
            <h3>📊 Current Session Data</h3>
            <pre style="background: #f1f1f1; padding: 10px; border-radius: 4px; overflow: auto;">
<?php print_r($_SESSION); ?>
            </pre>
        </div>

        <div class="debug-section">
            <h3>🔍 Database Users Check</h3>
            <?php
            try {
                $stmt = $conn->prepare("
                    SELECT u.user_id, u.username, u.email, u.status, ur.role_name,
                           CASE 
                               WHEN u.password LIKE '\$2%' THEN 'Properly Hashed (bcrypt)'
                               WHEN LENGTH(u.password) < 20 THEN 'Possibly Plain Text'
                               ELSE 'Unknown Hash Format'
                           END as password_status
                    FROM users u 
                    LEFT JOIN user_roles ur ON u.role_id = ur.role_id 
                    ORDER BY u.user_id
                ");
                $stmt->execute();
                $result = $stmt->get_result();
                
                echo "<table border='1' style='border-collapse: collapse; width: 100%;'>";
                echo "<tr style='background: #f8f9fa;'><th>ID</th><th>Username</th><th>Email</th><th>Role</th><th>Status</th><th>Password</th></tr>";
                while ($user = $result->fetch_assoc()) {
                    $statusColor = $user['status'] === 'ACTIVE' ? '#28a745' : '#dc3545';
                    $pwdColor = strpos($user['password_status'], 'Properly') !== false ? '#28a745' : '#ffc107';
                    echo "<tr>";
                    echo "<td>{$user['user_id']}</td>";
                    echo "<td>{$user['username']}</td>";
                    echo "<td>{$user['email']}</td>";
                    echo "<td>{$user['role_name']}</td>";
                    echo "<td style='color: {$statusColor}; font-weight: bold;'>{$user['status']}</td>";
                    echo "<td style='color: {$pwdColor}; font-weight: bold;'>{$user['password_status']}</td>";
                    echo "</tr>";
                }
                echo "</table>";
                $stmt->close();
            } catch (Exception $e) {
                echo "<p style='color: #dc3545;'>Error: " . $e->getMessage() . "</p>";
            }
            ?>
        </div>

        <div class="debug-section">
            <h3>🔗 Quick Navigation</h3>
            <p>
                <a href="auth-login.php" style="color: #007bff;">← Back to Regular Login</a> |
                <a href="index.php" style="color: #007bff;">Go to Index</a> |
                <a href="dashboard.php" style="color: #007bff;">Go to Dashboard</a>
            </p>
        </div>
    </div>

    <script>
        function fillLogin(email, password) {
            document.getElementById('email').value = email;
            document.getElementById('password').value = password;
        }
        
        // Auto-scroll to bottom if there's debug output
        <?php if ($_SERVER['REQUEST_METHOD'] === 'POST'): ?>
        window.scrollTo(0, document.body.scrollHeight);
        <?php endif; ?>
    </script>
</body>
</html>