<?php
require('db_connection.php');
include('routeros_api.class.php');

// Fungsi untuk memverifikasi signature dari Tripay
function verify_signature($data, $callback_signature, $private_key) {
    $signature = hash_hmac('sha256', json_encode($data), $private_key);
    return hash_equals($signature, $callback_signature);
}

$data = json_decode(file_get_contents('php://input'), true);

if (verify_signature($data, $_SERVER['HTTP_X_CALLBACK_SIGNATURE'], $privateKey)) {
    $merchant_ref = $data['merchant_ref'];
    $status = $data['status'];

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

    if ($status === 'PAID') {
        // Koneksi ke MikroTik
        if ($API->connect($ip_mikrotik, $user_mikrotik, $password_mikrotik, $mikrotik_port)) {
            try {
                // Update status transaksi di database
                $update_query = "UPDATE transaction SET status = 'PAID' WHERE merchant_ref = '$merchant_ref'";
                if ($db->query($update_query) === TRUE) {

                    $get_profile_query = "SELECT profile, type FROM transaction WHERE merchant_ref = '$merchant_ref'";
                    $result = $db->query($get_profile_query);
                    $row = $result->fetch_assoc();
                    $profile = $row['profile'];
                    $type = $row['type'];

                    if ($type === 'secret') {
                        $API->comm('/ppp/secret/set', array(
                            ".id" => $merchant_ref,
                            "profile" => $profile,
                            "comment"   => "lunas | pelanggan: " . $profile,
                        ));

                        $arrID2 = $API->comm("/ppp/active/getall", array(
                            ".proplist" => ".id",
                            "?name" => $merchant_ref,
                        ));
                        if (!empty($arrID2)) {
                            $API->comm("/ppp/active/remove", array(
                                ".id" => $arrID2[0][".id"],
                            ));
                        }
                    } elseif ($type === 'hotspot') {
                        $API->comm("/ip/hotspot/user/add", array(
                            "server"    => "all",
                            "profile"		=> "$profile",
                            "name"      => $merchant_ref,
                            "password"  => $merchant_ref,
                            "comment"   => "vc-tripay",
                        ));
                    }

                    $API->disconnect();

                    echo json_encode(['success' => true, 'message' => 'Transaksi berhasil diperbarui dan profil pengguna diubah.']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Gagal memperbarui status transaksi di database.']);
                }
            } catch (Exception $ex) {
                echo json_encode(['success' => false, 'message' => 'Caught exception: ' . $ex->getMessage()]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'VPN Offline atau router tidak konek.']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Status pembayaran tidak valid.']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Signature tidak valid.']);
}
?>
