<?php
require_once '../config.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $nama_lengkap = trim($_POST['nama_lengkap']);
        $asal_instansi = trim($_POST['asal_instansi']);
        $no_wa = trim($_POST['no_wa']);
        $email = trim($_POST['email']);
        $alamat = trim($_POST['alamat']);
        $kecamatan = trim($_POST['kecamatan']);
        $kota = trim($_POST['kota']);
        $provinsi = trim($_POST['provinsi']);
        $tujuan = trim($_POST['tujuan']);
        $catatan = trim($_POST['catatan']);

        // Format WA Number to 628...
        if (substr($no_wa, 0, 1) == '0') {
            $no_wa = '62' . substr($no_wa, 1);
        }

        // Handle File Upload (Anti-Deface)
        $file_lampiran = '';
        if (isset($_FILES['file_lampiran']) && $_FILES['file_lampiran']['error'] == 0) {
            $allowed = ['pdf', 'jpg', 'jpeg', 'png'];
            $filename = $_FILES['file_lampiran']['name'];
            $file_ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            $filesize = $_FILES['file_lampiran']['size'];

            // Pengecekan MIME Type & Ekstensi (Keamanan)
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $_FILES['file_lampiran']['tmp_name']);
            finfo_close($finfo);

            $allowed_mimes = ['application/pdf', 'image/jpeg', 'image/png'];

            if (!in_array($file_ext, $allowed) || !in_array($mime, $allowed_mimes)) {
                throw new Exception('Format file tidak diizinkan atau file terdeteksi berbahaya.');
            }
            if ($filesize > 2097152) { // 2MB
                throw new Exception('Ukuran file maksimal 2MB.');
            }

            // Rename file acak mencegah eksekusi
            $new_filename = time() . '_' . bin2hex(random_bytes(8)) . '.' . $file_ext;
            $upload_path = '../uploads/' . $new_filename;
            
            if (!move_uploaded_file($_FILES['file_lampiran']['tmp_name'], $upload_path)) {
                throw new Exception('Gagal mengunggah file.');
            }
            $file_lampiran = $new_filename;
        } else {
            throw new Exception('Harap unggah file lampiran.');
        }

        // Generate Ticket Number
        $today = date('Ymd');
        $stmt_last = $pdo->prepare("SELECT no_tiket FROM tbl_pengajuan WHERE no_tiket LIKE ? ORDER BY id DESC LIMIT 1");
        $stmt_last->execute(["T-$today-%"]);
        $last_ticket = $stmt_last->fetch();

        if ($last_ticket) {
            $last_num = intval(substr($last_ticket->no_tiket, -4));
            $new_num = str_pad($last_num + 1, 4, '0', STR_PAD_LEFT);
        } else {
            $new_num = '0001';
        }
        $no_tiket = "T-$today-$new_num";

        // Insert to DB (Prepared Statements Anti SQL-Injection)
        $stmt = $pdo->prepare("INSERT INTO tbl_pengajuan (no_tiket, nama_lengkap, asal_instansi, no_telp, email, alamat, kecamatan, kota, provinsi, tujuan, file_lampiran, catatan, status) 
                               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'diterima')");
        $stmt->execute([
            $no_tiket, $nama_lengkap, $asal_instansi, $no_wa, $email, $alamat, $kecamatan, $kota, $provinsi, $tujuan, $file_lampiran, $catatan
        ]);

        // ==========================
        // Kirim Notifikasi via DB Template
        // ==========================
        $link_track = base_url("client/track.php?tiket=$no_tiket");

        // WA
        $tpl_wa = getSetting($pdo, 'tpl_wa_baru');
        if (empty(trim($tpl_wa))) {
            $tpl_wa = "Halo [NAMA],\n\nPengajuan Anda telah kami terima.\nNo Tiket: *[TIKET]*\nStatus: *[STATUS]*\n\nPantau status pengajuan Anda melalui link berikut:\n[LINK_TRACKING]\n\nTerima kasih.";
        }
        $tpl_wa = str_replace('[NAMA]', $nama_lengkap, $tpl_wa);
        $tpl_wa = str_replace('[TIKET]', $no_tiket, $tpl_wa);
        $tpl_wa = str_replace('[TUJUAN]', $tujuan, $tpl_wa);
        $tpl_wa = str_replace('[STATUS]', 'DITERIMA ( Berkas Masuk )', $tpl_wa);
        $tpl_wa = str_replace('[LINK_TRACKING]', $link_track, $tpl_wa);
        @sendWhatsApp($no_wa, $tpl_wa);

        // Email
        $tpl_email = getSetting($pdo, 'tpl_email_baru');
        if (empty(trim($tpl_email))) {
            $tpl_email = "<h3>Halo [NAMA],</h3><p>Pengajuan Anda telah kami terima.</p><ul><li><b>No Tiket:</b> [TIKET]</li><li><b>Status:</b> [STATUS]</li></ul><p>Pantau status pengajuan Anda melalui link berikut: <a href=\"[LINK_TRACKING]\">Cek Status Pengajuan</a></p>";
        }
        $tpl_email = str_replace('[NAMA]', htmlspecialchars($nama_lengkap), $tpl_email);
        $tpl_email = str_replace('[TIKET]', htmlspecialchars($no_tiket), $tpl_email);
        $tpl_email = str_replace('[TUJUAN]', htmlspecialchars($tujuan), $tpl_email);
        $tpl_email = str_replace('[STATUS]', 'DITERIMA ( Berkas Masuk )', $tpl_email);
        $tpl_email = str_replace('[LINK_TRACKING]', $link_track, $tpl_email);
        $email_subj = "Pengajuan Baru - $no_tiket";
        @sendEmail($email, $email_subj, $tpl_email);

        echo json_encode([
            'status' => 'success',
            'no_tiket' => $no_tiket,
            'message' => 'Pengajuan berhasil dikirim.'
        ]);

    } catch (Exception $e) {
        echo json_encode([
            'status' => 'error',
            'message' => $e->getMessage()
        ]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid Request']);
}
?>
