
<?php

define("IN_SITE", true);
require_once(__DIR__."/../libs/db.php");
require_once(__DIR__."/../libs/lang.php");
require_once(__DIR__."/../libs/helper.php");
require_once(__DIR__."/../libs/database/users.php");
 
$CMSNT = new DB();
$Mobile_Detect = new Mobile_Detect();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    if (!empty($data)) {
        $idData = validate_alphanumeric($data['id'], 100);
        if ($idData === false) {
            die('Invalid transaction ID');
        }
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.flutterwave.com/v3/transactions/$idData/verify");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer ".$CMSNT->site('flutterwave_secretKey')
        ]);
        $response = curl_exec($ch);
        curl_close($ch);
        $response = json_decode($response, true);
        
        $id = validate_alphanumeric($response['data']['id'], 100);
        $txRef = validate_alphanumeric($response['data']['tx_ref'], 100);
        $currency = validate_string($response['data']['currency'], 10);
        $amount = validate_float($response['data']['amount'], 0.01);
        
        if ($id === false || $txRef === false || $currency === false || $amount === false) {
            die('Invalid response data');
        }
        
        $price = $amount * $CMSNT->site('flutterwave_rate');
        if ($response['data']['status'] == 'successful') {
            if($row = $CMSNT->get_row_safe("SELECT * FROM `payment_flutterwave` WHERE `tx_ref` = ? AND `currency` = ? AND `status` = 'pending'", [$txRef, $currency])){
                $user = new users;
                $isCong = $user->AddCredits($row['user_id'], $price, __('Recharge Flutterwave').' #'.$id);
                if($isCong){
                    $CMSNT->update('payment_flutterwave', [
                        'status'   => 'success',
                        'update_gettime'    => gettime(),
                        'amount'    => $amount
                    ], " `id` = ? AND `status` = 'pending'", [$row['id']]);
                }
            }
        }
    }
}