<?php
require("../config.php");

$DT_Pgateway = $conn->query("SELECT * FROM sakurupiah WHERE id = '1' OR nama = 'SAKURUPIAH'");
$data_Pgateway = $DT_Pgateway->fetch_assoc();

// Ambil data JSON
$json = file_get_contents('php://input');

// Ambil callback signature
$callbackSignature = isset($_SERVER['HTTP_X_CALLBACK_SIGNATURE'])
    ? $_SERVER['HTTP_X_CALLBACK_SIGNATURE']
    : '';

// Isi dengan api key merchant anda
$apiKey = $data_Pgateway['secret_key'];

// Generate signature untuk dicocokkan dengan X-Callback-Signature
$signature = hash_hmac('sha256', $json, $apiKey);

// Validasi signature
if ($callbackSignature !== $signature) {
    exit(json_encode([
        'success' => false,
        'message' => 'Invalid signature',
    ]));
}

try {
    
$data = json_decode($json);

if (JSON_ERROR_NONE !== json_last_error()) {
    exit(json_encode([
        'success' => false,
        'message' => 'Invalid data send by payment gateway',
    ]));
}

// Hentikan proses jika callback event-nya bukan payment_status
if ('payment_status' !== $_SERVER['HTTP_X_CALLBACK_EVENT']) {
    exit(json_encode([
        'success' => false,
        'message' => 'Unrecognized callback event: ' . $_SERVER['HTTP_X_CALLBACK_EVENT'],
    ]));
}

// Mengambil data callback
$merchantRef = $data->trx_id;
$payment_MerchantRef = $data->merchant_ref;
$payment_Status = $data->status;
$payment_StatusKode = $data->status_kode;


if ($data->status == "berhasil" and $payment_StatusKode == 1) {
    
    $ctrx = $conn->query("SELECT * FROM deposit WHERE merchant_ref = '".$merchantRef."' AND kode_deposit = '".$payment_MerchantRef."' AND status = 'Pending'");
     
    if ($ctrx->num_rows == 1) {
        
            $trx = $ctrx->fetch_assoc();
            
            $get_saldo = $trx['get_saldo'];
            $kode_deposit = $trx['kode_deposit'];
            $cek_nama = $trx['username'];
            
            $referral = $conn->query("SELECT * FROM referral_kode WHERE username = '".$cek_nama."' ");
            $data_follow = $referral->fetch_assoc();
            $nilai_coin = $conn->query("SELECT * FROM penukaran_coin WHERE tipe = 'Deposit' ");
            $data_coin = $nilai_coin->fetch_assoc();
            $set_coin = $data_coin['jumlah_coin'];
            if($referral->num_rows == 1){
                $follow = $data_follow['follow'];
                    $cari_ref = $conn->query("SELECT * FROM referral_kode WHERE kode = '".$follow."' ");
                    if($cari_ref->num_rows == 1){
                        $conn->query("UPDATE referral_kode SET coin = coin+$set_coin WHERE kode = '".$follow."'");
                    }
            }

            $conn->query("UPDATE deposit SET status = 'Success' WHERE id = '".$trx['id']."'");
            
            $conn->query("UPDATE users SET saldo = saldo+$get_saldo WHERE username = '".$trx['username']."'");
            
            $conn->query("INSERT INTO history_saldo VALUES ('', '".$trx['username']."', 'Penambahan Saldo', '$get_saldo', 'Mendapatkan Saldo Isi Saldo Via ".$trx['tipe']." ".$trx['provider']." Dengan Kode Isi Saldo : $kode_deposit', '$date', '$time')");
            
            exit(json_encode([
            'success' => true,
            'message' => 'Payment status berhasil dan Berhasil Update Database',
        ]));
        } else {
            exit(json_encode([
            'success' => true,
            'message' => 'Payment status berhasil namun data di database tidak ditemukan atau kemungkinan sudah di update',
        ]));
        
        }
    
} else if (($data->status == "expired" and $payment_StatusKode == 2)) {
    
    $ctrx = $conn->query("SELECT * FROM deposit WHERE merchant_ref = '".$merchantRef."' AND kode_deposit = '".$payment_MerchantRef."' AND status = 'Pending'");
    
    if ($ctrx->num_rows == 1) {
        
            $trx = $ctrx->fetch_assoc();

            $conn->query("UPDATE deposit SET status = 'Error' WHERE id = '".$trx['id']."'");
           
            exit(json_encode([
            'success' => true,
            'message' => 'Payment status expired successfull',
        ]));
        } else {
            exit(json_encode([
            'success' => true,
            'message' => 'Payment status expired namun data di database tidak ditemukan atau kemungkinan sudah di update',
        ]));
        }  
} else if (($data->status == "pending" and $payment_StatusKode == 0)) {

    //Jika status pending mungkin ada beberapa aksi yang ingin di lakukan tambahkan disini atau abaikan jika tidak ada aksi ketika status tetap pending biarkan cukup respon json yang di simpan
    exit(json_encode([
            'success' => true,
            'message' => 'Payment status pending',
        ]));
        
} else {
    
   throw new Exception('Error Data Status Callback');
}
} catch (Exception $e) {
exit(json_encode(['success' => false, 'message' => $e->getMessage()]));
}
?>