<?php
// Pastikan path ke file-file ini sudah benar
include('../../include/routeros_api.php');
include "../../include/koneksi.php";

// Pastikan hanya admin yang bisa mengakses
session_start();
if (!isset($_SESSION['admin'])) {
    // Arahkan ke halaman login jika bukan admin
    header("Location: login.php");
    exit();
}

// Ambil ID tagihan dari URL
$id_tagihan = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id_tagihan === 0) {
    die("Error: ID Tagihan tidak valid.");
}

// 1. Ambil data lengkap tagihan & pelanggan menggunakan prepared statement
$stmt_data = $koneksi->prepare(
    "SELECT 
        p.id_pelanggan, p.nama_pelanggan, p.ip_address, p.paket, p.no_telp, 
        u.username, 
        t.jml_bayar, 
        pk.nama_paket
     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
     JOIN tb_paket pk ON p.paket = pk.id_paket
     WHERE t.id_tagihan = ?"
);
$stmt_data->bind_param("i", $id_tagihan);
$stmt_data->execute();
$result_data = $stmt_data->get_result();
$data = $result_data->fetch_assoc();
$stmt_data->close();

if (!$data) {
    die("Error: Data tagihan tidak ditemukan.");
}

$id_pelanggan = $data['id_pelanggan'];
$jml_bayar = $data['jml_bayar'];

// 2. Proses buka blokir di MikroTik
$mikrotik_q = $koneksi->query("SELECT * FROM tbl_mikrotik WHERE id_mikrotik = 1");
$mikrotik_data = $mikrotik_q->fetch_assoc();
$config_pelanggan_q = $koneksi->query("SELECT * FROM tbl_penggunamikrotik");
$config_pelanggan = $config_pelanggan_q->fetch_assoc();

if ($mikrotik_data) {
    $API = new RouterosAPI();
    if ($API->connect($mikrotik_data['ip'], $mikrotik_data['username'], $mikrotik_data['password'])) {
        if ($config_pelanggan['ippelanggan'] == 'statik') {
            $commentToSearch = "Blokir Otomatis: " . $data['nama_pelanggan'];
            $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
            $secrets = $API->comm("/ppp/secret/print", ["?name" => $data['username']]);
            if (!empty($secrets)) {
                $API->comm("/ppp/secret/enable", [".id" => $secrets[0]['.id']]);
            }
        }
        $API->disconnect();
    }
}

// 3. Generate Nomor Invoice Baru
$sql_inv = $koneksi->query("SELECT no_invoice FROM tb_tagihan WHERE no_invoice IS NOT NULL ORDER BY no_invoice DESC LIMIT 1");
$data_inv = $sql_inv->fetch_assoc();
$no_spt = $data_inv ? $data_inv['no_invoice'] : '00000.BLR.MST.';
$urut = (int)substr($no_spt, 0, 5);
$tambah = $urut + 1;
$format_invoice = str_pad($tambah, 5, '0', STR_PAD_LEFT) . ".BLR.MST.";

// 4. Logika Inti: Update status & Hitung jatuh tempo baru
$tanggal_bayar = date('Y-m-d');

// Update status tagihan menjadi LUNAS
$stmt_tagihan = $koneksi->prepare("UPDATE tb_tagihan SET status_bayar=1, terbayar=?, tgl_bayar=?, waktu_bayar=NOW(), blokir_status=NULL, no_invoice=? WHERE id_tagihan=?");
$stmt_tagihan->bind_param("sssi", $jml_bayar, $tanggal_bayar, $format_invoice, $id_tagihan);
$stmt_tagihan->execute();
$isSuccess = $stmt_tagihan->affected_rows > 0;
$stmt_tagihan->close();

// Hitung tanggal jatuh tempo berikutnya
$jatuh_tempo_berikutnya = date('Y-m-d', strtotime('+35 days', strtotime($tanggal_bayar)));

// Update tanggal jatuh tempo baru ke tabel pelanggan
$stmt_pelanggan = $koneksi->prepare("UPDATE tb_pelanggan SET jatuh_tempo = ? WHERE id_pelanggan = ?");
$stmt_pelanggan->bind_param("si", $jatuh_tempo_berikutnya, $id_pelanggan);
$stmt_pelanggan->execute();
$stmt_pelanggan->close();

// Masukkan ke buku kas
$ket_kas = "Pembayaran Internet AN. " . $data['nama_pelanggan'] . ", Paket " . $data['nama_paket'];
$stmt_kas = $koneksi->prepare("INSERT INTO tb_kas (tgl_kas, keterangan, penerimaan, id_tagihan) SELECT ?, ?, ?, ? FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM tb_kas WHERE id_tagihan = ?)");
$stmt_kas->bind_param("ssiii", $tanggal_bayar, $ket_kas, $jml_bayar, $id_tagihan, $id_tagihan);
$stmt_kas->execute();
$stmt_kas->close();

// 5. Kirim Notifikasi Pembayaran Berhasil
if ($isSuccess) {
    $notif_q = $koneksi->query("SELECT pesan_bayar FROM tbl_notifbayar 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 ($notif_data && $token_data) {
        $pesan_template = $notif_data['pesan_bayar'];
        $placeholders = ['$nama', '$harinin', '$no_telp', '$jatuh_tempo', '$tagihan'];
        $values = [
            $data['nama_pelanggan'],
            date('d F Y, H:i') . ' WITA',
            $data['no_telp'],
            date('d F Y', strtotime($jatuh_tempo_berikutnya)),
            'Rp ' . number_format($data['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['no_telp'], 'message' => $pesan_final, 'countryCode' => '62'],
            CURLOPT_HTTPHEADER => ['Authorization: ' . $token_data['token']],
        ]);
        curl_exec($curl);
        curl_close($curl);
    }
}

// 6. Tampilkan notifikasi sukses di halaman admin
if ($isSuccess) {
    echo "
        <script>
            setTimeout(function() {
                swal({
                    title: 'Tagihan',
                    text: 'Berhasil Dibayar!',
                    type: 'success'
                }, function() {
                    window.location = '?page=transaksi';
                });
            }, 300);
        </script>
    ";
} else {
    echo "
        <script>
            setTimeout(function() {
                swal({
                    title: 'Informasi',
                    text: 'Tagihan ini sudah pernah dibayar sebelumnya.',
                    type: 'info'
                }, function() {
                    window.location = '?page=transaksi';
                });
            }, 300);
        </script>
    ";
}

$koneksi->close();
?>
