<?php

// simple callback (make sure whitelist paydisini 194.233.92.170)
if ($_POST['key'] == '4f120457653057e4362b56639478af67') {

    $key = $_POST['key'];
    $order_id = $_POST['unique_code'];
    $status = $_POST['status'];
    $signature = $_POST['signature'];
    $sign = md5('4f120457653057e4362b56639478af67' . $order_id . 'CallbackStatus');

    include '../../../config/connect.php';
    include '../../../config/whatsapp_api.php';

    $stmt = $pdo->prepare("SELECT * FROM apk_payment WHERE order_id = :order_id");
    $stmt->bindParam(':order_id', $order_id);
    $stmt->execute();
    $result = $stmt->fetch();

    // Generate log file name based on current date and time
    $logFileName = 'log_' . date('Y-m-d H:i:s') . '.log';

    // Prepare log message
    $logMessage = "[" . date('Y-m-d H:i:s') . "] Received Callback - Order ID: $order_id, Status: $status, Signature: $signature, Expected Signature: $sign\n";

    // Write log message to file without opening the file manually (appending mode)
    // file_put_contents($logFileName, $logMessage, FILE_APPEND);

    if ($signature != $sign) {
        $result = array('success' => false);
        $logMessage = "Signature mismatch, callback ignored.\n";
        // file_put_contents($logFileName, $logMessage, FILE_APPEND);
    } else if ($status == 'Success') {
        
        if ($result['jenis'] == 'PPPOE') {
            //Update Succesc untuk PPPOE ( di gunakan nanati );
        } else if($result['jenis'] == 'Hotspot') {
            // Ambil data voucher berdasarkan order_id
            $stmt = $pdo->prepare("SELECT * FROM v_voucher_paygw WHERE order_id = :order_id");
            $stmt->bindParam(':order_id', $order_id, PDO::PARAM_STR);
            $stmt->execute();
            $vcr = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$vcr) {
                // Tidak ditemukan
                exit("Voucher tidak ditemukan untuk order_id: $order_id");
            }
            
            // Konfigurasi koneksi MikroTik
            $m_ip   = $vcr['ip_address'];
            $m_user = $vcr['username'];
            $m_pass = $vcr['password'];
            $m_port = $vcr['port_api'];
            
            require('../../../config/routeros_api.class.php');
            $API = new RouterosAPI();
            $API->debug = false;
            
            // Coba koneksi ke MikroTik
            if ($API->connect2($m_ip, $m_user, $m_pass, $m_port)) {
                try {
                    // Tambah user ke hotspot
                    $API->comm('/ip/hotspot/user/add', [
                        "name"     => $vcr['voucher'],
                        "password" => $vcr['voucher'],
                        "profile"  => $vcr['nama_profile'],
                        "server"   => "all"
                    ]);
                
                    // Update status berhasil
                    $update = $pdo->prepare("UPDATE ganerate_voucher SET status_create = '1' WHERE id = :id");
                    $update->execute([':id' => $vcr['id']]);
                
                    // Kirim pesan WhatsApp
                    $nomorList = array_filter(array_map('trim', explode(',', $vcr['nomor_whatsapp'])));
                    $APIwa = new PesanWA();
                
                    $Pesan = "Pembelian voucher kamu *BERHASIL!*\n\n"
                           . "Tanggal            : " . $vcr['waktu_transaksi'] . "\n"
                           . "Pembayaran    : QRIS\n\n"
                           . "Paket                : " . $vcr['nama_paket'] . "\n"
                           . "Harga               : Rp " . number_format($vcr['harga']) . "\n"
                           . "Kode Voucher : *" . $vcr['voucher'] . "*\n\n"
                           . "_Voucher hanya bisa digunakan pada 1 perangkat / device._\n\n"
                           . "Terima kasih telah menggunakan layanan kami.";

                    if (!empty($nomorList)) {
                        $APIwa->Send_Pesan($vcr['id_data_server'], 'sendMessage', $nomorList, $Pesan);
                    }
                    
                } catch (Exception $e) {
                    // Jika gagal saat perintah ke router
                    $update = $pdo->prepare("UPDATE ganerate_voucher SET status_create = '0' WHERE id = :id");
                    $update->execute([':id' => $vcr['id']]);
                    // error_log("Gagal menambahkan user hotspot: " . $e->getMessage());
                } finally {
                    $API->disconnect();
                }
            } else {
                // Jika gagal konek ke MikroTik
                $update = $pdo->prepare("UPDATE ganerate_voucher SET status_create = '0' WHERE id = :id");
                $update->execute([':id' => $vcr['id']]);
                // error_log("Gagal koneksi ke MikroTik pada IP: $m_ip");
            }
            
        } else {
            // Pisahkan dan pastikan hanya angka
            $idArray = array_map('intval', explode(',', $result['id_data_server']));
            $placeholders = implode(',', array_fill(0, count($idArray), '?'));
            $sql = "UPDATE data_server SET status = 'Aktif', expaired_date = ? WHERE id IN ($placeholders)";
            $stmt = $pdo->prepare($sql);
            $params = array_merge([$result['expaired_time']], $idArray);
            $stmt->execute($params);
        }
        // Update payment status to "LUNAS"
        $stmt = $pdo->prepare("UPDATE apk_payment SET status = 'LUNAS' WHERE order_id = :order_id");
        $stmt->bindParam(':order_id', $order_id);
        $stmt->execute();

        $result = array('success' => true);
        $logMessage = "Payment success for Order ID: $order_id, Status updated to LUNAS.\n";
        // file_put_contents($logFileName, $logMessage, FILE_APPEND);
    } else if ($status == 'Canceled') {
        // Update payment status to "CANCELED"
        $stmt = $pdo->prepare("UPDATE apk_payment SET status = 'CANCELED' WHERE order_id = :order_id");
        $stmt->bindParam(':order_id', $order_id);
        $stmt->execute();

        $result = array('success' => true);
        $logMessage = "Payment canceled for Order ID: $order_id, Status updated to CANCELED.\n";
        // file_put_contents($logFileName, $logMessage, FILE_APPEND);
    } else {
        $result = array('success' => false);
        $logMessage = "Invalid status received for Order ID: $order_id\n";
        // file_put_contents($logFileName, $logMessage, FILE_APPEND);
    }
}

// Set response header and return JSON result
header('Content-type: application/json');
echo json_encode($result);
