<?php
declare(strict_types=1);

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

session_start();
require __DIR__ . '/db.php';

$email = trim((string)($_POST['email'] ?? ''));
$pass  = (string)($_POST['password'] ?? '');

if ($email === '' || $pass === '') {
  exit("DEBUG: Missing email or password");
}

$stmt = $pdo->prepare("SELECT id, email, password_hash, status FROM userdb WHERE email = :email LIMIT 1");
$stmt->execute([':email' => $email]);
$user = $stmt->fetch();

if (!$user) {
  exit("DEBUG: No user found for email = " . htmlspecialchars($email));
}

if ($user['status'] !== 'active') {
  exit("DEBUG: User status is not active. status=" . htmlspecialchars((string)$user['status']));
}

$ok = password_verify($pass, (string)$user['password_hash']);
if (!$ok) {
  exit("DEBUG: password_verify FAILED. Hash in DB = " . htmlspecialchars((string)$user['password_hash']));
}

session_regenerate_id(true);
$_SESSION['user_id'] = (int)$user['id'];

echo "DEBUG: Login OK. Session user_id=" . (int)$_SESSION['user_id'] . "<br>";
echo "<a href='dashboard.php'>Go to dashboard</a>";
