<?php
// TEMPORARY DEBUG LOGIN - remove after fixing
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
require_once '../config/database.php';

$error = "";
$debug = [];

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $login    = trim($_POST["login"] ?? "");
    $password = $_POST["password"]   ?? "";

    $debug[] = "Login attempt: " . htmlspecialchars($login);

    /* Find user */
    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE (email = ? OR username = ?) AND status = 'active' LIMIT 1");
        $stmt->execute([$login, $login]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        $debug[] = $user ? "User found: id={$user['id']} role={$user['role']}" : "No user found";
    } catch (Throwable $e) {
        $debug[] = "DB ERROR: " . $e->getMessage();
        $user = null;
    }

    if ($user) {
        $pwOk = password_verify($password, $user["password"]);
        $debug[] = "Password check: " . ($pwOk ? "OK" : "FAILED");

        if ($pwOk) {
            $_SESSION["user_id"] = $user["id"];
            $_SESSION["name"]    = $user["name"];
            $_SESSION["role"]    = $user["role"];
            $_SESSION["company_id"]   = null;
            $_SESSION["company_name"] = null;
            $_SESSION["staff_role"]   = null;

            if (in_array($user["role"], ["company_admin", "staff"])) {
                try {
                    $cs = $pdo->prepare("SELECT cs.company_id, cs.staff_role, c.name AS company_name FROM company_staff cs JOIN companies c ON c.id = cs.company_id WHERE cs.user_id = ? LIMIT 1");
                    $cs->execute([$user["id"]]);
                    $csRow = $cs->fetch(PDO::FETCH_ASSOC);
                    if ($csRow) {
                        $_SESSION["company_id"]   = $csRow["company_id"];
                        $_SESSION["company_name"] = $csRow["company_name"];
                        $_SESSION["staff_role"]   = $csRow["staff_role"];
                        $debug[] = "Company: id={$csRow['company_id']} name={$csRow['company_name']}";
                    } else {
                        $debug[] = "No company_staff row found for this user";
                    }
                } catch (Throwable $e) {
                    $debug[] = "Company lookup ERROR: " . $e->getMessage();
                }
            }

            $debug[] = "Role: {$user['role']} — would redirect to: ";
            switch ($user["role"]) {
                case "admin":         $debug[] = "../admin/dashboard.php"; break;
                case "company_admin": $debug[] = "../company/dashboard.php"; break;
                case "staff":         $debug[] = "../staff/dashboard.php"; break;
                case "partner":       $debug[] = "../partner/dashboard.php"; break;
                case "customer":      $debug[] = "../customer/dashboard.php"; break;
                default:              $debug[] = "NO REDIRECT — unknown role: {$user['role']}";
            }

            /* Check if target file exists */
            $targets = [
                "admin"         => "../admin/dashboard.php",
                "company_admin" => "../company/dashboard.php",
                "staff"         => "../staff/dashboard.php",
                "partner"       => "../partner/dashboard.php",
                "customer"      => "../customer/dashboard.php",
            ];
            if (isset($targets[$user["role"]])) {
                $target = $targets[$user["role"]];
                $realpath = realpath(__DIR__ . "/" . $target);
                $debug[] = "Target real path: " . ($realpath ?: "FILE NOT FOUND — " . __DIR__ . "/" . $target);
            }
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Login Debug</title>
    <style>
        body { font-family: monospace; background: #0f172a; color: #e2e8f0; padding: 32px; }
        h2 { color: #38bdf8; margin-bottom: 16px; }
        .debug { background: #1e293b; border: 1px solid #334155; border-radius: 8px; padding: 16px; margin-bottom: 24px; }
        .debug li { padding: 4px 0; border-bottom: 1px solid #1e293b; color: #94a3b8; font-size: 13px; }
        .debug li:first-child { color: #4ade80; font-weight: bold; }
        form { background: #1e293b; border-radius: 8px; padding: 24px; max-width: 400px; }
        label { display: block; color: #94a3b8; font-size: 12px; margin-bottom: 4px; margin-top: 12px; }
        input { width: 100%; padding: 8px 12px; background: #0f172a; border: 1px solid #334155; border-radius: 6px; color: #e2e8f0; font-family: monospace; font-size: 14px; }
        button { margin-top: 16px; width: 100%; padding: 10px; background: #2563eb; color: #fff; border: none; border-radius: 6px; font-size: 14px; cursor: pointer; }
        .note { color: #f59e0b; font-size: 12px; margin-top: 16px; padding: 10px; background: #1e293b; border-radius: 6px; border-left: 3px solid #f59e0b; }
    </style>
</head>
<body>

<h2>🔍 Login Debug Page</h2>

<?php if (!empty($debug)): ?>
<div class="debug">
    <ul>
        <?php foreach ($debug as $d): ?>
            <li><?= htmlspecialchars($d) ?></li>
        <?php endforeach; ?>
    </ul>
</div>
<?php endif; ?>

<form method="POST">
    <label>Username or Email</label>
    <input type="text" name="login" value="<?= htmlspecialchars($_POST['login'] ?? '') ?>" placeholder="admin@example.com">
    <label>Password</label>
    <input type="password" name="password" placeholder="password">
    <button type="submit">Test Login (no redirect)</button>
</form>

<div class="note">
    ⚠️ This page shows what happens during login WITHOUT redirecting.<br>
    Replace auth/login.php with this temporarily, then restore after fixing.
</div>

</body>
</html>