<?php
/**
 * POST /api/auth/login.php
 * Body: { email, password }
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

only_post_allowed();

$input = get_json_input();
$missing = validate_required($input, ['email', 'password']);
if ($missing) {
    send_error('Email and password are required.', 422, $missing);
}

$email    = trim($input['email']);
$password = (string) $input['password'];

$pdo = Database::connect();
$stmt = $pdo->prepare('SELECT id, email, password_hash, account_type, status, email_verified_at FROM users WHERE email = ? LIMIT 1');
$stmt->execute([$email]);
$user = $stmt->fetch();

if (!$user || !password_verify($password, $user['password_hash'])) {
    send_error('Invalid email or password.', 401);
}

if (!$user['email_verified_at']) {
    send_error('Please verify your email before logging in - check your inbox for the link.', 403, ['unverified' => true]);
}

if ($user['status'] !== 'active') {
    send_error('This account is not active. Please contact support.', 403);
}

login_user($user);

send_json(true, 'Logged in successfully.', [
    'user' => [
        'id'           => (int) $user['id'],
        'email'        => $user['email'],
        'account_type' => $user['account_type'],
    ],
]);
