<?php
include "connect.php";
include "tanggal_indo.php";
include "whatsapp_api.php";
require('routeros_api.class.php');

$time = date('H');
$now = date('d');

try {
    // Ambil data setting
    $stmt = $pdo->prepare("SELECT * FROM profile_tagihan");
    $stmt->execute();
    $settings = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($settings as $pset) {

        $kirim = $pset['kirim_tagihan'];
        $limit = $pset['limit_tagihan'];
        $jumhari = $pset['buat_tagihan'];
        $sekarang = date('Y-m-d');
        $skr2 = strtotime($sekarang);

        // Cari Max buat tagihan
        $date91 = new DateTime($sekarang);
        $date91->add(new DateInterval('P' . $jumhari . 'D'));
        $tgl91 = $date91->format('Y-m-d');
        $sendtag1 = substr($tgl91, 0, 8) . $kirim;

        // Kurangi 1 hari dari $tgl91
        $dateKirim = new DateTime($sendtag1);
        $dateKirim->modify('-1 day'); // Mengurangi 1 hari
        $sendtag = $dateKirim->format('Y-m-d');
        $lasttime = strtotime($sendtag);

        // Cari Min buat tagihan
        $date92 = new DateTime($sendtag);
        $date92->sub(new DateInterval('P' . $jumhari . 'D'));
        $tgl92 = $date92->format('Y-m-d');
        $starttime = strtotime($tgl92);

        // echo "BUAT TAGIHAN => " . $pset['id_data_server'] . " <-> " . $pset['nama'] . " Start : " . $tgl92 . " - Last : " . $sendtag . "<br><br>";
        // KIRIM TAGIHAN
        if ($now == $pset['kirim_tagihan'] AND $time >= '6') {
            echo "KIRIM TAGIHAN => " . $pset['id_data_server'] . " <-> " . $pset['nama'] . "<br>";

            $stmt = $pdo->prepare("SELECT * FROM v_tagihan WHERE status = 'buat' AND id_profile_tagihan = :id_profile_tagihan LIMIT 20");
            $stmt->bindParam(':id_profile_tagihan', $pset['id'], PDO::PARAM_INT);
            $stmt->execute();
            $tags = $stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($tags as $psend) {
                echo $psend['nama'] . "<br>";
                $idp = $psend['id_pelanggan'];
                $idtag = $psend['id'];
                $phone = array($psend['nomor_whatsapp']);

                // KIRIM PESAN WHATSAPP
                $API_WA = new PesanWA();
                $API_WA->Create_Pesan($psend['id_data_server'], $idtag, 'pesan_kirim_tagihan', 'tag');
                $Pesan = $API_WA->Get_Pesan();
                $API_WA->Send_Pesan($psend['id_data_server'], 'sendMessage', $phone, $Pesan);

                // UPDATE TAGIHAN
                $stmt = $pdo->prepare("
                    UPDATE tagihan SET status = 'pending' WHERE id = :id
                ");
                $stmt->bindParam(':id', $idtag, PDO::PARAM_INT);
                $stmt->execute();
                
            }
        }
        // END KIRIM TAGIHAN

        // REMAND TAGIHAN
        elseif ($now == $pset['peringatan_tagihan'] AND $time >= '6') {
            echo "REMAND => " . $pset['id_data_server'] . " <-> " . $pset['nama'] . "<br>";
            
            $stmt = $pdo->prepare("SELECT * FROM v_tagihan WHERE status = 'pending' AND id_profile_tagihan = :id_profile_tagihan LIMIT 20");
            $stmt->bindParam(':id_profile_tagihan', $pset['id'], PDO::PARAM_INT);
            $stmt->execute();
            $remands = $stmt->fetchAll(PDO::FETCH_ASSOC);

            foreach ($remands as $presend) {
                echo $presend['nama'] . "<br>";
                $idtagre = $presend['id'];
                $idpelre = $presend['id_pelanggan'];
                $wa_nore = array($presend['nomor_whatsapp']);

                // KIRIM PESAN WHATSAPP
                $API_WA = new PesanWA();
                $API_WA->Create_Pesan($presend['id_data_server'], $idtagre, 'pesan_peringatan_tagihan', 'tag');
                $Pesanre = $API_WA->Get_Pesan();
                $API_WA->Send_Pesan($presend['id_data_server'], 'sendMessage', $wa_nore, $Pesanre);

                // UPDATE TAGIHAN
                $stmt = $pdo->prepare("
                    UPDATE tagihan SET status = 'pending1' WHERE id = :id
                ");
                $stmt->bindParam(':id', $idtagre, PDO::PARAM_INT);
                $stmt->execute();
                echo "<br>".$Pesanre." => ";
                print_r($wa_nore);
            }
        }
        // END REMAND TAGIHAN

        // OFF CONNECTION OFF PELANGGAN
        elseif ($now == $pset['limit_tagihan']) {
            echo "OFF CONNECTION => " . $pset['id_data_server'] . " <-> " . $pset['nama'] . "<br>";

            $stmt = $pdo->prepare("SELECT * FROM v_tagihan
                WHERE status IN ('pending', 'pending1', 'pending2') 
                AND id_profile_tagihan = :id_profile_tagihan LIMIT 10");
            $stmt->bindParam(':id_profile_tagihan', $pset['id'], PDO::PARAM_INT);
            $stmt->execute();
            $offs = $stmt->fetchAll(PDO::FETCH_ASSOC);

            foreach ($offs as $poff) {
                echo $poff['nama'] . $poff['id_setting_mikrotik'] ."<br>";
                $idtagihan = $poff['id'];
                $idpelanggan = $poff['id_pelanggan'];
                $wa_nooff = array($poff['nomor_whatsapp']);
                $user = $poff['akun'];
                $userhs = $poff['user_hotspot'];

                //Get Mikrotik Setting
                $Mikro = $pdo->prepare("SELECT ip_address, port_api, username, password FROM setting_mikrotik WHERE id = :idset");
                $Mikro->bindParam(':idset', $poff['id_setting_mikrotik'], PDO::PARAM_INT);
                $Mikro->execute();
                $Mikrot = $Mikro->fetchAll(PDO::FETCH_ASSOC);
                print_r($Mikrot);
                $m_ip   = $Mikrot[0]['ip_address'];
                $m_user = $Mikrot[0]['username'];
                $m_pass = $Mikrot[0]['password'];
                $m_port = $Mikrot[0]['port_api'];

                $API = new RouterosAPI();
                $API->debug = false;

                if ($API->connect2($m_ip, $m_user, $m_pass, $m_port)) {
                    $cek = 1;
                    if ($poff['jenis_layanan'] == 'Hotspot') {
                        $arrIDh = $API->comm("/ip/hotspot/user/getall", [
                            ".proplist" => ".id",
                            "?name" => $userhs,
                        ]);

                        if (!empty($arrIDh)) {
                            $API->comm("/ip/hotspot/user/set", [
                                ".id" => $arrIDh[0][".id"],
                                "disabled" => "true",
                            ]);

                            $arrIDha = $API->comm("/ip/hotspot/active/getall", [
                                ".proplist" => ".id",
                                "?user" => $userhs,
                            ]);

                            if (!empty($arrIDha)) {
                                $API->comm("/ip/hotspot/active/remove", [
                                    ".id" => $arrIDha[0][".id"],
                                ]);
                            }
                        }
                    } else {
                        $arrID = $API->comm("/ppp/secret/getall", [
                            ".proplist" => ".id",
                            "?name" => $user,
                        ]);

                        if (!empty($arrID)) {
                            $API->comm("/ppp/secret/set", [
                                ".id" => $arrID[0][".id"],
                                "disabled" => "true",
                            ]);

                            $arrID1 = $API->comm("/ppp/active/getall", [
                                ".proplist" => ".id",
                                "?name" => $user,
                            ]);

                            if (!empty($arrID1)) {
                                $API->comm("/ppp/active/remove", [
                                    ".id" => $arrID1[0][".id"],
                                ]);
                            }
                        }
                    }
                } else { $cek = 0; }
                $API->disconnect();

                if($cek == 1){
                    // UPDATE TAGIHAN
                    $stmt = $pdo->prepare("
                        UPDATE tagihan SET status = 'lewat' WHERE id = :id_tagihan
                    ");
                    $stmt->bindParam(':id_tagihan', $idtagihan, PDO::PARAM_INT);
                    $stmt->execute();

                    // UPDATE PELANGGAN
                    $stmt = $pdo->prepare("
                        UPDATE pelanggan SET status = 'tidak aktif' WHERE id = :id_pelanggan
                    ");
                    $stmt->bindParam(':id_pelanggan', $idpelanggan, PDO::PARAM_INT);
                    $stmt->execute();

                    // KIRIM PESAN WHATSAPP
                    $API_WA = new PesanWA();
                    $API_WA->Create_Pesan($poff['id_data_server'], $idtagihan, 'pesan_isolir_pelanggan', 'tag');
                    $Pesanr = $API_WA->Get_Pesan();
                    $API_WA->Send_Pesan($poff['id_data_server'], 'sendMessage', $wa_nooff, $Pesanr);
                }
                else {
                    echo "Server Not Connect";
                }
            }
        }
        // END OFF CONNECTION OFF PELANGGAN

        // BUAT TAGIHAN
        elseif ($skr2 >= $starttime && $skr2 <= $lasttime) {
            echo "BUAT TAGIHAN => " . $pset['id_data_server'] . " <-> " . $pset['nama'] . " Start : " . $tgl92 . " - Last : " . $sendtag . "<br>";

            $stmt = $pdo->prepare("SELECT * FROM pelanggan WHERE status = 'aktif' AND id_profile_tagihan = :id");
            $stmt->bindParam(':id', $pset['id'], PDO::PARAM_INT);
            $stmt->execute();
            $pelanggan = $stmt->fetchAll(PDO::FETCH_ASSOC);

            foreach ($pelanggan as $pecah1) {
                // Cari data paket
                $stmt = $pdo->prepare("SELECT harga_paket FROM profile_paket WHERE id = :id_profile_paket ");
                $stmt->bindParam(':id_profile_paket', $pecah1['id_profile_paket'], PDO::PARAM_INT);
                $stmt->execute();
                $tagihan = $stmt->fetchColumn();
                // Cari data tagihan di tabel tagihan
                $stmt = $pdo->prepare("SELECT * FROM tagihan WHERE status = 'buat' AND id_pelanggan = :id");
                $stmt->bindParam(':id', $pecah1['id'], PDO::PARAM_INT);
                $stmt->execute();
                $adadata = $stmt->rowCount();

                if ($adadata == 0) {
                    echo $pecah1['nama'] . "<br>";

                    if ($pset['ppn'] == 1 ) {
                        $nominal_tagihan = $tagihan;
                        $jumlah_tagihan = $tagihan;
                        $ppn = 0;
                        $total_tagihan = $jumlah_tagihan + $ppn;
                        $kode_unik = 0;
                        $verifikasi_tagihan = $total_tagihan + $kode_unik;
                    }
                    elseif($pset['ppn'] == 2 ) {
                        $nominal_tagihan = $tagihan;
                        $jumlah_tagihan = $tagihan;
                        $ppn = $jumlah_tagihan / 100 * 11;
                        $total_tagihan = $jumlah_tagihan + $ppn;
                        $kode_unik = 0;
                        $verifikasi_tagihan = $total_tagihan + $kode_unik;
                    }
                    elseif($pset['ppn'] == 3 ) {
                        $nominal_tagihan = $tagihan;
                        $jumlah_tagihan = $tagihan - ($tagihan / 100 * 9.91);
                        $ppn = $jumlah_tagihan / 100 * 11;
                        $total_tagihan = $jumlah_tagihan + $ppn;
                        $kode_unik = 0;
                        $verifikasi_tagihan = $total_tagihan + $kode_unik;
                    }
                    elseif($pset['ppn'] == 4 ) {
                        $nominal_tagihan = $tagihan;
                        $jumlah_tagihan = $tagihan;
                        $ppn = $jumlah_tagihan / 100 * 11;
                        $total_tagihan = $jumlah_tagihan + $ppn;
                        $kode_unik = substr($total_tagihan, -3);
                        $verifikasi_tagihan = $total_tagihan - $kode_unik;
                    }

                    $datatag = substr($sendtag1, 0, 8) . $pset['limit_tagihan'];
                    $dataLim = new DateTime($datatag);
                    $dataLim->modify('-1 day'); // Mengurangi 1 hari
                    $limit_tag = $dataLim->format('Y-m-d');

                    $id_data_server = $pecah1['id_data_server'];
                    $id_pelanggan = $pecah1['id'];
                    $id_profile_paket = $pecah1['id_profile_paket'];
                    $id_profile_tagihan = $pecah1['id_profile_tagihan'];

                    $keterangan = "Tagihan Layanan Internet bulan " . formatIndo($limit_tag, 'F Y');
                    $status = 'buat';

                    $stmt = $pdo->prepare("INSERT INTO tagihan 
                        (id_data_server, id_pelanggan, id_profile_paket, id_profile_tagihan, nominal_tagihan, jumlah_tagihan, ppn, total_tagihan, kode_unik, verifikasi_tagihan, keterangan, limit_pembayaran, status)
                        VALUES (:id_data_server, :id_pelanggan, :id_profile_paket, :id_profile_tagihan, :nominal_tagihan, :jumlah_tagihan, :ppn, :total_tagihan, :kode_unik, :verifikasi_tagihan, :keterangan, :limit_pembayaran, :status)
                        ");
                    $stmt->execute([
                        ':id_data_server' => $id_data_server,
                        ':id_pelanggan' => $id_pelanggan,
                        ':id_profile_paket' => $id_profile_paket,
                        ':id_profile_tagihan' => $id_profile_tagihan,
                        ':nominal_tagihan' => $nominal_tagihan,
                        ':jumlah_tagihan' => $jumlah_tagihan,
                        ':ppn' => $ppn,
                        ':total_tagihan' => $total_tagihan,
                        ':kode_unik' => $kode_unik,
                        ':verifikasi_tagihan' => $verifikasi_tagihan,
                        ':keterangan' => $keterangan,
                        ':limit_pembayaran' => $limit_tag,
                        ':status' => $status,
                    ]);
                }
            }
        } else {
            echo "NO ACTION => " . $pset['id_data_server'] . " <-> " . $pset['nama'] . "<br>";
        }
        // END BUAT TAGIHAN
    }

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

?>