<?php
// api/core/mailer.php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once ROOT_PATH . 'vendor/autoload.php';
require_once ROOT_PATH . 'admin/backend/init.php';
function sendMail(
    array|string $to,
    string $subject,
    array $content,
    array $attachments = [],
    string $lang = 'id'
): array {

    $config = require ROOT_PATH . 'api/config/mail.php';
    $mail = new PHPMailer(true);

    // =========================
    // DEBUG TOGGLE
    // =========================
    $enableDebug = $config['smtp_debug'] ?? false;
    $debugLog = [];

    try {
        // =========================
        // SMTP CONFIG
        // =========================
        $mail->isSMTP();
        $mail->Host = $config['host'];
        $mail->SMTPAuth = true;
        $mail->Username = $config['username'];
        $mail->Password = $config['password'];
        $mail->SMTPSecure = $config['secure'];
        $mail->Port = $config['port'];

        if ($enableDebug) {
            $mail->SMTPDebug = 2;
            $mail->Debugoutput = function ($str, $level) use (&$debugLog) {
                $debugLog[] = "[SMTP][$level] $str";
            };
        }

        $mail->setFrom($config['from_email'], $config['from_name']);

        // =========================
        // RECIPIENTS
        // =========================
        if (is_array($to)) {
            foreach ($to as $email) {
                $mail->addAddress($email);
            }
        } else {
            $mail->addAddress($to);
        }

        // =========================
        // ATTACHMENTS
        // =========================
        foreach ($attachments as $file) {
            if (file_exists($file)) {
                $mail->addAttachment($file);
            }
        }

        // =========================
        // CONTENT
        // =========================
        $mail->isHTML(true);
        $mail->Subject = $subject;

        if (($content['type'] ?? '') === 'html') {

            $basePath = ROOT_PATH . "api/mail_templates/{$lang}/";
            $basePartial = ROOT_PATH . "api/mail_templates/partials/";

            if (!is_dir($basePath)) {
                $basePath = ROOT_PATH . "api/mail_templates/id/";
            }

            $headerPath = $basePartial . 'header.html';
            $footerPath = $basePartial . 'footer.html';
            $contentPath = $basePath . $content['template'];

            if (!file_exists($contentPath)) {
                throw new Exception('Email template tidak ditemukan');
            }

            $headerHtml = file_exists($headerPath) ? file_get_contents($headerPath) : '';
            $footerHtml = file_exists($footerPath) ? file_get_contents($footerPath) : '';
            $contentHtml = file_get_contents($contentPath);

            $html = $headerHtml . $contentHtml . $footerHtml;

            // =========================
            // DEFAULT GLOBAL PARAMS
            // =========================
            $defaultParams = [
                'LogoURL' => $config['logo_url'] ?? 'https://pbpisumut.com/public/padel_logo.jpeg',
                'CompanyName' => $config['company_name'] ?? 'PBPI Sumut',
                'CompanyAddress' => $config['company_address'] ?? 'Jl. HM. Said No.8, Perintis, Kec. Medan Tim., Kota Medan, Sumatera Utara 20232',
                'CompanyPhone' => $config['company_phone'] ?? '+62 811 677 1988',
                'CompanyEmail' => $config['company_email'] ?? 'info@pbpisumut.com',
                'CompanyWhatsapp' => '628116771988',
                'CompanyWhatsappDisplay' => '+62 811 677 1988',
                'CurrentYear' => date('Y'),
            ];

            // =========================
            // MERGE PARAMS (OVERRIDE)
            // =========================
            $finalParams = array_merge(
                $defaultParams,
                $content['params'] ?? []
            );

            foreach ($finalParams as $key => $value) {
                $html = str_replace('{{ ' . $key . ' }}', $value, $html);
            }

            // =========================
            // TRACKING PIXEL
            // =========================
            if (
                ($config['enable_tracking'] ?? false) &&
                isset($content['track_id'])
            ) {
                $html .= '<img src="https://api.domain.com/api/endpoints/track-email.php?id='
                    . htmlspecialchars($content['track_id']) .
                    '" width="1" height="1" style="display:none;" />';
            }

            $mail->Body = $html;
            $mail->AltBody = strip_tags($html);

        } else {
            $mail->Body = $content['text'] ?? '';
        }

        $result = $mail->send();

        return [
            'success' => $result,
            'debug' => $debugLog
        ];

    } catch (Throwable $e) {
        error_log('[MAILER ERROR] ' . $e->getMessage());
        return [
            'success' => false,
            'error' => $e->getMessage(),
            'debug' => $debugLog
        ];
    }
}
