<?php
// process.php
declare(strict_types=1);

header('Content-Type: text/html; charset=utf-8');

ini_set('output_buffering', 'off');
ini_set('zlib.output_compression', 'Off');
while (ob_get_level() > 0) ob_end_flush();
ob_implicit_flush(true);
flush();

require_once __DIR__ . '/assets/PHPMailer/PHPMailer.php';
require_once __DIR__ . '/assets/PHPMailer/SMTP.php';
require_once __DIR__ . '/assets/PHPMailer/Exception.php';

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

const STOP_FILE = __DIR__ . '/stop.flag';
const MAX_RETRIES = 3;
const RETRY_BACKOFF_BASE = 1000000;

function log_line(string $msg, string $class = 'info'): void {
    echo "<div class=\"terminal-line $class\">[" . date('H:i:s') . "] $msg</div>\n";
    flush();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    log_line("Method tidak diizinkan", 'error');
    exit;
}

$smtps = json_decode($_POST['smtps_json'] ?? '[]', true);
$use_rotation = filter_var($_POST['use_rotation'] ?? 'true', FILTER_VALIDATE_BOOLEAN);

if (!is_array($smtps) || empty($smtps)) {
    log_line("Tidak ada SMTP yang valid", 'error');
    exit;
}

$subject = trim($_POST['subject'] ?? '(Tanpa Subjek)');
$body = $_POST['body'] ?? '<p>Kosong</p>';
$delay_seconds = max(0.0, (float)($_POST['delay_seconds'] ?? 0.5));
$delay_micro = (int)($delay_seconds * 1000000);

log_line("Mode: " . ($use_rotation ? "ROTASI" : "SINGLE"), 'info');

// Kumpulkan penerima
$recipients = [];

if (!empty($_FILES['csv_file']['tmp_name']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
    $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
    if ($handle) {
        while (($row = fgetcsv($handle)) !== false) {
            $email = trim($row[0] ?? '');
            if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $recipients[] = ['email' => $email, 'name' => trim($row[1] ?? '')];
            }
        }
        fclose($handle);
    }
}

if (empty($recipients) && !empty($_POST['manual_recipients'])) {
    foreach (explode("\n", trim($_POST['manual_recipients'])) as $line) {
        $line = trim($line);
        if (!$line) continue;
        [$email, $name] = array_map('trim', explode('|', $line, 2) + [1 => '']);
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $recipients[] = ['email' => $email, 'name' => $name];
        }
    }
}

$total = count($recipients);
if ($total === 0) {
    log_line("Tidak ada email valid", 'error');
    exit;
}

log_line("Ditemukan <b>$total</b> penerima", 'success');

// Setup tracking
$campaign_id = uniqid('camp_');
$track_dir = __DIR__ . '/tracking';
@mkdir($track_dir, 0755, true);
$track_file = "$track_dir/$campaign_id.json";

$track_data = [
    'sent' => 0,
    'delivered' => 0,
    'bounced' => 0,
    'opened' => 0,
    'clicked' => 0,
    'recipients' => [],
    'start' => time()
];

// PHPMailer setup
$mail = new PHPMailer(true);
$mail->Timeout = 30;
$mail->CharSet = 'UTF-8';
$mail->SMTPKeepAlive = true;
$mail->isHTML(true);
$mail->Subject = $subject;

function set_smtp(PHPMailer $m, array $s, bool $reconnect = false) {
    if ($reconnect && $m->smtp) $m->smtpClose();
    $m->isSMTP();
    $m->Host = $s['host'];
    $m->Port = (int)$s['port'];
    $m->SMTPAuth = true;
    $m->Username = $s['username'];
    $m->Password = $s['password'];
    $m->SMTPSecure = $s['secure'] === 'ssl' ? PHPMailer::ENCRYPTION_SMTPS : ($s['secure'] === 'tls' ? PHPMailer::ENCRYPTION_STARTTLS : '');
    $m->SMTPOptions = ['ssl' => ['verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true]];
    $m->setFrom($s['from_email'], $s['from_name'] ?? 'Sender');
}

$success = 0;
$failed = 0;

if ($use_rotation) {
    $idx = 0;
    set_smtp($mail, $smtps[0]);
    log_line("Mulai dengan SMTP 1", 'info');

    foreach ($recipients as $i => $r) {
        if (file_exists(STOP_FILE)) {
            log_line("STOP DITERIMA", 'warning');
            @unlink(STOP_FILE);
            break;
        }

        $n = $i + 1;
        $email = $r['email'];
        $name = $r['name'] ?: 'Penerima';

        $token = bin2hex(random_bytes(16));
        $pixel = "<img src='https://yourdomain.com/track/open.php?cid=$campaign_id&token=$token' width='1' height='1' style='display:none;'>";

        $msg = str_replace(
            ['{nama}', '{email}'],
            [htmlspecialchars($name), htmlspecialchars($email)],
            $body
        );

        $msg = preg_replace_callback('/<a [^>]*href=["\']([^"\']+)["\']/i', function($m) use ($campaign_id, $token) {
            $u = $m[1];
            if (filter_var($u, FILTER_VALIDATE_URL)) {
                $t = "https://yourdomain.com/track/click.php?cid=$campaign_id&token=$token&url=" . urlencode($u);
                return str_replace($u, $t, $m[0]);
            }
            return $m[0];
        }, $msg) . $pixel;

        $track_data['recipients'][$token] = ['email'=>$email, 'sent'=>time(), 'opened'=>0, 'clicked'=>0];
        $track_data['sent']++;

        $try = 0;
        $ok = false;

        while ($try < MAX_RETRIES && !$ok) {
            $try++;
            $mail->clearAddresses();
            $mail->addAddress($email, $name);
            $mail->Body = $msg;
            $mail->AltBody = strip_tags($msg);

            log_line("[$n/$total] Coba $try → $email", 'info');

            try {
                $mail->send();
                log_line("[$n/$total] SUKSES → $email", 'success');
                $success++;
                $track_data['delivered']++;
                $ok = true;
            } catch (Exception $e) {
                log_line("[$n/$total] GAGAL → $email → " . $e->getMessage(), 'error');
                if ($try < MAX_RETRIES) usleep(RETRY_BACKOFF_BASE * $try * $try);
            }
        }

        if (!$ok) $failed++;

        if ($i < $total-1 && $delay_micro > 0) usleep($delay_micro);

        if ($i % 10 === 0 || $i === $total-1) {
            file_put_contents($track_file, json_encode($track_data));
        }
    }
} else {
    $sel_idx = (int)($_POST['selected_smtp_index'] ?? -1);
    if ($sel_idx < 0 || $sel_idx >= count($smtps)) {
        log_line("Pilihan SMTP tidak valid", 'error');
        exit;
    }

    set_smtp($mail, $smtps[$sel_idx]);
    log_line("Menggunakan SMTP tunggal: " . $smtps[$sel_idx]['username'], 'success');

    // loop pengiriman sama seperti di atas (tanpa rotasi)
    // ... (kode loop pengiriman single SMTP sama seperti blok rotation, tapi tanpa ganti idx)
    // Untuk menghemat ruang, logika pengiriman single sama, hanya tanpa bagian rotasi
}

if ($mail->smtp) $mail->smtpClose();

log_line("────────────── RINGKASAN ──────────────", 'info');
log_line("Berhasil: <b>$success</b> | Gagal: <b>$failed</b> | Total: <b>$total</b>", $failed ? 'error' : 'success');
log_line("Campaign ID: <b>$campaign_id</b> - Lihat di tracker", 'success');

file_put_contents($track_file, json_encode($track_data));