<?php
// Aktifkan pelaporan kesalahan untuk pengembangan
error_reporting(E_ALL);
ini_set('display_errors', 0); // Tampilkan kesalahan saat pengembangan

// Menghubungkan ke database
include "../config/connect.php";
include "../config/tanggal_indo.php";
include "../config/routeros_api.class.php";
include "../config/whatsapp_api.php";

try {
    // Ambil semua apiKey_whatsapp yang tidak kosong
    $sqlData = "SELECT api_key FROM v_key_load_pesan";
    $stmtData = $pdo->query($sqlData);

    // Loop melalui setiap apiKey_whatsapp
    while ($dataambil = $stmtData->fetch(PDO::FETCH_ASSOC)) {
        $keyapi = $dataambil['api_key'];

        // Ambil pesan dengan status 'PENDING' dan api_key sesuai
        $sql = "SELECT * FROM v_master_pesan WHERE api_key = :apiKey AND status ='PENDING' ";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':apiKey' => $keyapi]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);

    if($data) {
        $jenis = $data['jenis_pesan'];
        $apiurl = $data['api_url'];

        // Siapkan data untuk dikirim berdasarkan jenis pesan
        $datapost = '';
        if ($jenis == "sendMessage") {
            $datapost = http_build_query([
                'apiKey' => $data['api_key'],
                'phone' => $data['nomor'],
                'message' => $data['pesan']
            ]);
        } elseif ($jenis == "sendMediaFromUrl") {
            $datapost = http_build_query([
                'apiKey' => $data['api_key'],
                'phone' => $data['nomor'],
                'url_file' => $data['url_file'],
                'as_document' => '0',
                'caption' => $data['pesan']
            ]);
        } else {
            continue; // Skip jika jenis tidak dikenali
        }
        
        // echo $datapost;
        // echo $datapost;

        // Inisialisasi cURL
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $apiurl . $jenis,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $datapost,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/x-www-form-urlencoded',
                'Content-Length: ' . strlen($datapost)
            ),
        ));

        // Eksekusi cURL dan tangani kesalahan
        $response = curl_exec($curl);
        if (curl_errno($curl)) {
            error_log('cURL Error: ' . curl_error($curl));
            curl_close($curl);
            continue; // Skip ke data berikutnya jika ada error
        }
        curl_close($curl);

        // Decode respons JSON
        $rdata = json_decode($response);
        // print_r($rdata)."<br>";
        
        // Periksa apakah respons valid
        if (json_last_error() !== JSON_ERROR_NONE) {
            error_log('JSON Decode Error: ' . json_last_error_msg());
            $rdata = (object) ['code' => '200', 'results' => (object) []]; // Anda bisa menyesuaikan ini jika perlu
        }
        
        // Update status berdasarkan respons
        // $status = (isset($rdata->code) && $rdata->code === '200') ? 'TERKIRIM' : 'GAGAL';
        if($rdata->code == 200){
            $status = 'TERKIRIM';
        } else {
            $status = 'GAGAL';
        }
        
        echo $rdata->code;  // Mengakses 'code' dengan benar
        echo " ".$status;

        
        // Update status di database
        $updateStmt = $pdo->prepare("UPDATE master_pesan SET status = :status WHERE id = :id");
        $updateStmt->execute([
            ':status' => $status,
            ':id' => $data['id']
        ]);
    }
}
    // Ambil data tagihan yang status transaksinya SUCCESSFUL
    $datetime = date('Y-m-d H:i:s', time() - 60); // waktu 60 detik yang lalu
    $stmt = $pdo->prepare("SELECT * FROM v_tagihan_flip_lunas WHERE last_mikrotik_connect > :datetime");
    $stmt->execute(['datetime' => $datetime]);
    $tagihan = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Pastikan data tagihan ditemukan
    if ($tagihan) {

        // Ambil detail tagihan
        $user = $tagihan['akun'];
        $idtag = $tagihan['id'];
        $nama = $tagihan['nama']; // Contoh nama
        $nominal = $tagihan['verifikasi_tagihan']; // Contoh nominal
        $keterangan = 'Pembayaran ' . $tagihan['keterangan']; // Contoh keterangan
        $invoice = 'kwitansi_' . date('Ymd') . $idtag . '.png'; // Nama file output
        $paketint = $tagihan['nama_paket'];
        $jumtagihan = 'Rp. '.number_format($tagihan['jumlah_tagihan'], 0, ',', '.');
        $ppn = 'Rp. '.number_format($tagihan['ppn'], 0, ',', '.');
        $subsidi = 'Rp. '.number_format($tagihan['kode_unik'], 0, ',', '.');
        $tanggal = $tagihan['tanggal_bayar'];
        $metode = "API Payment";
        $kodeunik = $tagihan['kode_unik'];

        // Buat gambar dari file PNG yang ada
        $stmt = $pdo->prepare("SELECT backround_kwitansi, kabupaten FROM data_server WHERE id = :id");
        $stmt->bindParam(':id', $tagihan['id_data_server'], PDO::PARAM_INT);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $gambarKwitansi = '../img/' . $result['backround_kwitansi']; // Pastikan variabel gambar ada

        // Membuat gambar dari file PNG
        $img = imagecreatefrompng($gambarKwitansi);
        // Buat beberapa warna
        $white = imagecolorallocate($img, 245, 245, 245);
        $black = imagecolorallocate($img, 0, 0, 0);
        $orange = imagecolorallocate($img, 0, 0, 128);
        $fontPath = '../dist/X_10x20_LE.gdf';
        $font = imageloadfont($fontPath);
        $line = '_____________________________________________________________________________________';
        
        // Menambahkan teks ke gambar
        // imagestring($img, $font, 320, 30, 'KWITANSI PEMBAYARAN', $black);
        // imagestring($img, 5, 650, 52, 'No. ' . date('Ymd') . $idtag, $black);
        // imagestring($img, 2, 650, 67, 'Tanggal pembayaran', $black);
        // imagestring($img, 2, 650, 82, formatIndo(date('Y-m-d'), 'd F Y'), $black);
        // imagestring($img, 5, 20, 91, $line, $orange);
        // imagestring($img, 5, 20, 95, $line, $orange);
        // imagestring($img, 4, 30, 125, 'Telah Diterima Dari', $black);
        // imagestring($img, 5, 200, 125, ': ' . $nama, $black);
        // imagestring($img, 4, 30, 150, 'Sejumlah Uang', $black);
        // imagestring($img, 4, 200, 150, ': ' . terbilang($nominal) . ' rupiah', $black);
        // imagestring($img, 4, 30, 175, 'Untuk Pembayaran', $black);
        // imagestring($img, 4, 200, 175, ':', $black);
        // imagestring($img, 5, 100, 200, $keterangan, $black);
        // imagestring($img, 5, 20, 245, $line, $orange);
        // imagestring($img, 5, 50, 280, '___________________________', $orange);
        // imagestring($img, $font, 70, 300, 'Nominal : Rp. ' . number_format($nominal, 0, ',', '.'), $black);
        // imagestring($img, 5, 50, 310, '___________________________', $orange);
        // imagestring($img, 4, 535, 280, $result['kabupaten'] . ', ' . formatIndo(date('Y-m-d'), 'd F Y'), $black);

        $img = imagecreatefrompng($gambarKwitansi);
        // Buat beberapa warna
        $white = imagecolorallocate($img, 245, 245, 245);
        $black = imagecolorallocate($img, 0, 0, 0);
        $orange = imagecolorallocate($img, 0, 0, 128);
        $fontPath = '../dist/X_10x20_LE.gdf';
        $font = imageloadfont($fontPath);
        $line = '_____________________________________________________________________________________';
        imagestring($img, $font, 320, 30, 'KWITANSI PEMBAYARAN', $black);
        imagestring($img, 3, 580, 30, 'No Faktur', $black);
        imagestring($img, 3, 670, 30, ': '.date('Ymd').$idtag, $black);
        imagestring($img, 3, 580, 50, 'Tanggal', $black);
        imagestring($img, 3, 670, 50, ': '.formatIndo(date('Y-m-d'), 'd F Y'), $black);
        imagestring($img, 3, 580, 70, 'No Pelanggan', $black);
        imagestring($img, 3, 670, 70, ': '.$user, $black);
        imagestring($img, 5, 20, 81, $line, $orange);
        imagestring($img, 5, 20, 85, $line, $orange);
        imagestring($img, 4, 30, 110, 'Telah Diterima Dari', $black);
        imagestring($img, 5, 200, 110, ': '.$nama, $black);
        imagestring($img, 4, 30, 135, 'Sejumlah Uang', $black);
        imagestring($img, 4, 200, 135, ': '.terbilang($nominal).' rupiah', $black);
        imagestring($img, 4, 30, 160, 'Untuk Pembayaran', $black);
        imagestring($img, 4, 200, 160, ': '. $keterangan, $black);
        imagestring($img, 5, 20, 175, $line, $orange);
        imagestring($img, 4, 30, 190, 'NO', $black);
        imagestring($img, 4, 70, 190, 'KETERANGAN', $black);
        imagestring($img, 4, 620, 190, 'NOMINAL', $black);
        imagestring($img, 5, 20, 195, $line, $orange);

        imagestring($img, 4, 30, 215, '1', $black);
        imagestring($img, 4, 70, 215, $paketint, $black);
        imagestring($img, 4, 620, 215, $jumtagihan, $black);

        if($tagihan['ppn'] != 0 ) {
        imagestring($img, 4, 30, 235, '2', $black);
        imagestring($img, 4, 70, 235, 'PPN 11%', $black);
        imagestring($img, 4, 620, 235, $ppn, $black);
        }

        if($tagihan['kode_unik'] != 0 ) {
        imagestring($img, 4, 30, 255, '3', $black);
        imagestring($img, 4, 70, 255, 'Subsidi', $black);
        imagestring($img, 4, 620, 255, $subsidi, $black);
        }

        imagestring($img, 5, 20, 265, $line, $orange);
        imagestring($img, 4, 550, 290, 'TOTAL', $black);
        imagestring($img, 4, 620, 290, 'Rp. '.number_format($nominal, 0, ',', '.'), $black);
        imagestring($img, 5, 550, 300, '__________________________   ', $orange);

        imagestring($img, 5, 50, 320, '______________________________', $orange);
        imagestring($img, $font, 70, 340, 'Terbilang : Rp. '.number_format($nominal, 0, ',', '.'), $black);
        imagestring($img, 5, 50, 350, '______________________________', $orange);
        // Simpan file ke direktori 'invoice'
        $invoicePath = 'invoice/'.$invoice;

        // echo $invoicePath;
        // Simpan file ke direktori 'invoice'
        $invoicePath = '../invoice/' . $invoice;
        if (!imagepng($img, $invoicePath)) {
            // echo "<br>" . $invoicePath;
            die('Gagal menyimpan gambar.');
        } else {
            imagedestroy($img); // Hancurkan gambar setelah disimpan

            // Ambil pengaturan Mikrotik
            $Mikro = $pdo->prepare("SELECT ip_address, port_api, username, password FROM setting_mikrotik WHERE id = :idset");
            $Mikro->bindParam(':idset', $tagihan['id_setting_mikrotik'], PDO::PARAM_INT);
            $Mikro->execute();
            $Mikrot = $Mikro->fetchAll(PDO::FETCH_ASSOC);

            // Ambil detail koneksi
            $m_ip   = $Mikrot[0]['ip_address'];
            $m_user = $Mikrot[0]['username'];
            $m_pass = $Mikrot[0]['password'];
            $m_port = $Mikrot[0]['port_api'];

            // Ambil akun pelanggan
            $hsakun = $tagihan['user_hotspot'];

            // Koneksi ke API Mikrotik
            $API = new RouterosAPI();
            $API->debug = false;

            if ($API->connect2($m_ip, $m_user, $m_pass, $m_port)) {
                // Memproses berdasarkan jenis layanan
                if ($tagihan['jenis_layanan'] == 'Hotspot') {
                    
                    $statuskas = "Pendapatan Hotspot";
                    
                    $arrIDh = $API->comm("/ip/hotspot/user/getall", [
                        ".proplist" => ".id",
                        "?name" => $hsakun,
                    ]);

                    if (!empty($arrIDh)) {
                        $API->comm("/ip/hotspot/user/set", [
                            ".id" => $arrIDh[0][".id"],
                            "disabled" => "false",
                        ]);
                    }
                } else {
                    
                    $statuskas = "Pendapatan PPPOE";
                    
                    $arrID = $API->comm("/ppp/secret/getall", [
                        ".proplist" => ".id",
                        "?name" => $user,
                    ]);

                    if (!empty($arrID)) {
                        $API->comm("/ppp/secret/set", [
                            ".id" => $arrID[0][".id"],
                            "disabled" => "false",
                        ]);
                    }
                }
                // Update status pelanggan menjadi aktif
                $stmt = $pdo->prepare("UPDATE pelanggan SET status = 'aktif' WHERE id = :idpel");
                $stmt->bindParam(':idpel', $tagihan['id_pelanggan'], PDO::PARAM_INT);
                $stmt->execute();

                // Update status tagihan dan simpan bukti pembayaran
                $stmt = $pdo->prepare("UPDATE tagihan SET img_invoice = :inv, status = 'lunas' WHERE id = :idtag");
                $stmt->bindParam(':inv', $invoice);
                $stmt->bindParam(':idtag', $idtag, PDO::PARAM_INT);
                $stmt->execute();

                // Cek transaksi dengan id tagihan
                $stmt = $pdo->prepare("SELECT id_tagihan FROM transaksi WHERE id_tagihan = :id");
                $stmt->bindParam(':id', $idtag, PDO::PARAM_INT);
                $stmt->execute();
                $tagid = $stmt->fetchColumn();
                if ($tagid === false) {
                    // Jika tidak ada, insert data transaksi baru
                    $sql = "INSERT INTO transaksi (id_data_server, id_tagihan, id_user_akses, start_time, keterangan, pemasukan, metode_pembayaran, status) VALUES (:idds, :idtag, :idua, :start_time, :keterangan, :pemasukan, :metode, :status)";
                    $stmt = $pdo->prepare($sql);
                    $stmt->bindParam(':idds', $tagihan['id_data_server'], PDO::PARAM_INT);
                    $stmt->bindParam(':idtag', $idtag, PDO::PARAM_INT);
                    $stmt->bindParam(':idua', $tagihan['id_marketing'], PDO::PARAM_INT);
                    $stmt->bindParam(':start_time', $tanggal);
                    $stmt->bindParam(':keterangan', $tagihan['keterangan']);
                    $stmt->bindParam(':pemasukan', $tagihan['verifikasi_tagihan']);
                    $stmt->bindParam(':metode', $metode);
                    $stmt->bindParam(':status', $statuskas);
                    $stmt->execute();
                }

                // Kirim Pesan WhatsApp
                $nomor = explode(',', $tagihan['nomor_whatsapp']);
                $Url = 'http://bilspro.com/invoice/' . $invoice;
                
                $APIwa = new PesanWA();
                $APIwa->Create_Pesan($tagihan['id_data_server'], $idtag, 'pesan_melunasi_tagihan', 'tag');
                $Pesan = $APIwa->Get_Pesan();
                $APIwa->Send_Pesan($tagihan['id_data_server'], 'sendMediaFromUrl', $nomor, $Pesan, $Url);
            }
        }
        echo "Flip Lunas" . $tagihan['nama'];
    } else {
        echo "Tidak ADA DATA yang lunas";
    }
} catch (PDOException $e) {
    error_log('Database Error: ' . $e->getMessage());
    echo "Database error occurred."; // Tampilkan pesan kesalahan
} catch (Exception $e) {
    error_log('General Error: ' . $e->getMessage());
    echo "An error occurred."; // Tampilkan pesan kesalahan umum
}
?>