<?php
/* ============================================================================
 *  admin/login_check.php — diagnose why a specific account can't log in.
 *  Usage: login_check.php?login=<username-or-email>
 *  Shows the users row state the login query cares about. Admin-only. Delete after.
 * ==========================================================================*/
session_start();
require_once '../config/database.php';
header('Content-Type: text/html; charset=utf-8');
if (!isset($_SESSION["user_id"]) || ($_SESSION["role"] ?? '') !== 'admin') {
    die('Admins only. <a href="dashboard.php">Back</a>');
}
echo "<style>body{font-family:Arial;padding:24px;max-width:820px;margin:auto;}table{border-collapse:collapse;width:100%;}td,th{border:1px solid #ccc;padding:7px 10px;text-align:left;font-size:14px;}th{background:#0f172a;color:#fff;width:230px;}form{margin-bottom:18px;}input{padding:8px;width:280px;}button{padding:8px 14px;background:#0f766e;color:#fff;border:none;border-radius:6px;}</style>";

echo "<h2>Login diagnostic</h2>";
echo "<form method='get'><input name='login' placeholder='username or email' value='".htmlspecialchars($_GET['login'] ?? '')."' autofocus> <button>Check</button></form>";

$login = trim($_GET['login'] ?? '');
if ($login === '') { echo "<p>Enter the username or email the user types to log in.</p>"; exit; }

/* mirror the real login lookup, but WITHOUT the status filter so we can see why */
$st = $pdo->prepare("SELECT u.*, c.id AS wallet_id, c.status AS wallet_status, c.customer_code
                     FROM users u LEFT JOIN customers c ON c.user_id=u.id
                     WHERE (u.email=? OR u.username=?) LIMIT 1");
$st->execute([$login, $login]);
$u = $st->fetch(PDO::FETCH_ASSOC);

if (!$u) {
    echo "<p style='color:#b91c1c;font-weight:700'>❌ No user matches email OR username = '".htmlspecialchars($login)."'.</p>";
    echo "<p>Likely cause: they log in with something that isn't their username or email (e.g. phone), or the value changed. Try the other one.</p>";
    exit;
}

$rows = [
    'users.id'        => $u['id'],
    'name'            => $u['name'],
    'username'        => $u['username'] === null ? '⟨NULL⟩' : ($u['username']===''?'⟨empty⟩':$u['username']),
    'email'           => $u['email'] === null ? '⟨NULL⟩' : ($u['email']===''?'⟨empty⟩':$u['email']),
    'role'            => $u['role'],
    'status'          => $u['status'],
    'password set?'   => !empty($u['password']) ? 'yes ('.strlen($u['password']).' chars)' : '❌ NO',
    'wallet (customers)' => $u['wallet_id'] ? "yes #{$u['wallet_id']}" : '— none',
    'wallet status'   => $u['wallet_status'] ?? '—',
];
echo "<table>";
foreach ($rows as $k=>$v) echo "<tr><th>".htmlspecialchars($k)."</th><td>".htmlspecialchars((string)$v)."</td></tr>";
echo "</table>";

echo "<h3>Verdict</h3><ul>";
if ($u['status'] !== 'active') {
    echo "<li style='color:#b91c1c;font-weight:700'>BLOCKED: status is '".htmlspecialchars($u['status'])."'. Login requires 'active'. → This is why they can't log in.</li>";
    echo "<li>Fix: set them active again. <a href='login_check.php?login=".urlencode($login)."&activate=1'>Click here to re-activate this user</a>.</li>";
} else {
    echo "<li style='color:#15803d'>status = active ✓ (not blocked by status)</li>";
}
if (empty($u['password'])) echo "<li style='color:#b91c1c'>No password hash stored — reset their password.</li>";
echo "<li>The login also matches on <b>email OR username</b>. Make sure the user types exactly the value shown above (email is now NULL for blanks, so they must use their <b>username</b> if email shows NULL).</li>";
echo "</ul>";

/* optional one-click reactivate */
if (isset($_GET['activate']) && $u['status'] !== 'active') {
    $pdo->prepare("UPDATE users SET status='active' WHERE id=?")->execute([$u['id']]);
    echo "<p style='color:#15803d;font-weight:700'>✓ Re-activated. Try logging in again. <a href='login_check.php?login=".urlencode($login)."'>Refresh</a></p>";
}