<?php
require("../../include/routeros_api.php");
include("../../include/koneksi.php");

header('Content-Type: application/json');
date_default_timezone_set('Asia/Makassar');

// 1. Ambil Data & Validasi
$id_tagihan = isset($_GET['id_tagihan']) ? (int)$_GET['id_tagihan'] : 0;
if ($id_tagihan === 0) {
    echo json_encode(["status" => "error", "message" => "ID Tagihan tidak valid."]);
    exit;
}

// 2. Ambil semua data yang diperlukan dalam satu query
$stmt = $koneksi->prepare(
    "SELECT 
        p.nama_pelanggan, p.alamat, p.no_telp, p.tgl_pemasangan, p.ip_address, p.jatuh_tempo,
        t.jml_bayar,
        u.username, u.password_aplikasi
     FROM tb_tagihan t
     JOIN tb_pelanggan p ON t.id_pelanggan = p.id_pelanggan
     JOIN tb_user u ON p.id_pelanggan = u.id_pelanggan
     WHERE t.id_tagihan = ?"
);
$stmt->bind_param("i", $id_tagihan);
$stmt->execute();
$result = $stmt->get_result();
$data_lengkap = $result->fetch_assoc();
$stmt->close();

if (!$data_lengkap) {
    echo json_encode(["status" => "error", "message" => "Data pelanggan atau tagihan tidak ditemukan."]);
    exit;
}

// 3. Logika Blokir MikroTik
$mikrotik_q = $koneksi->query("SELECT * FROM tbl_mikrotik LIMIT 1");
$mikrotik_data = $mikrotik_q->fetch_assoc();
$config_q = $koneksi->query("SELECT ippelanggan FROM tbl_penggunamikrotik LIMIT 1");
$config_data = $config_q->fetch_assoc();

$blokirBerhasil = false;

if ($mikrotik_data) {
    $API = new RouterosAPI();
    if ($API->connect($mikrotik_data['ip'], $mikrotik_data['username'], $mikrotik_data['password'])) {
        if ($config_data['ippelanggan'] === 'statik') {
            $API->comm("/ip/firewall/address-list/add", [
                "list"    => "blocked_clients",
                "address" => $data_lengkap['ip_address'],
                "comment" => "Blokir Manual: " . $data_lengkap['nama_pelanggan']
            ]);
        } else { // Asumsi PPPoE
            $secrets = $API->comm("/ppp/secret/print", ["?name" => $data_lengkap['username']]);
            if (!empty($secrets)) {
                $API->comm("/ppp/secret/disable", [".id" => $secrets[0]['.id']]);
                
                $active = $API->comm("/ppp/active/print", ["?name" => $data_lengkap['username']]);
                if (!empty($active)) {
                    $API->comm("/ppp/active/remove", [".id" => $active[0]['.id']]);
                }
            }
        }
        $blokirBerhasil = true;
        $API->disconnect();
    }
}

// 4. Update status blokir di database
if ($blokirBerhasil) {
    $koneksi->query("UPDATE tb_tagihan SET blokir_status = 1 WHERE id_tagihan = $id_tagihan");
}

// 5. Kirim Notifikasi WhatsApp
$notif_q = $koneksi->query("SELECT pesan_blokir FROM tbl_blokir LIMIT 1");
$notif_data = $notif_q->fetch_assoc();
$token_q = $koneksi->query("SELECT token FROM tbl_token LIMIT 1");
$token_data = $token_q->fetch_assoc();

if ($blokirBerhasil && $notif_data && $token_data) {
    $pesan_template = $notif_data['pesan_blokir'];
    $placeholders = ['$nama', '$alamat', '$username', '$password', '$tgl_pemasangan', '$jatuh_tempo', '$harinin', '$tagihan'];
    $values = [
        $data_lengkap['nama_pelanggan'],
        $data_lengkap['alamat'],
        $data_lengkap['username'],
        $data_lengkap['password_aplikasi'],
        date('d F Y', strtotime($data_lengkap['tgl_pemasangan'])),
        date('d F Y', strtotime($data_lengkap['jatuh_tempo'])),
        date('d F Y, H:i') . ' WITA',
        'Rp ' . number_format($data_lengkap['jml_bayar'], 0, ",", ".")
    ];
    $pesan_final = str_replace($placeholders, $values, $pesan_template);

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => 'https://api.fonnte.com/send',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => ['target' => $data_lengkap['no_telp'], 'message' => $pesan_final, 'countryCode' => '62'],
        CURLOPT_HTTPHEADER => ['Authorization: ' . $token_data['token']],
    ]);
    curl_exec($curl);
    curl_close($curl);
}

// 6. Kirim respons JSON kembali ke halaman
if ($blokirBerhasil) {
    echo json_encode([
        "status" => "success",
        "message" => "Pelanggan berhasil diblokir dan notifikasi terkirim."
    ]);
} else {
    echo json_encode([
        "status" => "error",
        "message" => "Gagal memblokir pelanggan di MikroTik."
    ]);
}

$koneksi->close();
?>
