<?php

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

// ============================================
// FUNÇÃO: Pegar IP real (considera proxy)
// ============================================

function getRealIpAddress() {
    // Tenta pegar IP real atrás de proxy/load balancer
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        return trim($ips[0]); // Primeiro IP da lista
    }
    
    if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
        return $_SERVER['HTTP_X_REAL_IP'];
    }
    
    return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
}

// ============================================
// VALIDAÇÃO DO TOKEN (GET ou POST)
// ============================================

// Aceita token via GET ou POST (híbrido)
$token = null;

if (isset($_GET['token'])) {
    $token = trim($_GET['token']);
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $payload = json_decode(file_get_contents('php://input'), true);
    if (isset($payload['token'])) {
        $token = trim($payload['token']);
    }
}

if (!$token) {
    jsonResponse(['error' => 'Missing token parameter'], 400);
}

// Validação de formato (flexível: 32-128 caracteres)
if (strlen($token) < 32 || strlen($token) > 128) {
    jsonResponse(['error' => 'Invalid token format'], 400);
}

// ============================================
// BUSCA NO BANCO
// ============================================

$db = Database::getConnection();

$stmt = $db->prepare(
    'SELECT 
        t.id as access_token_id,
        t.expires_at,
        r.document_number,
        r.order_number,
        r.invoice_series,
        r.invoice_number,
        r.invoice_key,
        r.barcode,
        r.issue_date,
        r.due_date,
        r.payment_date,
        r.amount,
        c.name as customer_name,
        c.email as customer_email,
        c.document as customer_document
     FROM access_tokens t
     JOIN email_sends e ON e.id = t.email_send_id
     JOIN receivables r ON r.id = e.receivable_id
     JOIN billing_customers c ON c.id = r.customer_id
     WHERE t.token = ? AND t.is_active = 1 AND t.expires_at >= NOW()
     LIMIT 1'
);

$stmt->bind_param('s', $token);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    jsonResponse(['error' => 'Invalid or expired token'], 404);
}

$data = $result->fetch_assoc();

// ============================================
// REGISTRA O ACESSO
// ============================================

$stmt = $db->prepare(
    'INSERT INTO access_logs 
     (access_token_id, ip_address, user_agent, action, accessed_at)
     VALUES (?, ?, ?, "viewed_page", NOW())'
);

$ipAddress = getRealIpAddress();
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';

$stmt->bind_param('iss', 
    $data['access_token_id'],
    $ipAddress,
    $userAgent
);
$stmt->execute();

// ============================================
// CALCULA STATUS
// ============================================

$status = 'open';
$status_label = 'Em Aberto';

if ($data['payment_date']) {
    $status = 'paid';
    $status_label = 'Pago';
} elseif (strtotime($data['due_date']) < time()) {
    $status = 'overdue';
    $status_label = 'Vencido';
}

// ============================================
// MONTA LINKS DOS ARQUIVOS
// ============================================

$files = [];

// Boleto (usa document_number)
if ($data['document_number']) {
    $files['boleto'] = [
        'name' => 'Boleto Bancário',
        'download_url' => BASE_URL . '/api/receivables/download.php?token=' . $token . '&type=boleto',
        'available' => true
    ];
}

// Nota Fiscal PDF (usa invoice_key)
if ($data['invoice_key']) {
    $files['invoice_pdf'] = [
        'name' => 'Nota Fiscal (PDF)',
        'download_url' => BASE_URL . '/api/receivables/download.php?token=' . $token . '&type=invoice_pdf',
        'available' => true
    ];
    
    $files['invoice_xml'] = [
        'name' => 'Nota Fiscal (XML)',
        'download_url' => BASE_URL . '/api/receivables/download.php?token=' . $token . '&type=invoice_xml',
        'available' => true
    ];
}

// ============================================
// RESPOSTA
// ============================================

jsonResponse([
    'receivable' => [
        'document_number' => $data['document_number'],
        'order_number' => $data['order_number'],
        'invoice_series' => $data['invoice_series'],
        'invoice_number' => $data['invoice_number'],
        'invoice_key' => $data['invoice_key'],
        'barcode' => $data['barcode'],
        'issue_date' => $data['issue_date'],
        'due_date' => $data['due_date'],
        'payment_date' => $data['payment_date'],
        'amount' => number_format($data['amount'], 2, '.', ''),
        'amount_formatted' => 'R$ ' . number_format($data['amount'], 2, ',', '.'),
        'status' => $status,
        'status_label' => $status_label
    ],
    'customer' => [
        'name' => $data['customer_name'],
        'email' => $data['customer_email'],
        'document' => $data['customer_document']
    ],
    'files' => $files,
    'token_expires_at' => $data['expires_at']
]);