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

date_default_timezone_set('Asia/Makassar');

// 1. Ambil semua konfigurasi yang diperlukan
$config_result = $koneksi->query("
    SELECT 
        (SELECT token FROM tbl_token LIMIT 1) as fonnte_token,
        (SELECT status_blokir FROM tbl_blokir LIMIT 1) as status_blokir,
        (SELECT pesan_blokir FROM tbl_blokir LIMIT 1) as pesan_blokir,
        (SELECT ippelanggan FROM tbl_penggunamikrotik LIMIT 1) as ippelanggan,
        (SELECT ip FROM tbl_mikrotik LIMIT 1) as mikrotik_ip,
        (SELECT username FROM tbl_mikrotik LIMIT 1) as mikrotik_user,
        (SELECT password FROM tbl_mikrotik LIMIT 1) as mikrotik_pass,
        (SELECT port_mikrotik FROM tbl_mikrotik LIMIT 1) as mikrotik_port
");
$config = $config_result->fetch_assoc();

// Hentikan skrip jika fitur blokir otomatis tidak aktif
if ($config['status_blokir'] !== 'aktif') {
    echo "Cron Job: Blokir otomatis tidak aktif.\n";
    exit;
}

echo "Cron Job: Blokir otomatis aktif. Mencari pelanggan...\n";

// Tentukan periode bulan dan tahun saat ini (contoh: 072025)
// Query BARU: Cari pelanggan yang jatuh temponya sudah lewat & masih punya tagihan belum lunas
$stmt = $koneksi->prepare(
    "SELECT 
        p.nama_pelanggan, p.alamat, p.no_telp, p.tgl_pemasangan, p.ip_address, p.jatuh_tempo,
        t.id_tagihan, t.jml_bayar,
        u.username, u.password_aplikasi
     FROM tb_pelanggan p
     JOIN tb_tagihan t ON p.id_pelanggan = t.id_pelanggan
     JOIN tb_user u ON p.id_pelanggan = u.id_pelanggan
     WHERE 
         p.jatuh_tempo <= CURDATE()
         AND t.status_bayar = 0
         AND t.blokir_status IS NULL"
);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo "Cron Job: Tidak ada pelanggan yang memenuhi syarat untuk diblokir saat ini.\n";
    exit;
}

echo "Cron Job: Ditemukan " . $result->num_rows . " pelanggan untuk diblokir.\n";

// 3. Sambungkan ke MikroTik
$API = new RouterosAPI();
if (!$API->connect($config['mikrotik_ip'], $config['mikrotik_user'], $config['mikrotik_pass'], $config['mikrotik_port'])) {
    echo "Cron Job: Gagal menyambung ke MikroTik. Proses dibatalkan.\n";
    exit;
}

// Siapkan statement untuk update status blokir
$stmt_update = $koneksi->prepare("UPDATE tb_tagihan SET blokir_status = 1 WHERE id_tagihan = ?");

// 4. Proses setiap pelanggan yang ditemukan
while ($data = $result->fetch_assoc()) {
    echo "Memproses: " . $data['nama_pelanggan'] . "\n";

    // --- Aksi di MikroTik ---
    if ($config['ippelanggan'] == 'statik') {
        $API->comm("/ip/firewall/address-list/add", [
            "list"    => "blocked_clients",
            "address" => $data['ip_address'],
            "comment" => "Blokir Otomatis: " . $data['nama_pelanggan']
        ]);
    } else { // Asumsi PPPoE
        $secrets = $API->comm("/ppp/secret/print", ["?name" => $data['username']]);
        if (!empty($secrets)) {
            $API->comm("/ppp/secret/disable", [".id" => $secrets[0]['.id']]);
            $active_sessions = $API->comm("/ppp/active/print", ["?name" => $data['username']]);
            if (!empty($active_sessions)) {
                $API->comm("/ppp/active/remove", [".id" => $active_sessions[0]['.id']]);
            }
        }
    }

    // --- Update status blokir di database ---
    $stmt_update->bind_param("i", $data['id_tagihan']);
    $stmt_update->execute();

    // --- Persiapan dan Pengiriman Notifikasi WhatsApp ---
    $pesan_template = $config['pesan_blokir'];
    $placeholders = ['$nama', '$alamat', '$username', '$password', '$tgl_pemasangan', '$jatuh_tempo', '$harinin', '$tagihan'];
    $values = [
        $data['nama_pelanggan'],
        $data['alamat'],
        $data['username'],
        $data['password_aplikasi'],
        date('d F Y', strtotime($data['tgl_pemasangan'])),
        date('d F Y', strtotime($data['jatuh_tempo'])), // Mengambil jatuh tempo personal
        date('d F Y, H:i') . ' WITA',
        'Rp ' . number_format($data['jml_bayar'], 0, ",", ".")
    ];
    $pesan_final = str_replace($placeholders, $values, $pesan_template);
    // --- KODE DEBUGGING UNTUK LOGGING ---
    $log_file = 'debug_whatsapp.log';
    $log_message = "[" . date('Y-m-d H:i:s') . "] Pesan yang dibuat untuk " . $data['no_telp'] . ":\n" . $pesan_final . "\n-----------------\n";
    file_put_contents($log_file, $log_message, FILE_APPEND);
    // --- AKHIR KODE DEBUGGING ---
    // Kirim ke WhatsApp
    $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: ' . $config['fonnte_token']],
    ]);
    curl_exec($curl);
    curl_close($curl);
}

// 5. Tutup semua koneksi
$stmt->close();
$stmt_update->close();
$API->disconnect();
$koneksi->close();

echo "Cron Job Selesai.\n";
