<?php
declare(strict_types=1);

define('CLI_SCRIPT', true);
require __DIR__ . '/../../public/index.php';

$db = \App\Core\Database::getInstance();

$email = '';
$pass  = '';
foreach ($argv as $a) {
    if (str_starts_with($a, '--email=')) $email = substr($a, 8);
    if (str_starts_with($a, '--pass='))  $pass  = substr($a, 7);
}
if ($email === '' || $pass === '') {
    echo "Usage: php debug_login.php --email=user@x.com --pass='PASSWORD'\n";
    exit(1);
}

$emailNorm = mb_strtolower(trim($email));

// detect password column
$cols = $db->query("SHOW COLUMNS FROM users")->fetchAll();
$colNames = array_map(fn($r) => (string)$r['Field'], $cols);

$candidates = ['password_hash','password_digest','pass_hash','passwd_hash','hash','password'];
$pwCol = '';
foreach ($candidates as $c) {
    if (in_array($c, $colNames, true)) { $pwCol = $c; break; }
}
if ($pwCol === '') {
    echo "No known password column found in users table.\n";
    echo "Columns: " . implode(', ', $colNames) . "\n";
    exit(1);
}

$sql = "SELECT id, email, role_id, is_active, `$pwCol` AS pw FROM users WHERE LOWER(email)=:email LIMIT 1";
$st = $db->prepare($sql);
$st->execute([':email' => $emailNorm]);
$u = $st->fetch();
if (!$u) {
    echo "User not found for email: $email\n";
    exit(1);
}

$hash = (string)($u['pw'] ?? '');

echo "ID: {$u['id']}\n";
echo "Email: {$u['email']}\n";
echo "Role: {$u['role_id']}\n";
echo "Active: {$u['is_active']}\n";
echo "Password column used: {$pwCol}\n";
echo "pw len=" . strlen($hash) . " prefix=" . substr($hash,0,12) . "\n";

$isBcrypt = str_starts_with($hash, '$2y$') || str_starts_with($hash, '$2a$') || str_starts_with($hash, '$2b$');
echo "Looks bcrypt: " . ($isBcrypt ? "YES" : "NO") . "\n";

if ($isBcrypt) {
    echo "password_verify(): " . (password_verify($pass, $hash) ? "TRUE" : "FALSE") . "\n";
} else {
    echo "Plain compare: " . (hash_equals($hash, $pass) ? "TRUE" : "FALSE") . "\n";
}
