<?php

include_once __DIR__ . '/../secrets.php';
include '../db_connect.php';

$userid = $_POST['userid'];
$number = $_POST['number'];
$balance = $_POST['balance'];
$operator = $_POST['operator'];
$title = $_POST['title'];
$time = $_POST['time'];
$transid = $_POST['transid'];
$simtype = $_POST['simtype'];
$profit = $_POST['profit'];
$details = $_POST['details'];
$key = $_POST['key'];

$security_key = decrypData($key);

if ($security_key === false) {
    echo 'Invalid encryption data';
    exit;
}

if ($security_key == SECURITY_KEY_PLAIN) {

    $con = dbConnect();
    $sql1 = "SELECT * FROM history_table WHERE transid = '$transid'";
    $result = mysqli_query($con, $sql1);
    $rows = mysqli_num_rows($result);

    if ($rows <= 0) {

        // Recharge API URL
        $apiUrl = 'https://rechargegetway.top/sendapi/request';

        // API POST data
        $postData = array(
            'number'   => $number,
            'service'  => '64',
            'amount'   => $balance,
            'type'     => $simtype,
            'id'       => $transid,
            'user'     => '01312112001',
            'key'      => '9ZHZO0O0XS0B4UW2X2NO4GB97YTBAS08YJIQHD1XDTA7PN0J82',
            'operator' => $operator
        );

        $headers = array(
            'band-key: flexisoftwarebd'
        );

        // cURL call
        $ch = curl_init($apiUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $apiResponse = curl_exec($ch);
        $curlError = curl_error($ch);
        curl_close($ch);

        $responseData = json_decode($apiResponse, true);

        // get previous balance
        $prevBalRes = $con->query("SELECT balance FROM signup WHERE userid = '$userid' LIMIT 1");
        if (!$prevBalRes || $prevBalRes->num_rows === 0) {
            echo 'User not found';
            exit();
        }
        $prevBal = (float)$prevBalRes->fetch_assoc()['balance'];
        $newBal = round($prevBal - $balance + $profit, 2);

        // check API response
        if ($curlError || !isset($responseData['success']) || $responseData['success'] != true || $responseData['status'] != 1) {
            // API Failed → Pending
            $status = 'Pending';
        } else {
            $status = 'Success';
        }
        
        $sql2 = "UPDATE signup SET balance = ROUND(balance - $balance + $profit, 2) WHERE userid = '$userid'";
        mysqli_query($con, $sql2);

        // Insert history
        $sql = "INSERT INTO history_table(userid, number, balance, profit, oldbalance, time, operator, title, transid, status, details, lastnumber, type, newbalance) VALUES
            ('$userid', '$number', '$balance', '$profit', '$prevBal', '$time', '$operator','$title', '$transid', '$status', '$details', 'N/A', 'Send', '$newBal')";
        $result = mysqli_query($con, $sql);

        if ($result) {
            echo 'Successfully';
        } else {
            echo 'Query Error: ' . mysqli_error($con);
        }

    } else {
        echo 'Already Exists';
    }

} else {
    echo 'Invalid password';
}

?>
