<?php

// Ambil data POST
$data = isset($_POST['data']) ? $_POST['data'] : null;
$token = isset($_POST['token']) ? $_POST['token'] : null;

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

// Validasi token
if (empty($token)) {
    http_response_code(401); // Unauthorized
    echo "Token is required.";
    exit;
}

// Validasi format data JSON
if (!is_string($data)) {
    http_response_code(400); // Bad Request
    echo "Data must be a valid JSON string.";
    exit;
}

try {
    // Query untuk mengambil data berdasarkan tokenkey_payment_gateway
    $stmt = $pdo->prepare("
        SELECT id, tokenkey_payment_gateway, apikey_payment_gateway, url_payment_gateway 
        FROM data_server 
        WHERE tokenkey_payment_gateway = :tokenkey_payment_gateway
    ");
    $stmt->bindParam(':tokenkey_payment_gateway', $token, PDO::PARAM_STR);
    $stmt->execute();

    // Array untuk menyimpan semua ID
    $dataId = [];
    $apiKey = null;
    $apiUrl = null;

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $dataId[] = $row['id'];
        $apiKey = $row['apikey_payment_gateway'];
        $apiUrl = $row['url_payment_gateway'];
    }

    // Jika tidak ada data server, hentikan proses
    if (empty($dataId)) {
        http_response_code(404); // Not Found
        echo "No data found for the provided token.";
        exit;
    }

    $idsServer = implode(",", $dataId);

    // Decode data JSON
    $respon = json_decode($data, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400); // Bad Request
        echo "Invalid JSON format.";
        exit;
    }

    // Ambil dan validasi data
    $bill_link_id = filter_var($respon['bill_link_id'], FILTER_SANITIZE_STRING);
    $status = filter_var($respon['status'], FILTER_SANITIZE_STRING);
    $nominal = filter_var($respon['amount'], FILTER_SANITIZE_STRING);
    $sender_bank = filter_var($respon['sender_bank'], FILTER_SANITIZE_STRING);

    // Validasi waktu
    try {
        $waktu = new DateTime($respon['created_at']);
        $waktu = $waktu->format('Y-m-d H:i:s');
    } catch (Exception $e) {
        http_response_code(400); // Bad Request
        echo "Invalid date format.";
        exit;
    }

    // Validasi status transaksi
    $validStatuses = ['SUCCESS', 'DONE', 'SUCCESSFUL', 'PENDING', 'ACTIVE', 'INACTIVE', 'CANCELLED'];
    if (!in_array($status, $validStatuses)) {
        http_response_code(400); // Bad Request
        echo "Invalid status.";
        exit;
    }

    // Cek tagihan
    $query = "
        SELECT transaction_id, keterangan, verifikasi_tagihan, id_data_server 
        FROM tagihan 
        WHERE id_data_server IN ($idsServer) AND transaction_id = :bill_link_id
    ";
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':bill_link_id', $bill_link_id, PDO::PARAM_STR);
    $stmt->execute();

    $cek_tagihan = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($cek_tagihan) {
        // Proses update tagihan
        if ($status === 'SUCCESSFUL') {
            $stmt = $pdo->prepare("
                UPDATE tagihan 
                SET transaction_status = :status, tanggal_bayar = :tanggal_bayar 
                WHERE id_data_server = :idsvrtag AND transaction_id = :bill_link_id
            ");
            $stmt->bindParam(':idsvrtag', $cek_tagihan['id_data_server'], PDO::PARAM_INT);
            $stmt->bindParam(':bill_link_id', $bill_link_id, PDO::PARAM_STR);
            $stmt->bindParam(':status', $status, PDO::PARAM_STR);
            $stmt->bindParam(':tanggal_bayar', $waktu, PDO::PARAM_STR);
            $stmt->execute();

            // Matikan link payment gateway
            require '../Flip/Transaction.php';
            $flip = new FlipPaymentGateway($apiKey, $apiUrl);
            $response = $flip->editBill($bill_link_id, 'INACTIVE', $cek_tagihan['keterangan'], $cek_tagihan['verifikasi_tagihan']);

        } else {
            http_response_code(200); // OK
            echo "Transaction status: $status";
            exit;
        }
    } else {
        // Proses untuk agen
        $query = "
            SELECT id_agen_voucher, keterangan, nominal, id_data_server 
            FROM agen_tambah_saldo 
            WHERE id_data_server IN ($idsServer) AND id_payment = :id_payment
        ";
        $stmt = $pdo->prepare($query);
        $stmt->bindParam(':id_payment', $bill_link_id, PDO::PARAM_STR);
        $stmt->execute();

        $cek_agen = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($cek_agen) {
            $stmt = $pdo->prepare("
                UPDATE agen_tambah_saldo 
                SET status_payment = :status, tanggal_bayar = :tanggal_bayar 
                WHERE id_data_server = :idsvragen AND id_payment = :bill_link_id
            ");
            $stmt->bindParam(':idsvragen', $cek_agen['id_data_server'], PDO::PARAM_INT);
            $stmt->bindParam(':bill_link_id', $bill_link_id, PDO::PARAM_STR);
            $stmt->bindParam(':status', $status, PDO::PARAM_STR);
            $stmt->bindParam(':tanggal_bayar', $waktu, PDO::PARAM_STR);
            $stmt->execute();

            if ($status === 'SUCCESSFUL') {

                $keteranganAgen = "Isi Saldo Reff:" . $bill_link_id;

                // Cek transaksi Agent
                $stmt = $pdo->prepare("SELECT keterangan FROM transaksi_agen_voucher WHERE id_data_server = :idsvragen AND keterangan = :ketagen");
                $stmt->bindParam(':idsvragen', $cek_agen['id_data_server'], PDO::PARAM_INT);
                $stmt->bindParam(':ketagen', $keteranganAgen);
                $stmt->execute();
                $TranAgen = $stmt->fetchColumn();
                
                if ($TranAgen === false) {
                    $stmt = $pdo->prepare("INSERT INTO transaksi_agen_voucher (id_data_server, id_agen_voucher, id_ganerate_voucher, debet, keterangan, status) VALUES (:idsvragen, :idagen, '0', :nominal, :ketagen, '3')");
                    $stmt->bindParam(':idsvragen', $cek_agen['id_data_server'], PDO::PARAM_INT);
                    $stmt->bindParam(':idagen', $cek_agen['id_agen_voucher'], PDO::PARAM_INT);
                    $stmt->bindParam(':nominal', $nominal, PDO::PARAM_STR);
                    $stmt->bindParam(':ketagen', $keteranganAgen, PDO::PARAM_STR);
                    $stmt->execute();
                }

                // Ambil Nomor Agen dan buat keterangan transaksi
                $stmt = $pdo->prepare("SELECT nomor_whatsapp, nama FROM agen_voucher WHERE id = :id_agen");
                $stmt->bindParam(':id_agen', $cek_agen['id_agen_voucher'], PDO::PARAM_INT);
                $stmt->execute();
                $nomor_agen = $stmt->fetch(PDO::FETCH_ASSOC);

                $keteranganTransaksi = "Top Up Agen Voucher " . $nomor_agen['nama'] . " Reff:" . $bill_link_id;

                // Cek transaksi dengan id tagihan
                $stmt = $pdo->prepare("SELECT keterangan FROM transaksi WHERE id_data_server = :idsvragen AND keterangan = :ket");
                $stmt->bindParam(':idsvragen', $cek_agen['id_data_server'], PDO::PARAM_INT);
                $stmt->bindParam(':ket', $keteranganTransaksi);
                $stmt->execute();
                $tagid = $stmt->fetchColumn();
                
                if ($tagid === false) {
                    $sql = "INSERT INTO transaksi (id_data_server, id_user_akses, start_time, keterangan, pemasukan, metode_pembayaran, status) VALUES (:idsvragen, '0', :start_time, :keterangan, :pemasukan, 'API Payment', 'Pendapatan Hotspot')";
                    $stmt = $pdo->prepare($sql);
                    $stmt->bindParam(':idsvragen', $cek_agen['id_data_server'], PDO::PARAM_INT);
                    $stmt->bindParam(':start_time', $waktu);
                    $stmt->bindParam(':keterangan', $keteranganTransaksi);
                    $stmt->bindParam(':pemasukan', $nominal);
                    $stmt->execute();
                }

                if ($nomor_agen) {
                    $Pesan = "Saldo anda telah bertambah Rp." . number_format($nominal);
                    $APIwa = new PesanWA();
                    $APIwa->Send_Pesan($cek_agen['id_data_server'], 'sendMessage', [$nomor_agen['nomor_whatsapp']], $Pesan);
                }

                // Matikan link payment gateway
                require '../Flip/Transaction.php';
                $flip = new FlipPaymentGateway($apiKey, $apiUrl);
                $response = $flip->editBill($bill_link_id, 'INACTIVE', $cek_agen['keterangan'], $cek_agen['nominal']);
            }
        }
    }

    // Validasi apakah update berhasil
    if ($stmt->rowCount() === 0) {
        http_response_code(404); // Not Found
        echo "Transaction not found. " . $bill_link_id;
        exit;
    }

    http_response_code(200); // OK
    echo "Transaction status updated.";
} catch (PDOException $e) {
    http_response_code(500); // Internal Server Error
    echo "Database error: " . htmlspecialchars($e->getMessage());
    exit;
}
