<?php
/**
 * POST /api/auth/token.php
 * Body (JSON): { email, password }
 *
 * Mobile equivalent of login.php - same credential checks, same account
 * status/verification rules, but issues a JWT access token + refresh token
 * pair instead of starting a PHP session. Does not touch $_SESSION at all,
 * so this can be called from a native app with no cookie jar.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/jwt.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'];
$deviceLabel = isset($input['device_label']) ? trim((string) $input['device_label']) : null;

$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);
}

[$accessToken, $refreshToken] = issue_token_pair($pdo, (int) $user['id'], (string) $user['account_type'], $deviceLabel);

send_json(true, 'Logged in successfully.', [
    'user' => [
        'id'           => (int) $user['id'],
        'email'        => $user['email'],
        'account_type' => $user['account_type'],
    ],
    'access_token'  => $accessToken,
    'refresh_token' => $refreshToken,
    'expires_in'    => JWT_ACCESS_TTL,
]);
