<?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.no_telp, p.ip_address, p.jatuh_tempo,
        t.jml_bayar,
        u.username
     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 Buka 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();

$bukaBlokirBerhasil = false;

if ($mikrotik_data) {
    $API = new RouterosAPI();
    if ($API->connect($mikrotik_data['ip'], $mikrotik_data['username'], $mikrotik_data['password'])) {
        if ($config_data['ippelanggan'] === 'statik') {
            // Cari dan hapus dari address-list
            $commentToSearch = "Blokir Manual: " . $data_lengkap['nama_pelanggan']; // Sesuaikan dengan comment saat blokir
            $lists = $API->comm("/ip/firewall/address-list/print", ["?comment" => $commentToSearch]);
            if (!empty($lists)) {
                $API->comm("/ip/firewall/address-list/remove", [".id" => $lists[0]['.id']]);
            }
        } else { // Asumsi PPPoE
            // Aktifkan kembali user PPPoE
            $secrets = $API->comm("/ppp/secret/print", ["?name" => $data_lengkap['username']]);
            if (!empty($secrets)) {
                $API->comm("/ppp/secret/enable", [".id" => $secrets[0]['.id']]);
            }
        }
        $bukaBlokirBerhasil = true;
        $API->disconnect();
    }
}

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

// 5. Kirim Notifikasi WhatsApp
$notif_q = $koneksi->query("SELECT pesan_bukablokir FROM tbl_bukablokir 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 ($bukaBlokirBerhasil && $notif_data && $token_data) {
    $pesan_template = $notif_data['pesan_bukablokir'];
    $placeholders = ['$nama', '$harinin', '$tagihan', '$jatuh_tempo'];
    $values = [
        $data_lengkap['nama_pelanggan'],
        date('d F Y, H:i') . ' WITA',
        'Rp ' . number_format($data_lengkap['jml_bayar'], 0, ",", "."),
        date('d F Y', strtotime($data_lengkap['jatuh_tempo']))
    ];
    $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 ($bukaBlokirBerhasil) {
    echo json_encode([
        "status" => "success",
        "message" => "Blokir pelanggan berhasil dibuka dan notifikasi terkirim."
    ]);
} else {
    echo json_encode([
        "status" => "error",
        "message" => "Gagal membuka blokir pelanggan di MikroTik."
    ]);
}

$koneksi->close();
?>
