<?php
/**
 * SAC 2026 - MASTER MAILER ENGINE v20.0 (RESEND + TELEGRAM)
 * Arquitecto: Andres Mathison
 * Soporta: Mensajería Masiva, Individual y Avisos de Cobro.
 * MODIFICACIÓN NUCLEAR: Mejora estética y corrección de versión 2026.
 */
require_once __DIR__ . '/config.php';

if (ob_get_length()) ob_clean();

/**
 * Función Maestra de Envío vía RESEND API
 */
function sendEmailResend($to, $subject, $htmlContent) {
    $apiKey = "re_M4DYa3iV_2wy7bG7EnU3LCH6yRX681BS1";
    $url = "https://api.resend.com/emails";
    
    // Remitente verificado tras configuración DNS
    $from = "Administración El Tejar <tejaradministracion@tecnomath.com>"; 
    
    $payload = [
        "from" => $from,
        "to" => [$to],
        "subject" => $subject,
        "html" => $htmlContent
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $apiKey",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) return ["success" => false, "message" => "CURL Error: " . $error];

    return [
        "success" => ($httpCode === 200 || $httpCode === 201),
        "response" => json_decode($response, true),
        "code" => $httpCode
    ];
}

/**
 * Envío a Telegram con Formato Enriquecido
 */
function sendTelegramSafe($chatId, $text) {
    $token = "8201949320:AAGGJtbYzhYJFV6zXPensEToIbwtah7aTVs";
    $url = "https://api.telegram.org/bot$token/sendMessage";
    $payload = ['chat_id' => $chatId, 'text' => $text, 'parse_mode' => 'Markdown'];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

/**
 * Plantilla HTML Premium SAC 2026 para Avisos de Cobro
 */
function getFeeTemplate($name, $unit, $amount, $month, $year, $status) {
    $portalUrl = DOMAIN . BASE_PATH;
    $colorStatus = ($status === 'Pagado') ? '#10b981' : '#ef4444';
    
    return "
    <div style='font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif; background-color: #f1f5f9; padding: 40px 10px; color: #1e293b;'>
        <div style='max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 32px; overflow: hidden; border: 1px solid #e2e8f0; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);'>
            <div style='background: #0f172a; padding: 45px 20px; text-align: center; border-bottom: 8px solid #2563eb;'>
                <div style='font-size: 10px; font-weight: 900; color: #60a5fa; text-transform: uppercase; letter-spacing: 5px; margin-bottom: 10px;'>Plataforma Administrativa</div>
                <h1 style='color: #ffffff; margin: 0; font-size: 32px; font-weight: 900; letter-spacing: -1px;'>SAC <span style='color: #2563eb;'>2026</span></h1>
                <p style='color: #94a3b8; margin: 10px 0 0; font-size: 14px; font-weight: bold;'>CONDOMINIO EL TEJAR</p>
            </div>
            <div style='padding: 50px;'>
                <p style='font-size: 18px; color: #0f172a;'>Estimado(a) <b>$name</b>,</p>
                <p style='line-height: 1.8; color: #475569; font-size: 16px;'>Le informamos que el recibo de condominio para la unidad <b>$unit</b> correspondiente al periodo <b>$month $year</b> ha sido emitido satisfactoriamente.</p>
                
                <div style='background: #f8fafc; padding: 35px; border-radius: 24px; margin: 30px 0; text-align: center; border: 2px solid #f1f5f9;'>
                    <p style='margin: 0; color: #64748b; font-size: 11px; font-weight: 900; text-transform: uppercase; letter-spacing: 2px;'>Monto a Liquidar</p>
                    <p style='margin: 10px 0; font-size: 48px; font-weight: 900; color: #1e293b; letter-spacing: -2px;'>$ $amount <span style='font-size: 16px; color: #94a3b8; font-weight: normal;'>USD</span></p>
                    <div style='display: inline-block; padding: 6px 20px; background-color: $colorStatus; color: #ffffff; border-radius: 10px; font-size: 10px; font-weight: 900; text-transform: uppercase;'>$status</div>
                </div>

                <div style='text-align: center; margin: 40px 0;'>
                    <a href='$portalUrl' style='background: #2563eb; color: #ffffff; padding: 20px 45px; border-radius: 18px; text-decoration: none; font-weight: 900; font-size: 14px; display: inline-block; box-shadow: 0 10px 15px -3px rgba(37, 99, 235, 0.4); text-transform: uppercase; letter-spacing: 1px;'>Reportar Pago Ahora</a>
                </div>
                
                <p style='font-size: 12px; color: #94a3b8; line-height: 1.6; text-align: center;'>Recuerde que el mantenimiento de nuestras áreas comunes depende de su puntualidad. ¡Gracias por ser un vecino responsable!</p>
            </div>
            <div style='background: #f8fafc; padding: 30px; text-align: center; border-top: 1px solid #f1f5f9;'>
                <p style='margin: 0; font-size: 10px; color: #94a3b8; font-weight: bold; text-transform: uppercase; letter-spacing: 1px;'>&copy; 2026 Condominio El Tejar | Powered by TecnoMath</p>
            </div>
        </div>
    </div>";
}

/**
 * Plantilla HTML Premium SAC 2026 para Acuses de Recibo de Pago
 */
function getReceiptTemplate($name, $unit, $amount, $paid, $month, $year, $status, $balance) {
    $colorStatus = ($status === 'Solvente') ? '#10b981' : '#f59e0b';
    $statusIcon = ($status === 'Solvente') ? '✅' : '⚠️';
    
    return "
    <div style='font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif; background-color: #f8fafc; padding: 40px 10px; color: #1e293b;'>
        <div style='max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 32px; overflow: hidden; border: 1px solid #e2e8f0; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);'>
            <div style='background: #0f172a; padding: 40px 20px; text-align: center; border-bottom: 8px solid #10b981;'>
                <div style='font-size: 10px; font-weight: 900; color: #10b981; text-transform: uppercase; letter-spacing: 5px; margin-bottom: 10px;'>Acuse de Recibo Digital</div>
                <h1 style='color: #ffffff; margin: 0; font-size: 28px; font-weight: 900; letter-spacing: -1px;'>SAC <span style='color: #10b981;'>2026</span></h1>
                <p style='color: #94a3b8; margin: 10px 0 0; font-size: 12px; font-weight: bold;'>CONDOMINIO EL TEJAR</p>
            </div>
            <div style='padding: 40px;'>
                <div style='margin-bottom: 30px; border-bottom: 1px solid #f1f5f9; padding-bottom: 20px;'>
                    <p style='margin: 0; color: #64748b; font-size: 10px; font-weight: 900; text-transform: uppercase;'>Propietario</p>
                    <p style='margin: 5px 0 0; font-size: 18px; font-weight: 900; color: #0f172a;'>$name</p>
                    <p style='margin: 10px 0 0; color: #64748b; font-size: 10px; font-weight: 900; text-transform: uppercase;'>Unidad</p>
                    <p style='margin: 5px 0 0; font-size: 16px; font-weight: 900; color: #2563eb;'>$unit</p>
                </div>

                <div style='display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 30px;'>
                    <div style='background: #f8fafc; padding: 20px; border-radius: 20px; text-align: center;'>
                        <p style='margin: 0; color: #64748b; font-size: 9px; font-weight: 900; text-transform: uppercase;'>Monto Cuota</p>
                        <p style='margin: 5px 0 0; font-size: 20px; font-weight: 900; color: #1e293b;'>$ $amount</p>
                    </div>
                    <div style='background: #ecfdf5; padding: 20px; border-radius: 20px; text-align: center;'>
                        <p style='margin: 0; color: #059669; font-size: 9px; font-weight: 900; text-transform: uppercase;'>Monto Pagado</p>
                        <p style='margin: 5px 0 0; font-size: 20px; font-weight: 900; color: #047857;'>$ $paid</p>
                    </div>
                </div>

                <div style='background: #0f172a; padding: 30px; border-radius: 24px; text-align: center; color: #ffffff;'>
                    <p style='margin: 0; color: #94a3b8; font-size: 10px; font-weight: 900; text-transform: uppercase; letter-spacing: 2px;'>Estatus de Solvencia</p>
                    <p style='margin: 10px 0; font-size: 32px; font-weight: 900; color: #ffffff;'>$statusIcon $status</p>
                    <p style='margin: 0; font-size: 12px; color: #60a5fa;'>Periodo: $month $year</p>
                </div>

                " . ($balance > 0 ? "
                <div style='margin-top: 20px; padding: 15px; background: #fff7ed; border: 1px solid #ffedd5; border-radius: 15px; text-align: center;'>
                    <p style='margin: 0; color: #c2410c; font-size: 12px; font-weight: bold;'>Deuda Pendiente: $ $balance USD</p>
                </div>" : "
                <div style='margin-top: 20px; padding: 15px; background: #f0fdf4; border: 1px solid #dcfce7; border-radius: 15px; text-align: center;'>
                    <p style='margin: 0; color: #15803d; font-size: 12px; font-weight: bold;'>✨ Propiedad totalmente solvente</p>
                </div>") . "

                <p style='margin-top: 40px; font-size: 11px; color: #94a3b8; line-height: 1.6; text-align: center;'>Este documento sirve como comprobante oficial de recepción de fondos. Para cualquier duda, contacte a la administración.</p>
            </div>
            <div style='background: #f8fafc; padding: 25px; text-align: center; border-top: 1px solid #f1f5f9;'>
                <p style='margin: 0; font-size: 9px; color: #94a3b8; font-weight: 900; text-transform: uppercase; letter-spacing: 1px;'>Kernel V4.1.85 MC/MB • SAC 2026 • TecnoMath</p>
            </div>
        </div>
    </div>";
}

/**
 * Plantilla HTML Premium SAC 2026 para Mensajes Libres
 */
function getCustomTemplate($title, $content) {
    return "
    <div style='font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif; background-color: #f8fafc; padding: 40px 10px; color: #1e293b;'>
        <div style='max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 32px; overflow: hidden; border: 1px solid #e2e8f0; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);'>
            <div style='background: #1e293b; padding: 40px; text-align: center; border-bottom: 8px solid #2563eb;'>
                <h1 style='color: #ffffff; margin: 0; font-size: 24px; font-weight: 900; letter-spacing: 1px; text-transform: uppercase;'>Comunicado Oficial</h1>
                <p style='color: #60a5fa; margin: 5px 0 0; font-size: 11px; font-weight: bold; letter-spacing: 3px;'>SAC 2026 - EL TEJAR</p>
            </div>
            <div style='padding: 50px;'>
                <h2 style='font-size: 24px; color: #0f172a; margin-bottom: 25px; font-weight: 900; tracking-tighter;'>$title</h2>
                <div style='line-height: 1.8; color: #475569; font-size: 16px; white-space: pre-wrap; background: #f8fafc; padding: 30px; border-radius: 20px; border-left: 5px solid #2563eb;'>$content</div>
            </div>
            <div style='background: #f1f5f9; padding: 25px; text-align: center;'>
                <p style='margin: 0; font-size: 9px; color: #94a3b8; font-weight: 900; text-transform: uppercase;'>Enviado mediante el Sistema de Gestión Integral SAC 2026</p>
            </div>
        </div>
    </div>";
}

/**
 * PROCESAMIENTO DE PETICIONES POST
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && basename($_SERVER['PHP_SELF']) == 'mailer.php') {
    header("Content-Type: application/json; charset=UTF-8");
    $data = json_decode(file_get_contents("php://input"), true);
    
    if (!$data || !isset($data['recipients'])) {
        echo json_encode(["status" => "error", "message" => "Datos incompletos"]);
        exit;
    }

    $channel = $data['channel'] ?? 'email';
    $results = ["sent" => 0, "failed" => 0];

    foreach ($data['recipients'] as $recipient) {
        if ($data['messageType'] === 'fee') {
            $html = getFeeTemplate($recipient['name'], $recipient['propName'], $recipient['amount'], $data['monthName'], $data['year'], $recipient['status']);
            $subject = "Aviso de Cobro SAC 2026: " . $data['monthName'] . " " . $data['year'];
            
            $tgText = "💰 *AVISO DE COBRO SAC 2026*\n\n";
            $tgText .= "Hola *".$recipient['name']."*,\n\n";
            $tgText .= "Se ha emitido su recibo de condominio:\n";
            $tgText .= "🏢 *Unidad:* `".$recipient['propName']."`\n";
            $tgText .= "📅 *Periodo:* ".$data['monthName']." ".$data['year']."\n";
            $tgText .= "💵 *Monto:* `$ ".$recipient['amount']." USD`\n";
            $tgText .= "📌 *Estatus:* ".$recipient['status']."\n\n";
            $tgText .= "🌐 [ACCEDER AL PORTAL](" . DOMAIN . BASE_PATH . ")";
        } elseif ($data['messageType'] === 'receipt') {
            $html = getReceiptTemplate($recipient['name'], $recipient['propName'], $recipient['amount'], $recipient['paid'], $data['monthName'], $data['year'], $recipient['status'], $recipient['balance']);
            $subject = "Acuse de Recibo SAC 2026: " . $data['monthName'] . " " . $data['year'];
            
            $tgText = "📄 *ACUSE DE RECIBO SAC 2026*\n\n";
            $tgText .= "Hola *".$recipient['name']."*,\n\n";
            $tgText .= "Se ha procesado su pago correctamente:\n";
            $tgText .= "🏢 *Unidad:* `".$recipient['propName']."`\n";
            $tgText .= "📅 *Periodo:* ".$data['monthName']." ".$data['year']."\n";
            $tgText .= "💰 *Monto Cuota:* `$ ".$recipient['amount']." USD`\n";
            $tgText .= "💵 *Monto Pagado:* `$ ".$recipient['paid']." USD`\n";
            $tgText .= "----------------------------\n";
            $tgText .= "📊 *ESTATUS:* ".($recipient['status'] === 'Solvente' ? '✅ SOLVENTE' : '⚠️ PENDIENTE')."\n";
            if ($recipient['balance'] > 0) {
                $tgText .= "📉 *Deuda Restante:* `$ ".$recipient['balance']." USD`\n";
            } else {
                $tgText .= "✨ *PROPIEDAD AL DÍA*\n";
            }
            $tgText .= "\n🌐 [ACCEDER AL PORTAL](" . DOMAIN . BASE_PATH . ")\n\n";
            $tgText .= "_Gracias por su compromiso con el condominio._";
        } else {
            $content = $recipient['customMessage'] ?? $data['customMessage'] ?? "";
            $html = getCustomTemplate($data['subject'], $content);
            $subject = "📢 " . $data['subject'];
            
            $tgText = "📢 *COMUNICADO SAC 2026*\n\n";
            $tgText .= "*Asunto:* ".$data['subject']."\n";
            $tgText .= "----------------------------\n\n";
            $tgText .= $content . "\n\n";
            $tgText .= "🌐 [ACCEDER AL PORTAL](" . DOMAIN . BASE_PATH . ")\n\n";
            $tgText .= "_Atentamente, La Administración_";
        }

        if ($channel === 'email' && !empty($recipient['email'])) {
            $res = sendEmailResend($recipient['email'], $subject, $html);
            if ($res['success']) $results['sent']++; else $results['failed']++;
        } 
        elseif ($channel === 'telegram' && !empty($recipient['telegramChatId'])) {
            $res = sendTelegramSafe($recipient['telegramChatId'], $tgText);
            if (isset($res['ok']) && $res['ok']) $results['sent']++; else $results['failed']++;
        }
    }

    echo json_encode(["status" => "success", "sent" => $results['sent'], "failed" => $results['failed']]);
    exit;
}
?>