<?php
// api/auth/login.php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../layouts/dbconn.php';
require_once __DIR__ . '/../../includes/JWTHelper.php';
require_once __DIR__ . '/../response.php';

header('Content-Type: application/json');

// Only allow POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonError('Method not allowed', 405);
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['username']) || !isset($input['password'])) {
    jsonError('Username and password required', 400);
}

$username = trim($input['username']);
$password = $input['password'];

// Authenticate against users table
// Using similar logic to main login.php but optimized for API
$stmt = $conn->prepare("SELECT user_id, username, password_hash, role_id, full_name, role_code 
                        FROM users u 
                        INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                        WHERE (username = ? OR email = ?) AND status = 'ACTIVE' LIMIT 1");
$stmt->bind_param("ss", $username, $username);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    // Log failure (optional/simplified)
    jsonError('Invalid credentials', 401);
}

$user = $result->fetch_assoc();

if (password_verify($password, $user['password_hash'])) {

    // Authorization Payload
    $payload = [
        'sub' => $user['user_id'],
        'username' => $user['username'],
        'role_code' => $user['role_code'],
        'full_name' => $user['full_name']
        // Add more claims as needed
    ];

    // Generate Token
    try {
        $token = JWTHelper::generate($payload);

        jsonResponse([
            'token' => $token,
            'user' => [
                'id' => $user['user_id'],
                'username' => $user['username'],
                'full_name' => $user['full_name'],
                'role' => $user['role_code']
            ]
        ]);
    } catch (Exception $e) {
        jsonError('Token generation failed', 500);
    }

} else {
    jsonError('Invalid credentials', 401);
}
?>