<?php

// Carrega config PRIMEIRO (ele carrega o .env)
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../vendor/autoload.php';

use SendGrid\Mail\Mail;

/**
 * Envia email de cobrança via SendGrid
 * 
 * @param array $receivable Dados da cobrança
 * @param array $customer Dados do cliente
 * @param string $accessToken Token de acesso
 * @param string $accessUrl URL completa com token
 * @return array|false Retorna ['message_id' => 'xxx'] ou false em caso de erro
 */
function sendReceivableEmail($receivable, $customer, $accessToken, $accessUrl) {
    
    // Validações básicas
    if (!SENDGRID_API_KEY) {
        error_log('SendGrid: API Key not configured');
        return false;
    }
    
    if (!filter_var($customer['email'], FILTER_VALIDATE_EMAIL)) {
        error_log('SendGrid: Invalid customer email: ' . $customer['email']);
        return false;
    }
    
    // Monta subject
    $subject = 'Documentos Fiscais Disponíveis';
    if (!empty($receivable['invoice_number'])) {
        $subject .= ' - NF ' . $receivable['invoice_number'];
    } else {
        $subject .= ' - Doc ' . $receivable['document_number'];
    }
    
    // Monta corpo do email (HTML)
    $htmlContent = buildEmailHtml($receivable, $customer, $accessUrl);
    
    // Monta corpo do email (texto plano - fallback)
    $textContent = buildEmailText($receivable, $customer, $accessUrl);
    
    // Cria objeto de email
    $email = new Mail();
    
    try {
        // Remetente
        $email->setFrom(SENDGRID_FROM_EMAIL, SENDGRID_FROM_NAME);
        
        // Destinatário
        $email->addTo(
            $customer['email'],
            $customer['name']
        );
        
        // Assunto
        $email->setSubject($subject);
        
        // Conteúdo
        $email->addContent("text/plain", $textContent);
        $email->addContent("text/html", $htmlContent);
        
        // Tracking
        $email->setClickTracking(true, true); // Habilita tracking de cliques
        $email->setOpenTracking(true); // Habilita tracking de abertura
        
        // Custom args (pra identificar no webhook)
        $email->addCustomArg('receivable_id', (string)$receivable['id']);
        $email->addCustomArg('document_number', $receivable['document_number']);
        
        // Envia
        $sendgrid = new \SendGrid(SENDGRID_API_KEY);
        $response = $sendgrid->send($email);
        
        // Verifica resposta
        if ($response->statusCode() >= 200 && $response->statusCode() < 300) {
            
            // Pega message ID do header
            $headers = $response->headers();
            $messageId = null;
            
            foreach ($headers as $header => $value) {
                if (strtolower($header) === 'x-message-id') {
                    $messageId = is_array($value) ? $value[0] : $value;
                    break;
                }
            }
            
            error_log('SendGrid: Email sent successfully to ' . $customer['email']);
            
            return [
                'message_id' => $messageId,
                'status_code' => $response->statusCode()
            ];
            
        } else {
            error_log('SendGrid: Failed to send email. Status: ' . $response->statusCode());
            error_log('SendGrid: Body: ' . $response->body());
            return false;
        }
        
    } catch (Exception $e) {
        error_log('SendGrid Exception: ' . $e->getMessage());
        return false;
    }
}

/**
 * Monta HTML do email
 */
function buildEmailHtml($receivable, $customer, $accessUrl) {
    
    $customerName = htmlspecialchars($customer['name']);
    $documentNumber = htmlspecialchars($receivable['document_number']);
    $invoiceNumber = !empty($receivable['invoice_number']) 
        ? htmlspecialchars($receivable['invoice_number']) 
        : null;
    $dueDate = date('d/m/Y', strtotime($receivable['due_date']));
    $amount = 'R$ ' . number_format($receivable['amount'], 2, ',', '.');
    
    $html = '
<!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</title>
</head>
<body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;">
    <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f4f4; padding: 20px;">
        <tr>
            <td align="center">
                <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    
                    <!-- Header -->
                    <tr>
                        <td style="background-color: #007bff; padding: 30px; text-align: center;">
                            <h1 style="color: #ffffff; margin: 0; font-size: 24px;">
                                ' . SENDGRID_FROM_NAME . '
                            </h1>
                        </td>
                    </tr>
                    
                    <!-- Body -->
                    <tr>
                        <td style="padding: 40px 30px;">
                            <h2 style="color: #333333; margin-top: 0; font-size: 20px;">
                                Olá, ' . $customerName . '!
                            </h2>
                            
                            <p style="color: #666666; line-height: 1.6; font-size: 16px;">
                                Seus documentos fiscais estão disponíveis para download.
                            </p>
                            
                            <table width="100%" cellpadding="0" cellspacing="0" style="margin: 30px 0; border: 1px solid #e0e0e0; border-radius: 4px;">
                                <tr>
                                    <td style="padding: 20px; background-color: #f9f9f9;">
                                        <p style="margin: 5px 0; color: #333; font-size: 14px;">
                                            <strong>Documento:</strong> ' . $documentNumber . '
                                        </p>';
    
    if ($invoiceNumber) {
        $html .= '
                                        <p style="margin: 5px 0; color: #333; font-size: 14px;">
                                            <strong>Nota Fiscal:</strong> ' . $invoiceNumber . '
                                        </p>';
    }
    
    $html .= '
                                        <p style="margin: 5px 0; color: #333; font-size: 14px;">
                                            <strong>Vencimento:</strong> ' . $dueDate . '
                                        </p>
                                        <p style="margin: 5px 0; color: #333; font-size: 14px;">
                                            <strong>Valor:</strong> ' . $amount . '
                                        </p>
                                    </td>
                                </tr>
                            </table>
                            
                            <div style="text-align: center; margin: 30px 0;">
                                <a href="' . $accessUrl . '" style="display: inline-block; padding: 15px 40px; background-color: #007bff; color: #ffffff; text-decoration: none; border-radius: 4px; font-size: 16px; font-weight: bold;">
                                    Acessar Documentos
                                </a>
                            </div>
                            
                            <p style="color: #999999; font-size: 12px; line-height: 1.6; margin-top: 30px;">
                                <strong>Importante:</strong> Este link é exclusivo e expira em 15 dias. 
                                Não compartilhe com terceiros.
                            </p>
                        </td>
                    </tr>
                    
                    <!-- Footer -->
                    <tr>
                        <td style="background-color: #f9f9f9; padding: 20px; text-align: center; border-top: 1px solid #e0e0e0;">
                            <p style="color: #999999; font-size: 12px; margin: 0;">
                                ' . SENDGRID_FROM_NAME . '<br>
                                Este é um email automático, não responda.
                            </p>
                        </td>
                    </tr>
                    
                </table>
            </td>
        </tr>
    </table>
</body>
</html>';
    
    return $html;
}

/**
 * Monta texto plano do email (fallback)
 */
function buildEmailText($receivable, $customer, $accessUrl) {
    
    $customerName = $customer['name'];
    $documentNumber = $receivable['document_number'];
    $invoiceNumber = !empty($receivable['invoice_number']) 
        ? $receivable['invoice_number'] 
        : null;
    $dueDate = date('d/m/Y', strtotime($receivable['due_date']));
    $amount = 'R$ ' . number_format($receivable['amount'], 2, ',', '.');
    
    $text = "Olá, {$customerName}!\n\n";
    $text .= "Seus documentos fiscais estão disponíveis para download.\n\n";
    $text .= "DETALHES DA COBRANÇA:\n";
    $text .= "Documento: {$documentNumber}\n";
    
    if ($invoiceNumber) {
        $text .= "Nota Fiscal: {$invoiceNumber}\n";
    }
    
    $text .= "Vencimento: {$dueDate}\n";
    $text .= "Valor: {$amount}\n\n";
    $text .= "Acesse seus documentos em:\n";
    $text .= "{$accessUrl}\n\n";
    $text .= "IMPORTANTE: Este link é exclusivo e expira em 15 dias. Não compartilhe com terceiros.\n\n";
    $text .= "---\n";
    $text .= SENDGRID_FROM_NAME . "\n";
    $text .= "Este é um email automático, não responda.";
    
    return $text;
}