<?php

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

// ============================================
// PEGA O TOKEN DA URL
// ============================================

$token = $_GET['token'] ?? null;

if (empty($token) || strlen($token) !== 64) {
    http_response_code(404);
    die('Token inválido');
}

// ============================================
// BUSCA RECEIVABLES DO TOKEN
// ============================================

$db = Database::getConnection();

// Busca access_token
$stmt = $db->prepare(
    'SELECT id, email_send_id, expires_at 
     FROM access_tokens 
     WHERE token = ? 
     LIMIT 1'
);
$stmt->bind_param('s', $token);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    http_response_code(404);
    die('Token não encontrado');
}

$accessToken = $result->fetch_assoc();
$emailSendId = $accessToken['email_send_id'];
$expiresAt = $accessToken['expires_at'];

// Verifica se expirou
if (strtotime($expiresAt) < time()) {
    http_response_code(403);
    die('Token expirado');
}

// Busca receivables relacionados ao email_send
$stmt = $db->prepare(
    'SELECT r.id, r.document_number, r.order_number, r.invoice_number, 
            r.invoice_series, r.due_date, r.amount, r.barcode, r.invoice_key,
            c.name as customer_name, c.email as customer_email
     FROM receivables r
     INNER JOIN email_send_receivables esr ON r.id = esr.receivable_id
     INNER JOIN billing_customers c ON r.customer_id = c.id
     WHERE esr.email_send_id = ?
     ORDER BY r.due_date ASC'
);
$stmt->bind_param('i', $emailSendId);
$stmt->execute();
$receivables = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

if (empty($receivables)) {
    http_response_code(404);
    die('Nenhum documento encontrado');
}

// ============================================
// BUSCA CONFIGURAÇÕES DE EMAIL DA EMPRESA
// ============================================

$companyId = 1;

$stmt = $db->prepare(
    'SELECT primary_color, button_color, button_text_color, logo_url, header_title
     FROM company_email_settings 
     WHERE company_id = ?'
);
$stmt->bind_param('i', $companyId);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $settings = $result->fetch_assoc();
} else {
    $settings = [
        'primary_color' => '#28a745',
        'button_color' => '#28a745',
        'button_text_color' => '#ffffff',
        'logo_url' => null,
        'header_title' => 'Seus Documentos Fiscais'
    ];
}

// ============================================
// CALCULA TOTAL
// ============================================

$totalAmount = 0;
foreach ($receivables as $r) {
    $totalAmount += $r['amount'];
}

$customerName = $receivables[0]['customer_name'];

?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documentos Fiscais - <?= htmlspecialchars($customerName) ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
		/* Cores dinâmicas da empresa */
		.header,
		.documents-table thead {
			background: <?= $settings['primary_color'] ?>;
		}
		.summary {
			border-left-color: <?= $settings['primary_color'] ?>;
		}
		.btn-download {
			background: <?= $settings['button_color'] ?>;
			color: <?= $settings['button_text_color'] ?>;
		}
	</style>
</head>
<body>
    <div class="container">
        <div class="header">
			<?php if (!empty($settings['logo_url'])): ?>
				<img src="<?= htmlspecialchars($settings['logo_url']) ?>" 
					 alt="Logo" 
					 class="header-logo">
			<?php endif; ?>
			
			<h1><?= htmlspecialchars($settings['header_title']) ?></h1>
			<p>Olá, <?= htmlspecialchars($customerName) ?></p>
		</div>
        
        <div class="content">
            <div class="summary">
                <h2>Resumo</h2>
                <div class="summary-grid">
                    <div class="summary-item">
                        <strong>Total de Documentos</strong>
                        <span><?= count($receivables) ?></span>
                    </div>
                    <div class="summary-item">
                        <strong>Valor Total</strong>
                        <span>R$ <?= number_format($totalAmount, 2, ',', '.') ?></span>
                    </div>
                </div>
            </div>

            <h2 style="margin-bottom: 20px;">Documentos</h2>
            
            <table class="documents-table">
                <thead>
                    <tr>
                        <th>Documento</th>
                        <th>NF-e</th>
                        <th>Vencimento</th>
                        <th>Valor</th>
                        <th>Status</th>
                        <th>Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($receivables as $rec): ?>
                        <?php
                            $dueDate = strtotime($rec['due_date']);
                            $today = strtotime(date('Y-m-d'));
                            
                            if ($dueDate < $today) {
                                $statusClass = 'status-overdue';
                                $statusText = 'Vencido';
                            } elseif ($dueDate == $today) {
                                $statusClass = 'status-pending';
                                $statusText = 'Vence Hoje';
                            } else {
                                $statusClass = 'status-ok';
                                $statusText = 'Em Dia';
                            }
                        ?>
                        <tr>
                            <td><strong><?= htmlspecialchars($rec['document_number']) ?></strong></td>
                            <td><?= $rec['invoice_number'] ?? '-' ?></td>
                            <td><?= date('d/m/Y', strtotime($rec['due_date'])) ?></td>
                            <td><strong>R$ <?= number_format($rec['amount'], 2, ',', '.') ?></strong></td>
                            <td><span class="status-badge <?= $statusClass ?>"><?= $statusText ?></span></td>
                            <td class="actions-cell">
                                <?php if ($rec['barcode'] || $rec['invoice_key']): ?>
                                    <div class="actions-grid">
                                        <!-- BOLETO -->
                                        <div class="action-column">
                                            <span class="action-label">Boleto</span>
                                            <?php if ($rec['barcode']): ?>
                                                <a href="/api/receivables/download.php?token=<?= htmlspecialchars($token) ?>&type=boleto&id=<?= $rec['id'] ?>" 
                                                   class="btn-download" 
                                                   target="_blank"
                                                   title="Baixar Boleto">
                                                    ⬇️
                                                </a>
                                            <?php else: ?>
                                                <span style="color: #ccc; font-size: 20px;">—</span>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <!-- DANFE PDF -->
                                        <div class="action-column">
                                            <span class="action-label">DANFE</span>
                                            <?php if ($rec['invoice_key']): ?>
                                                <a href="/api/receivables/download.php?token=<?= htmlspecialchars($token) ?>&type=invoice_pdf&id=<?= $rec['id'] ?>" 
                                                   class="btn-download" 
                                                   target="_blank"
                                                   title="Baixar DANFE em PDF">
                                                    ⬇️
                                                </a>
                                            <?php else: ?>
                                                <span style="color: #ccc; font-size: 20px;">—</span>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <!-- XML -->
                                        <div class="action-column">
                                            <span class="action-label">XML</span>
                                            <?php if ($rec['invoice_key']): ?>
                                                <a href="/api/receivables/download.php?token=<?= htmlspecialchars($token) ?>&type=invoice_xml&id=<?= $rec['id'] ?>" 
                                                   class="btn-download" 
                                                   target="_blank"
                                                   title="Baixar XML da NF-e">
                                                    ⬇️
                                                </a>
                                            <?php else: ?>
                                                <span style="color: #ccc; font-size: 20px;">—</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php else: ?>
                                    <span class="no-attachments">Sem anexos</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            
            <div class="footer">
                <p>Em caso de dúvidas, entre em contato com nosso suporte.</p>
                <p class="expiration">Este link expira em <?= date('d/m/Y', strtotime($expiresAt)) ?></p>
            </div>
        </div>
    </div>
</body>
</html>