<?php
require('database.php');
require('links.php');
// Fetch Website Settings Data
$host = $_SERVER['SERVER_NAME'];
$dir = dirname($_SERVER['SCRIPT_NAME']);
date_default_timezone_set("Asia/Kolkata");
$webres = mysqli_query($ahk_conn,"SELECT * FROM settings WHERE id=1 AND status=1");

$webdata = mysqli_fetch_assoc($webres);
$tng_apiurl=$webdata['tng_apiurl'];
$tng_apikey=$webdata['tng_apikey'];
$tng_gatewaye_url=$webdata['tng_gatewaye_url'];
$tng_gatewaye_apikey=$webdata['tng_gatewaye_apikey'];
$tng_wa_apikey=$webdata['tng_wa_apikey'];
$tng_wa_sender=$webdata['tng_wa_sender'];



function checkSession(){
    if(!$_SESSION['phone']){
        header('Location: ../login.php');
        die();
    }
}


if(isset($_SESSION['phone'])){
    $udata = mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT * FROM users WHERE phone='".$_SESSION['phone']."'"));

//  Check Admin Here 
    function checkAdmin($usertype){
        if($usertype == "admin"){
            return true;
        }else{
            return false;
        }
    }
  

    $nutype =  $udata['type'];
    function ifAdmin(){
        global $nutype;
        if($nutype == 'admin'){
            return true;
        }else{
            return false;
        }
    }



}
// Session END
$ENDPOINT = base64_decode('aHR0cHM6Ly9hcGkuYW11c21zLmluL3NlbmQtbWVzc2FnZQ==');
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
$domain = $protocol . "://" . $_SERVER['HTTP_HOST'];
// -------------------- Commission Function --------------------
function addCommission($ahk_conn, $userPhone, $txnAmount, $parentPhone, $serviceName) {
    if (empty($parentPhone)) {
        return; // Parent phone missing
    }

    global $webdata;
    $commissionPercent = isset($webdata['user_commission']) ? floatval($webdata['user_commission']) : 3;

    $commissionAmount = round(($txnAmount * $commissionPercent) / 100, 2);

    if ($commissionAmount <= 0) {
        return; // No commission to add
    }

    $parentPhoneEsc = mysqli_real_escape_string($ahk_conn, $parentPhone);

    // 🔹 Get Old Balance first
    $oldBalanceQuery = mysqli_query($ahk_conn, "SELECT balance FROM users WHERE phone='$parentPhoneEsc'");
    $oldBalanceRow   = mysqli_fetch_assoc($oldBalanceQuery);
    $oldBalance      = floatval($oldBalanceRow['balance'] ?? 0);

    // 🔹 Update parent balance
    $update = mysqli_query($ahk_conn, 
        "UPDATE users 
         SET balance = balance + $commissionAmount 
         WHERE phone='$parentPhoneEsc'"
    );

    if (!$update) {
        error_log("Commission Error (Balance Update): " . mysqli_error($ahk_conn));
        return;
    }

    // 🔹 Get New Balance after update
    $newBalanceQuery = mysqli_query($ahk_conn, "SELECT balance FROM users WHERE phone='$parentPhoneEsc'");
    $newBalanceRow   = mysqli_fetch_assoc($newBalanceQuery);
    $newBalance      = floatval($newBalanceRow['balance'] ?? 0);

    // 🔹 Purpose message with old + new balance
    $purpose = "Commission from $userPhone on $serviceName | Old: $oldBalance | New: $newBalance";

    // 🔹 Insert into wallethistory
    $insert = mysqli_query($ahk_conn, 
        "INSERT INTO wallethistory (userid, amount, balance, purpose, status, type)
         VALUES ('$parentPhoneEsc', '$commissionAmount', '$newBalance', '" . mysqli_real_escape_string($ahk_conn, $purpose) . "', '1', 'Credit')"
    );

    if (!$insert) {
        error_log("Commission Error (Wallet History): " . mysqli_error($ahk_conn));
    }
}


// Query Execute
function ahkQuery($sql){
    global $ahk_conn ;
    $res = mysqli_query($ahk_conn,$sql);
    return $res;
}
// Count Row Number
// Count Row Number
function ahkRows($sql) {
    global $ahk_conn;
    
    // Execute the query
    $result = ahkQuery($sql);

    // Check if the query was successful
    if ($result === false) {
        // Log or handle the error
        error_log("Query failed: " . mysqli_error($ahk_conn));
        return 0; // Return 0 rows if the query failed
    }
    $wasenderamu=$webwhatsapp;
    
    // Return the number of rows
    return mysqli_num_rows($result);
}
// Fetch Row Data 
function fetchRow($sql){
    global $ahk_conn ;
    $res = mysqli_fetch_assoc(ahkQuery($sql));
    return $res;
}
// Get Website data 
function ahkweb($columnName){
    $res = fetchRow("SELECT * FROM settings WHERE id=1");
    echo $res[$columnName];
}
// Get Particular Column Name of table
function getColumn($tableName,$columnName,$Identity){
    $sql = "SELECT * FROM ". $tableName . " WHERE ".  $Identity ;
    if(ahkRows($sql)>0){
        $res = fetchRow($sql);
        echo $res[$columnName];
    }else{
        return "data not Found";
    }
}
// Get Safe Value 
function getSafe($value){
    global $ahk_conn;
    $safe = mysqli_real_escape_string($ahk_conn,$value);
    return $safe;
}
// print Array Function 
function printR($data){
    echo "<pre>";
    print_r($data);
}
function ahkRedirect($url='',$time){
    ?>
    <script>
         setTimeout(() => {
            window.location='<?php echo $url; ?>';
        }, <?php echo $time; ?>);
    </script>
    <?php 
}
function showAlert($fmsg = '',$smsg ='',$type='success'){
    ?>
    <script>
       $(function(){
                Swal.fire(
                '<?php echo $fmsg; ?>', 
                '<?php echo $smsg; ?>', 
                '<?php echo $type; ?>'
            )
        })
    </script>
    <?php 
}


?>
