<?php

require_once __DIR__ . '/../config/database.php';

function authenticateCompany()
{
    $headers = getallheaders();

    if (!isset($headers['Authorization'])) {
        http_response_code(401);
        exit(json_encode(['error' => 'Missing Authorization header']));
    }

    if (!preg_match('/Bearer\s+(\S+)/', $headers['Authorization'], $matches)) {
        http_response_code(401);
        exit(json_encode(['error' => 'Invalid Authorization format']));
    }

    $apiKey = trim($matches[1]);
    
    // Validação básica do formato
    if (strlen($apiKey) < 32) {
        http_response_code(401);
        exit(json_encode(['error' => 'Invalid API key format']));
    }

    $db = Database::getConnection();
    $stmt = $db->prepare(
        'SELECT id, name, token_expiration_days 
         FROM api_companies 
         WHERE api_key = ? AND is_active = 1'
    );
    $stmt->bind_param('s', $apiKey);
    $stmt->execute();

    $result = $stmt->get_result();
    if ($result->num_rows === 0) {
        http_response_code(401);
        exit(json_encode(['error' => 'Invalid or inactive API key']));
    }

    return $result->fetch_assoc(); // Retorna array completo, não só ID
}