<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_user.php';

apply_cors();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_error('Method not allowed.', 405);
}

$input = get_json_input();
require_fields($input, ['email', 'password']);

$email = strtolower(clean_str($input['email']));
$password = (string) $input['password'];
$deviceId = clean_str($input['device_id'] ?? '');

$pdo = getDbConnection();

$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email AND role = 'USER' LIMIT 1");
$stmt->execute([':email' => $email]);
$user = $stmt->fetch();

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

if ((int) $user['is_blocked'] === 1) {
    send_error('This account has been blocked. Contact support for assistance.', 403);
}

// ---- Single-device lock enforcement ----
if ($deviceId !== '') {
    if (!empty($user['active_device_id']) && $user['active_device_id'] !== $deviceId) {
        send_error(
            'This account is already active on another device. Ask an admin to reset your device lock, or log out there first.',
            409,
            ['error_code' => 'DEVICE_LOCKED']
        );
    }
    if (empty($user['active_device_id'])) {
        $bind = $pdo->prepare('UPDATE users SET active_device_id = :device_id WHERE id = :id');
        $bind->execute([':device_id' => $deviceId, ':id' => $user['id']]);
    }
}

$upd = $pdo->prepare('UPDATE users SET last_login = NOW() WHERE id = :id');
$upd->execute([':id' => $user['id']]);

$token = create_user_session((int) $user['id'], $deviceId);

unset($user['password_hash'], $user['reset_token'], $user['verification_token']);

send_success(['token' => $token, 'user' => $user], 'Login successful.');
