<?php
// POST /api/auth/login.php
// Body: username, password

require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

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

$username = trim(post('username', ''));
$password = trim(post('password', ''));

if (empty($username) || empty($password)) {
    apiError('Username and password are required.', 422, [
        'username' => empty($username) ? 'Required' : null,
        'password' => empty($password) ? 'Required' : null,
    ]);
}

$db = getDB();
$stmt = $db->prepare("
    SELECT u.*, r.name AS role_name 
    FROM users u 
    LEFT JOIN roles r ON r.id = u.role_id 
    WHERE (u.username = ? OR u.email = ?) AND u.is_active = 1
    LIMIT 1
");
$stmt->execute([$username, $username]);
$user = $stmt->fetch();

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

// Generate secure token
$token = bin2hex(random_bytes(32)); // 64 char hex string

// Store token in DB (expires in 30 days)
$expiresAt = date('Y-m-d H:i:s', strtotime('+30 days'));
$deviceInfo = substr($_SERVER['HTTP_USER_AGENT'] ?? 'unknown', 0, 255);
$ipAddress  = $_SERVER['REMOTE_ADDR'] ?? null;

$db->prepare("
    INSERT INTO user_tokens (user_id, token, device_info, ip_address, expires_at)
    VALUES (?, ?, ?, ?, ?)
")->execute([$user['id'], $token, $deviceInfo, $ipAddress, $expiresAt]);

// Update last login
$db->prepare("UPDATE users SET last_login = NOW() WHERE id = ?")->execute([$user['id']]);

// Clean up old tokens for this user (keep last 5)
$db->prepare("
    DELETE FROM user_tokens 
    WHERE user_id = ? AND id NOT IN (
        SELECT id FROM (
            SELECT id FROM user_tokens WHERE user_id = ? ORDER BY created_at DESC LIMIT 5
        ) t
    )
")->execute([$user['id'], $user['id']]);

unset($user['password_hash']);

apiSuccess([
    'token'      => $token,
    'expires_at' => $expiresAt,
    'user'       => [
        'id'        => (int)$user['id'],
        'username'  => $user['username'],
        'email'     => $user['email'],
        'full_name' => $user['full_name'],
        'role_id'   => (int)$user['role_id'],
        'role_name' => $user['role_name'],
        'avatar'    => $user['avatar'],
    ]
], 'Login successful.');
