<?php

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

$db = Database::getConnection();

// ============================================
// 1. BUSCA OU CRIA EMPRESA DE TESTE
// ============================================

$companyName = 'Empresa Teste';

// Primeiro tenta buscar
$stmt = $db->prepare('SELECT id, api_key FROM api_companies WHERE name = ? LIMIT 1');
$stmt->bind_param('s', $companyName);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    // Empresa já existe
    $company = $result->fetch_assoc();
    $companyId = $company['id'];
    $apiKey = $company['api_key'];
    echo "✅ Usando empresa existente\n";
} else {
    // Cria nova empresa
    $apiKey = bin2hex(random_bytes(32));
    $stmt = $db->prepare(
        'INSERT INTO api_companies (name, api_key, is_active, created_at)
         VALUES (?, ?, 1, NOW())'
    );
    $stmt->bind_param('ss', $companyName, $apiKey);
    $stmt->execute();
    $companyId = $stmt->insert_id;
    echo "🆕 Empresa criada\n";
}

echo "Company ID: {$companyId}\n";
echo "API Key: {$apiKey}\n\n";

// ============================================
// 2. MONTA PAYLOAD COM DOCUMENT_NUMBER ÚNICO
// ============================================

$payload = [
    'customer' => [
        'name' => 'Cliente Teste Ltda',
        'email' => 'leandro.santiago.rosa@gmail.com',
        'document' => '12345678000199'
    ],
    'receivable' => [
        'order_id' => null,
        'document_number' => 'TEST-' . time(),
        'order_number' => 'PED-001',
        'quote_number' => null,
        'customer_po_number' => null,
        'invoice_series' => '001',
        'invoice_number' => 12345,
        'invoice_key' => '35250112345678000199550010000123451234567890',
        'barcode' => '34191234567890123456789012345678901234567890123456',
        'issue_date' => date('Y-m-d'),
        'due_date' => date('Y-m-d', strtotime('+30 days')),
        'amount' => 1500.50
    ],
    'email' => [
        'subject' => 'Teste de Envio - NF 12345'
    ]
];

// ============================================
// 3. FAZ REQUISIÇÃO
// ============================================

$url = BASE_URL . '/api/receivables/send.php';
echo "Calling: {$url}\n\n";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $apiKey
]);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

echo "HTTP Code: {$httpCode}\n";

if ($curlError) {
    echo "CURL Error: {$curlError}\n";
}

echo "\nResponse:\n";
echo json_encode(json_decode($response), JSON_PRETTY_PRINT) . "\n";