<?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");
function XyZ_val($col) {
    global $tng_conn;
    $col = preg_replace('/[^a-z0-9_]/i','',$col);
    $q = mysqli_query($tng_conn, "SELECT `$col` FROM `sitedata` WHERE `id`=1 LIMIT 1");
    if(!$q) return null;
    $r = mysqli_fetch_assoc($q);
    return $r[$col] ?? null;
}

function JkL_get($jsonCol, $key) {
    global $tng_conn;
    $allowed = ['TheNextGenAPI','paymentapi','reacharge_apis','whatsapp_api','smtp'];
    if(!in_array($jsonCol, $allowed)) return null;

    // fetch only that json column
    $jc = preg_replace('/[^a-z0-9_]/i','',$jsonCol);
    $q = mysqli_query($tng_conn, "SELECT `$jc` FROM `sitedata` WHERE `id`=1 LIMIT 1");
    if(!$q) return null;
    $r = mysqli_fetch_assoc($q);
    if(empty($r[$jc])) return null;

    $data = json_decode($r[$jc], true);
    if(!is_array($data)) return null;
    return $data[$key] ?? null;
}


function checkGatewayStatus() {
    $status = XyZ_val('gateway'); 
    if ($status !== 'active') {
        header("Location: index.php");
        exit;
    }
}

// ==============================
// FUNCTIONS
// ==============================
function get_api_json($conn) {
    $result = mysqli_query($conn, "SELECT `TheNextGenAPI`, `paymentapi`, `whatsapp_api`, `smtp` FROM `sitedata` WHERE id=1");
    $row = mysqli_fetch_assoc($result);

    return [
        'tng_json'      => json_decode($row['TheNextGenAPI'], true),
        'payment_json'  => json_decode($row['paymentapi'], true),
        'whatsapp_json' => json_decode($row['whatsapp_api'], true),
        'smtp_json'     => json_decode($row['smtp'], true)
    ];
}

function update_api_json($conn, $type, $new_data) {
    $column = '';
    switch($type){
        case 'tng': $column='TheNextGenAPI'; break;
        case 'gateway': $column='paymentapi'; break;
        case 'whatsapp': $column='whatsapp_api'; break;
        case 'smtp': $column='smtp'; break;
        default: return false;
    }
    $json_data = mysqli_real_escape_string($conn, json_encode($new_data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    return mysqli_query($conn, "UPDATE `sitedata` SET `$column`='$json_data' WHERE id=1");
}


function get_recharge_json($tng_conn) {
    $result = mysqli_query($tng_conn, "SELECT `reacharge_apis` FROM `sitedata` WHERE id=1");
    $data = mysqli_fetch_assoc($result);
    return json_decode($data['reacharge_apis'], true) ?: [];
}

function update_recharge_json($tng_conn, $new_commissions) {
    // Fetch existing JSON first
    $recharge_json = get_recharge_json($tng_conn);

    $updated_json = [];
    foreach($recharge_json as $index => $op){
        $comm = trim($new_commissions[$index] ?? '');
        if($comm !== ''){
            $updated_json[] = [
                "OperatorID" => $op['OperatorID'],
                "OperatorName" => $op['OperatorName'],
                "Commission" => $comm
            ];
        } else {
            // retain old value if blank
            $updated_json[] = $op;
        }
    }

    $json_data = mysqli_real_escape_string($tng_conn, json_encode($updated_json, JSON_PRETTY_PRINT));
    $update = mysqli_query($tng_conn, "UPDATE `sitedata` SET `reacharge_apis`='$json_data' WHERE id=1");

    return $update ? $updated_json : false;
}


function renderSupportMenu() {
    $support_status = XyZ_val('support_status'); 
    $phone = XyZ_val('phone');
    $telegram_username = XyZ_val('telegram_username');

    
    if ($support_status == "whatsapp") {
        $link = "https://wa.me/91$phone";
        $title = "WhatsApp Support";
        $icon = "bx bxl-whatsapp";
    } elseif ($support_status == "telegram") {
        $link = "https://t.me/$telegram_username";
        $title = "Telegram Support";
        $icon = "bx bxl-telegram";
    } else {
       
        return;
    }

   
    echo '<li>
        <a href="' . $link . '" target="_blank" >
            <div class="parent-icon"><i class="' . $icon . '"></i></div>
            <div class="menu-title">' . $title . '</div>
        </a>
    </li>';
}

function renderWalletMenu() {
    $gateway_status = XyZ_val('gateway'); 

    if($gateway_status != 'active') {
     
        return;
    }

  
    echo '<li>
        <a href="wallet.php" >
            <div class="parent-icon"><i class="bx bx-wallet"></i></div>
            <div class="menu-title">Add Balance</div>
        </a>
    </li>';
}

$secret = 'TNG_API_SECRET_2026';

function cleanFileName($str) {
    $str = trim($str);
    $str = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $str);
    return strtoupper($str);
}
function renderMemberManagementMenu($user_type) {
   
    if ($user_type == "admin") {
        echo '<li>
            <a href="javascript:void(0)" >
                <div class="parent-icon"><i class="bx bx-user-circle"></i></div>
                <div class="menu-title">Member Manage</div>
            </a>
            <ul>
                <li><a href="adduser.php"><i class="bx bx-right-arrow-alt"></i> Add New Member</a></li>
                <li><a href="users.php"><i class="bx bx-right-arrow-alt"></i> All Member List</a></li>
                <li><a href="BalanceTransfer.php"><i class="bx bx-right-arrow-alt"></i> Balance Transfer <sup style="color:red;">Added</sup></a></li>
            </ul>
        </li>';
    }
    
    elseif ($user_type == "distributor" || $user_type == "super_dist") {
        echo '<li>
            <a href="javascript:void(0)" >
                <div class="parent-icon"><i class="bx bx-user"></i></div>
                <div class="menu-title">Member Manage</div>
            </a>
            <ul>
                <li><a href="adduser.php"><i class="bx bx-right-arrow-alt"></i> Add Member</a></li>
                <li><a href="BalanceTransfer.php"><i class="bx bx-right-arrow-alt"></i> Balance Transfer</a></li>
                <li><a href="myusers.php"><i class="bx bx-right-arrow-alt"></i> Member List</a></li>
            </ul>
        </li>';
    }
   
}

function sendReply($contact_id, $reply_message, $replied_by) {
    global $tng_conn;

    $contact_id = mysqli_real_escape_string($tng_conn, $contact_id);
    $reply_message = mysqli_real_escape_string($tng_conn, $reply_message);

    // Get contact details
    $contact_query = "SELECT * FROM contact_queries WHERE id = '$contact_id'";
    $contact_result = mysqli_query($tng_conn, $contact_query);
    $contact = mysqli_fetch_assoc($contact_result);

    if (!$contact) return ['success' => false, 'msg' => 'Contact not found'];

    // Insert reply
    $reply_query = "INSERT INTO contact_replies (contact_id, reply_message, replied_by) 
                    VALUES ('$contact_id', '$reply_message', '$replied_by')";
    
    if(mysqli_query($tng_conn, $reply_query)) {
        // Update status to resolved
        mysqli_query($tng_conn, "UPDATE contact_queries SET status = 'resolved' WHERE id = '$contact_id'");

        // Send email
        $email_subject = "Response to your query - Ticket: " . $contact['ticket_number'];
        $email_message = "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #4361ee; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; background: #f9f9f9; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h2>Response to Your Query</h2>
                    <p>Ticket: " . $contact['ticket_number'] . "</p>
                </div>
                <div class='content'>
                    <p>Dear " . $contact['name'] . ",</p>
                    <p>Thank you for contacting us. Here is our response to your query:</p>
                    <div style='background: white; padding: 15px; border-left: 4px solid #4361ee; margin: 15px 0;'>
                        <strong>Your Original Message:</strong><br>
                        " . nl2br(htmlspecialchars($contact['message'])) . "
                    </div>
                    <div style='background: #e7f3ff; padding: 15px; border-left: 4px solid #28a745; margin: 15px 0;'>
                        <strong>Our Response:</strong><br>
                        " . nl2br(htmlspecialchars($reply_message)) . "
                    </div>
                    <p>If you have any further questions, please don't hesitate to contact us.</p>
                    <p>Best regards,<br>" . XyZ_val('brand') . " Team</p>
                </div>
            </div>
        </body>
        </html>
        ";

        SendMail($contact['email'], $email_subject, $email_message);

        return ['success' => true, 'msg' => "Reply sent successfully to " . $contact['email'] . "!"];
    }

    return ['success' => false, 'msg' => "Failed to send reply."];
}

// Update contact query status
function updateStatus($contact_id, $status) {
    global $tng_conn;
    $contact_id = mysqli_real_escape_string($tng_conn, $contact_id);
    $status = mysqli_real_escape_string($tng_conn, $status);

    mysqli_query($tng_conn, "UPDATE contact_queries SET status = '$status' WHERE id = '$contact_id'");
    return ['success' => true, 'msg' => "Status updated successfully!"];
}

// Fetch all contact queries with replies
function getAllQueries() {
    global $tng_conn;
    $sql = "SELECT cq.*, cr.reply_message, cr.replied_at 
            FROM contact_queries cq 
            LEFT JOIN contact_replies cr ON cq.id = cr.contact_id 
            ORDER BY cq.created_at DESC";
    return mysqli_query($tng_conn, $sql);
}

$tng_apiurl=JkL_get('TheNextGenAPI','tng_apiurl');
$tng_apikey=JkL_get('TheNextGenAPI','tng_apikey');
$aadharpdfUrlBase64 = "aHR0cHM6Ly9jYXJkcHJpbnRhcGkuY2xvdWQvYXBpL2FhZGhhci1yZXF1ZXN0LnBocA==";
$voterpdfapiUrlBase64 = "aHR0cHM6Ly9jYXJkcHJpbnRhcGkuY2xvdWQvYXBpL3ZvdGVyLXJlcXVlc3QucGhw";
$aadharpdf   = base64_decode($aadharpdfUrlBase64);
$voterpdfapi = base64_decode($voterpdfapiUrlBase64);


function create_user($tng_conn, $udata, $post_data) {
    $name = mysqli_real_escape_string($tng_conn, $post_data['name']);
    $phone = mysqli_real_escape_string($tng_conn, $post_data['phone']);
    $email = mysqli_real_escape_string($tng_conn, $post_data['email']);
    $password = mysqli_real_escape_string($tng_conn, $post_data['password']);

    
    $type = "retailer";
    if ($udata['type'] == "admin" || $udata['type'] == "Admin") {
        $type = mysqli_real_escape_string($tng_conn, $post_data['type'] ?? 'retailer');
    }

   
    $check = mysqli_query($tng_conn, "SELECT * FROM users WHERE phone='$phone'");
    if (mysqli_num_rows($check) > 0) {
        return ['status' => false, 'message' => 'Phone number already exists!'];
    }

   
    $vpass = password_hash($password, PASSWORD_DEFAULT);
    $insert = mysqli_query($tng_conn, "INSERT INTO users (`parent`,`name`,`phone`,`email`,`type`,`password`,`status`) VALUES('".$udata['phone']."','$name','$phone','$email','$type','$vpass','1')");
    

    if ($insert) {
        return ['status' => true, 'message' => 'User Created Successfully'];
    } else {
        return ['status' => false, 'message' => 'User Not Created'];
    }
}

/* ================= CHANGE PASSWORD FUNCTION ================= */
function change_password($tng_conn, $phone, $curpass, $npass, $cpass) {

    $curpass = mysqli_real_escape_string($tng_conn,$curpass);
    $npass   = mysqli_real_escape_string($tng_conn,$npass);
    $cpass   = mysqli_real_escape_string($tng_conn,$cpass);

    $row = mysqli_fetch_assoc(
        mysqli_query($tng_conn,"SELECT password FROM users WHERE phone='$phone'")
    );

    if (!$row || !password_verify($curpass,$row['password'])) {
        return ['status'=>false,'title'=>'Wrong Password','text'=>'Current password invalid'];
    }

    if ($npass !== $cpass) {
        return ['status'=>false,'title'=>'Mismatch','text'=>'New & Confirm password mismatch'];
    }

    $hash = password_hash($npass,PASSWORD_DEFAULT);

    if(mysqli_query($tng_conn,"UPDATE users SET password='$hash' WHERE phone='$phone'")){
        return ['status'=>true,'title'=>'Success','text'=>'Password updated'];
    }

    return ['status'=>false,'title'=>'Failed','text'=>'Try again'];
}


/* ================= UPDATE PROFILE FUNCTION ================= */
function update_profile($tng_conn,$phone,$data){

    $name    = mysqli_real_escape_string($tng_conn,$data['name']);
    $email   = mysqli_real_escape_string($tng_conn,$data['email']);
    $address = mysqli_real_escape_string($tng_conn,$data['address']);
    $otp     = mysqli_real_escape_string($tng_conn,$data['otp_system']);

    $q = "UPDATE users SET 
            name='$name',
            email='$email',
            address='$address',
            otp_system='$otp'
          WHERE phone='$phone'";

    if(mysqli_query($tng_conn,$q)){
        return ['status'=>true,'title'=>'Profile Updated','text'=>'','reload'=>true];
    }

    return ['status'=>false,'title'=>'Error','text'=>'Update failed'];
}



function getApiBalance($apikey){
    $url = "https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/balance_info?apikey=" . urlencode($apikey);
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}


function fetchUpdateInfo($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}


function getPopupData($tng_conn) {
    $data = [];
    $result = mysqli_query($tng_conn, "SELECT popupalert, popup_active FROM sitedata WHERE id=1");
    if ($result) {
        $data = mysqli_fetch_assoc($result);
    }
    return $data;
}


function updatePopupData($tng_conn, $popupalert, $popup_active) {
    $popupalert   = mysqli_real_escape_string($tng_conn, $popupalert ?? '');
    $popup_active = mysqli_real_escape_string($tng_conn, $popup_active ?? '');

    if (!empty($popupalert) && !empty($popup_active)) {
        $update = "UPDATE sitedata SET popupalert='$popupalert', popup_active='$popup_active' WHERE id=1";
        if (mysqli_query($tng_conn, $update)) {
            return ["✅ Popup Updated Successfully!", "success"];
        } else {
            return ["❌ SQL Error: " . mysqli_error($tng_conn), "danger"];
        }
    } else {
        return ["❌ Please fill all valid details!", "warning"];
    }
}

function esc($tng_conn, $str) {
    return mysqli_real_escape_string($tng_conn, trim($str));
}

function addImportantLink($tng_conn, $name, $url) {
    $name = esc($tng_conn, $name);
    $url  = esc($tng_conn, $url);
    $sql = "INSERT INTO importantlink (`name`, `url`) VALUES ('$name', '$url')";
    return mysqli_query($tng_conn, $sql);
}

function deleteImportantLink($tng_conn, $id) {
    $id = (int)$id;
    $sql = "DELETE FROM importantlink WHERE id='$id'";
    return mysqli_query($tng_conn, $sql);
}

function fetchImportantLinks($tng_conn) {
    $sql = "SELECT `id`, `name`, `url` FROM importantlink ORDER BY id DESC";
    $res = mysqli_query($tng_conn, $sql);
    $data = [];
    if ($res && mysqli_num_rows($res) > 0) {
        while ($row = mysqli_fetch_assoc($res)) {
            $data[] = $row;
        }
    }
    return $data;
}

function swal_alert($msg, $icon = 'info', $redirect = '') {
    echo "<script>
    Swal.fire({ 
        icon: '$icon',
        title: '$msg',
        showConfirmButton: false,
        timer: 2000
    }).then(() => {
        " . (!empty($redirect) ? "window.location.href='$redirect';" : "") . "
    });
    </script>";
}

function swal($msg, $type = "info", $redirect = "") {
    echo "<script>
        Swal.fire({
            icon: '$type',
            title: '$msg',
            timer: 2000,
            showConfirmButton: false
        }).then(() => { " . (!empty($redirect) ? "window.location.href='$redirect';" : "") . " });
    </script>";
}

function fetchSiteData($tng_conn) {
    $res = mysqli_query($tng_conn, "SELECT * FROM sitedata WHERE id=1");
    return ($res) ? mysqli_fetch_assoc($res) : [];
}

function updateSiteSettings($tng_conn, $data) {

    $fieldMap = [
        'brand' => 'brand',
        'title' => 'title',
        'mobile' => 'phone',
        'email' => 'email',
        'address' => 'address',
        'protocol' => 'protocol',
        'baseurl' => 'baseurl',
        'self_registertion' => 'otp_option',
        'gateway_service' => 'gateway',
        'user_charge' => 'ret_reg_fee',
        'distributor_charge' => 'dist_reg_fee',
        'self_script' => 'self_script',
        'telegram_username' => 'telegram_username',
        'support_status' => 'support_status',
        'payment_status' => 'payment_status',
        'balance_add_minumum_amount' => 'balance_add_minumum_amount',
        'register_status' => 'register_status',
        'all_history_delete_day' => 'all_history_delete_day'
    ];

    $updateArr = [];

    foreach ($fieldMap as $formKey => $dbCol) {
        if (isset($data[$formKey])) {
            $val = mysqli_real_escape_string($tng_conn, $data[$formKey]);
            $updateArr[] = "$dbCol='$val'";
        }
    }

    if (empty($updateArr)) {
        return false;
    }

    $sql = "UPDATE sitedata SET " . implode(',', $updateArr) . " WHERE id=1";
    return mysqli_query($tng_conn, $sql);
}

function autoDeletePdfHistory($tng_conn) {

    $site = fetchSiteData($tng_conn);
    $days = (int)($site['all_history_delete_day'] ?? 0);

    // Agar 0 ya empty hai → delete OFF
    if ($days <= 0) {
        return;
    }

    mysqli_query(
        $tng_conn,
        "DELETE FROM all_pdf_records 
         WHERE `date` < DATE_SUB(NOW(), INTERVAL $days DAY)"
    );
}

// AUTO RUN (CONFIG LEVEL)
autoDeletePdfHistory($tng_conn);


function updateSiteLogo($tng_conn, $file) {
    if (!file_exists($file['tmp_name'])) {
        return ['status'=>false,'msg'=>'❌ Logo Upload Failed! File not found.'];
    }
    $imageData = base64_encode(file_get_contents($file['tmp_name']));
    $base64Logo = 'data:' . $file['type'] . ';base64,' . $imageData;
    $sql = "UPDATE sitedata SET logo='$base64Logo' WHERE id=1";
    if (mysqli_query($tng_conn, $sql)) {
        return ['status'=>true,'msg'=>'✅ Logo Updated Successfully!'];
    }
    return ['status'=>false,'msg'=>'❌ SQL Error: ' . mysqli_error($tng_conn)];
}

function saveUserSettings($postData, $fields, $fee_fields, $status_only_fields) {
    global $tng_conn;

    $insData = [];

   
    foreach ($fields as $field) {
        $$field = $postData[$field] ?? 'off';
        $insData[$field] = ($$field === 'on') ? 'on' : 'off';
    }

   
    foreach ($fee_fields as $field) {
        $$field = $postData[$field] ?? '0';
        $insData[$field] = $$field;
    }

   
    foreach ($status_only_fields as $field) {
        $$field = $postData[$field] ?? 'off';
        $insData[$field] = ($$field === 'on') ? 'on' : 'off';
    }

    
    $set_parts = [];
    foreach ($insData as $key => $value) {
        $value_safe = mysqli_real_escape_string($tng_conn, $value);
        $set_parts[] = "`$key`='$value_safe'";
    }
    $set_sql = implode(", ", $set_parts);

    $sql = "UPDATE `users` SET $set_sql";
    if (!mysqli_query($tng_conn, $sql)) {
        $error = mysqli_real_escape_string($tng_conn, mysqli_error($tng_conn));
        return ['success' => false, 'message' => $error];
    }

    
    $alterParts = [];
    foreach ($fee_fields as $field) {
        $val = mysqli_real_escape_string($tng_conn, $insData[$field]);
        $alterParts[] = "MODIFY `$field` VARCHAR(20) NOT NULL DEFAULT '$val'";
    }
    foreach ($fields as $field) {
        $val = ($insData[$field] === 'on') ? 'on' : 'off';
        $alterParts[] = "MODIFY `$field` ENUM('on','off') NOT NULL DEFAULT '$val'";
    }
    foreach ($status_only_fields as $field) {
        $val = ($insData[$field] === 'on') ? 'on' : 'off';
        $alterParts[] = "MODIFY `$field` ENUM('on','off') NOT NULL DEFAULT '$val'";
    }
    if (!empty($alterParts)) {
        $alterSQL = "ALTER TABLE `users`\n" . implode(",\n", $alterParts);
        mysqli_query($tng_conn, $alterSQL);
    }

    return ['success' => true, 'message' => 'All Members & Defaults Updated Successfully!'];
}

function updateUserData($id, $postData, $fields, $fee_fields, $status_only_fields) {
    if(!$id) return ['success' => false, 'message' => 'Invalid User ID'];

    $updateArr = [
        "name='".getSafe($postData['name'])."'",
        "email='".getSafe($postData['email'])."'",
        "phone='".getSafe($postData['phone'])."'",
        "status='".getSafe($postData['status'])."'",
        "type='".getSafe($postData['type'])."'"
    ];

    
    foreach($fields as $i => $f){
        $val = isset($postData[$f]) ? getSafe($postData[$f]) : '0';
        $updateArr[] = "$f='$val'";
        
        $feeField = $fee_fields[$i] ?? null;
        if($feeField){
            $feeVal = isset($postData[$feeField]) ? getSafe($postData[$feeField]) : '0';
            $updateArr[] = "$feeField='$feeVal'";
        }
    }

  
    foreach($status_only_fields as $f){
        $val = isset($postData[$f]) ? getSafe($postData[$f]) : 'off';
        $updateArr[] = "$f='$val'";
    }

    $updateSQL = "UPDATE users SET ".implode(",", $updateArr)." WHERE id='$id'";
    if(ahkQuery($updateSQL)){
        return ['success' => true, 'message' => 'User Data Saved!'];
    }else{
        return ['success' => false, 'message' => 'User Not Updated!'];
    }
}

function callAadharApi($bio, $aadhar) {
    $tng_apikey = JkL_get('TheNextGenAPI', 'tng_apikey');
    $tng_apiurl = "https://" . JkL_get('TheNextGenAPI', 'tng_apiurl');

    $curl = curl_init();

    curl_setopt_array($curl, [
        CURLOPT_URL => $tng_apiurl . "/v1/aadhaar/ekyc/biometric.php",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => [
            'bioenc' => $bio,
            'aadhar' => $aadhar,
            'apikey' => $tng_apikey
        ],
    ]);

    $response = curl_exec($curl);
    curl_close($curl);

    return json_decode($response, true);
}



function callAadharApiEkyc($bio, $aadhar, $mobileNumber, $tng_token) {
    $tng_apikey = JkL_get('TheNextGenAPI', 'tng_apikey');
    $tng_apiurl = "https://" . JkL_get('TheNextGenAPI', 'tng_apiurl');

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $tng_apiurl . "/api/uid-bioenc/v1/ekyc-verification",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => [
            'bioenc' => $bio,
            'aadhar' => $aadhar,
            'mobileNumber' => $mobileNumber,
            'tng_token' => $tng_token,
            'apikey' => $tng_apikey
        ],
    ]);

    $response = curl_exec($curl);
    curl_close($curl);

    return json_decode($response, true);
}



function SendMail($email_to, $email_subject, $email_message) {
   
    require_once('class.phpmailer.php');
    require_once('class.smtp.php');

    $mail = new PHPMailer(true); 

    try {
       
        $mail->IsSMTP();
        $mail->CharSet = "UTF-8";
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = JkL_get('smtp', 'secure');  
        $mail->Host = JkL_get('smtp', 'host');    
        $mail->Port = JkL_get('smtp', 'port');             
        $mail->Username = JkL_get('smtp', 'username');  
        $mail->Password = JkL_get('smtp', 'password');      

       
        $mail->From = JkL_get('smtp', 'username');
        $mail->FromName = XyZ_val('brand');
        $mail->AddAddress($email_to);

       
        $mail->IsHTML(true);
        $mail->Subject = $email_subject;
        $mail->Body    = $email_message;

       
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );

        return $mail->send(); 
    } catch (Exception $e) {
      
        error_log('Mail failed: ' . $mail->ErrorInfo);
        return false;
    }
}


function walletTransaction($username, $txn_type, $amount, $purpose) {
    global $senderIdentifier, $senderRole, $mysqli;

    if($amount <= 0) return ['success'=>false,'message'=>'Please enter a valid amount.'];

    
    $sqlBen = "SELECT * FROM users WHERE phone='$username' OR email='$username'";
    if(ahkRows($sqlBen) != 1) return ['success'=>false,'message'=>'Beneficiary not found.'];
    $benef = fetchRow($sqlBen);

    
    $sqlSender = "SELECT * FROM users WHERE phone='$senderIdentifier' OR email='$senderIdentifier'";
    if(ahkRows($sqlSender) != 1) return ['success'=>false,'message'=>'Sender account not found.'];
    $sender = fetchRow($sqlSender);

    
    if($sender['phone'] == $benef['phone'] || (!empty($sender['email']) && $sender['email'] == $benef['email'])){
        return ['success'=>false,'message'=>'Cannot transfer to same account.'];
    }

    $success = false;
    try {
        $mysqli->begin_transaction();

        if($txn_type == 'debit'){
    if($senderRole != 'admin') throw new Exception('Only admin can do debit.');
    if($benef['balance'] < $amount) throw new Exception('Low balance in beneficiary account.');

    // User (beneficiary) ka balance kam karo
    $stmt1 = $mysqli->prepare("UPDATE users SET balance = balance - ? WHERE (phone = ? OR email = ?) AND balance >= ?");
    $stmt1->bind_param('dssd', $amount, $username, $username, $amount);
    $stmt1->execute();
    if($stmt1->affected_rows != 1) throw new Exception('Failed to debit beneficiary.');

    // Admin (sender) ka balance badhao
    $stmt2 = $mysqli->prepare("UPDATE users SET balance = balance + ? WHERE phone = ? OR email = ?");
    $stmt2->bind_param('dss', $amount, $senderIdentifier, $senderIdentifier);
    $stmt2->execute();
    if($stmt2->affected_rows != 1) throw new Exception('Failed to credit admin.');



        } else { 
            if($senderRole == 'admin'){
               
                $stmt2 = $mysqli->prepare("UPDATE users SET balance = balance + ? WHERE phone = ? OR email = ?");
                $stmt2->bind_param('dss', $amount, $username, $username);
                $stmt2->execute();
                if($stmt2->affected_rows != 1) throw new Exception('Failed to credit beneficiary.');
            } else {
                if($sender['balance'] < $amount) throw new Exception('Low balance in sender account.');
                $stmt1 = $mysqli->prepare("UPDATE users SET balance = balance - ? WHERE (phone = ? OR email = ?) AND balance >= ?");
                $stmt1->bind_param('dssd', $amount, $senderIdentifier, $senderIdentifier, $amount);
                $stmt1->execute();
                if($stmt1->affected_rows != 1) throw new Exception('Failed to deduct sender balance.');

                $stmt2 = $mysqli->prepare("UPDATE users SET balance = balance + ? WHERE phone = ? OR email = ?");
                $stmt2->bind_param('dss', $amount, $username, $username);
                $stmt2->execute();
                if($stmt2->affected_rows != 1) throw new Exception('Failed to credit beneficiary.');
            }
        }

       
        $newSender = fetchRow("SELECT balance, phone FROM users WHERE phone='$senderIdentifier' OR email='$senderIdentifier'");
        $newBen    = fetchRow("SELECT balance, phone FROM users WHERE phone='$username' OR email='$username'");

        if($txn_type == 'debit'){
    $p1 = 'Debit from '.$newBen['phone'].' ('.$purpose.')';
    ahkQuery("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) 
              VALUES ('".$newBen['phone']."','$amount','".$newBen['balance']."','$p1','1','debit')");

    $p2 = 'Received from '.$newBen['phone'].' ('.$purpose.')';
    ahkQuery("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) 
              VALUES ('".$newSender['phone']."','$amount','".$newSender['balance']."','$p2','1','credit')");

        } else {
            if($senderRole == 'admin'){
                $p2 = 'Admin Credit ('.$purpose.')';
                ahkQuery("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) VALUES ('".$newBen['phone']."','$amount','".$newBen['balance']."','$p2','1','credit')");
            } else {
                $p1 = 'Transfer to '.$newBen['phone'].' ('.$purpose.')';
                ahkQuery("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) VALUES ('".$newSender['phone']."','$amount','".$newSender['balance']."','$p1','1','debit')");
                $p2 = 'Credit by '.$newSender['phone'].' ('.$purpose.')';
                ahkQuery("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) VALUES ('".$newBen['phone']."','$amount','".$newBen['balance']."','$p2','1','credit')");
            }
        }

        $mysqli->commit();
        $success = true;
        return ['success'=>true,'message'=>'Transaction Completed!'];

    } catch(Exception $e){
        $mysqli->rollback();
        return ['success'=>false,'message'=>'Transaction failed: '.$e->getMessage()];
    }
}


function check_user_session($conn, $redirect_url = "../../includes/logout.php") {
    if(!isset($_SESSION['is_login']) || $_SESSION['is_login'] !== true){
        echo '<script>
alert("Access Denied. Please login again.");
window.location.href = "'.$redirect_url.'";
</script>';
        exit;
    }

    $user_id = $_SESSION['user_id'] ?? 0;
    $login_token = $_SESSION['login_token'] ?? '';

    $stmt = $conn->prepare("SELECT login_token FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->bind_result($db_token);
    $stmt->fetch();
    $stmt->close();

    if($db_token !== $login_token){
        session_unset();
        session_destroy();
        echo '<script>
alert("Session Expired. Please login again.");
window.location.href = "'.$redirect_url.'";
</script>';
        exit;
    }
}


function renderServices(array $services, array $udata) {
    foreach ($services as $srv) {
        if (!isset($srv['db']) || !isset($udata[$srv['db']]) || $udata[$srv['db']] !== 'on') {
            continue;
        }

        echo '<div class="col-lg-3 col-md-4 col-sm-6 mb-4">';
        echo '<div class="card h-100 text-center shadow-sm border-0 service-box">';
        echo '<div class="p-3">';
        echo '<img src="https://' . $_SERVER['SERVER_NAME'] . '/template/tngweb/assets/images/' . $srv['img'] . '" 
                  alt="' . $srv['text'] . '" class="img-fluid service-img">';
        echo '</div>';
        echo '<div class="card-body">';
        echo '<h6 class="card-title">' . $srv['text'] . '</h6>';
        echo '<span class="badge bg-success mb-2">LIVE</span>';
        echo '<div class="d-flex justify-content-center gap-2">';
        if (isset($srv['link'])) {
            echo '<a href="' . $srv['link'] . '" class="btn btn-sm btn-primary">New Apply/Correction</a>';
        }
        if (isset($srv['list_link'])) {
            echo '<a href="' . $srv['list_link'] . '" class="btn btn-sm btn-outline-secondary">History View</a>';
        }
        echo '</div>'; 
        echo '</div>';
        echo '</div>'; 
        echo '</div>'; 
    }
}

function sendregisterOtpEmail($to, $name, $otp, $domain) {
    $subject = "Your OTP for Register";

    $body = "
    <html>
    <head>
        <style>
            body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f6f8; color: #333; margin:0; padding:0; }
            .container { max-width: 600px; margin: 40px auto; background: #ffffff; padding: 30px 40px; border-radius: 12px; box-shadow: 0 4px 16px rgba(0,0,0,0.1); }
            .header { font-size: 26px; font-weight: 700; color: #2b7a78; text-align: center; margin-bottom: 20px; }
            .content { font-size: 16px; color: #555; line-height: 1.6; }
            .otp { font-size: 36px; font-weight: bold; color: #d9534f; text-align: center; margin: 20px 0; letter-spacing: 2px; }
            .footer { font-size: 13px; color: #999; text-align: center; margin-top: 30px; }
            .note { font-size: 14px; color: #666; margin-top: 15px; text-align: center; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>".XyZ_val('brand')."</div>
            <div class='content'>
                Hello <b>$name</b>,<br><br>
                Your One-Time Password (OTP) for registration is:
            </div>
            <div class='otp'>$otp</div>
            <div class='note'>
                This OTP is valid for 5 minutes only.<br>
                If you did not request this OTP, please ignore this email.
            </div>
            <div class='footer'>&copy; ".date('Y')." ".XyZ_val('baseurl').". All rights reserved.</div>
        </div>
    </body>
    </html>
    ";

    SendMail($to, $subject, $body);
}



function sendOtpEmail($to, $name, $otp, $domain) {
    $subject = "Your OTP for Login";

    $body = "
    <html>
    <head>
        <style>
            body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f6f8; color: #333; margin:0; padding:0; }
            .container { max-width: 600px; margin: 40px auto; background: #ffffff; padding: 30px 40px; border-radius: 12px; box-shadow: 0 4px 16px rgba(0,0,0,0.1); }
            .header { font-size: 26px; font-weight: 700; color: #2b7a78; text-align: center; margin-bottom: 20px; }
            .content { font-size: 16px; color: #555; line-height: 1.6; }
            .otp { font-size: 36px; font-weight: bold; color: #d9534f; text-align: center; margin: 20px 0; letter-spacing: 2px; }
            .footer { font-size: 13px; color: #999; text-align: center; margin-top: 30px; }
            .note { font-size: 14px; color: #666; margin-top: 15px; text-align: center; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>".XyZ_val('brand')."</div>
            <div class='content'>
                Hello <b>$name</b>,<br><br>
                Your One-Time Password (OTP) for login is:
            </div>
            <div class='otp'>$otp</div>
            <div class='note'>
                This OTP is valid for 5 minutes only.<br>
                If you did not request this OTP, please ignore this email.
            </div>
            <div class='footer'>&copy; ".date('Y')." ".XyZ_val('baseurl').". All rights reserved.</div>
        </div>
    </body>
    </html>
    ";

    SendMail($to, $subject, $body);
}



function sendRegistrationEmail($to, $name, $phone, $password_plain, $domain) {
    $subject = "Your Account Details - " . XyZ_val('brand');
    $body = "
    <html>
    <head>
        <style>
            body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f6f8; color: #333; margin:0; padding:0; }
            .card { max-width:600px; margin:40px auto; background:#ffffff; border-radius:12px; padding:30px 40px; box-shadow:0 4px 16px rgba(0,0,0,0.1); text-align:center; }
            .header { font-size:26px; font-weight:700; color:#2b7a78; margin-bottom:20px; }
            .info { font-size:16px; color:#555; line-height:1.6; text-align:left; margin-bottom:15px; }
            .cred { background:#f7f7f7; border-radius:6px; padding:15px; margin:12px 0; font-family:monospace; text-align:left; font-size:15px; }
            .btn { display:inline-block; padding:12px 20px; background:#2b7a78; color:#fff; text-decoration:none; border-radius:6px; margin-top:20px; font-weight:600; }
            .note { color:#666; font-size:14px; margin-top:15px; text-align:left; }
            .footer { margin-top:30px; color:#999; font-size:13px; text-align:center; }
        </style>
    </head>
    <body>
        <div class='card'>
            <div class='header'>Welcome to " . XyZ_val('brand') . "!</div>
            <div class='info'>
                Hi <strong>{$name}</strong>,<br/><br/>
                Your account has been created successfully. Below are your login details:
            </div>
            <div class='cred'>
                ID / Phone: <strong>{$phone}</strong><br/>
                Password: <strong>{$password_plain}</strong>
            </div>
            <a class='btn' href='{$domain}/login.php'>Login Now</a>
            <div class='note'>
                For security, we recommend changing your password after first login. If you did not create this account, contact our support immediately.
            </div>
            <div class='footer'>&copy; " . date('Y') . " " . XyZ_val('baseurl') . "</div>
        </div>
    </body>
    </html>
    ";

    SendMail($to, $subject, $body);
}



function generatePasswordResetEmail($userName, $newPassword, $brandName, $serverUrl) {
    $BODY = "
    <html>
    <head>
        <style>
            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                background-color: #f4f6f8;
                margin: 0;
                padding: 0;
            }
            .container {
                max-width: 600px;
                margin: 40px auto;
                background: #ffffff;
                border-radius: 12px;
                overflow: hidden;
                box-shadow: 0 4px 16px rgba(0,0,0,0.1);
                text-align: center;
            }
            .header {
                background-color: #2b7a78;
                color: white;
                padding: 30px 20px;
            }
            .header h2 {
                margin: 0;
                font-size: 26px;
                font-weight: 700;
            }
            .content {
                padding: 30px 20px;
                color: #333333;
            }
            .content p {
                font-size: 16px;
                margin: 15px 0;
            }
            .password {
                font-size: 20px;
                font-weight: bold;
                color: #d9534f;
            }
            .btn {
                display: inline-block;
                background-color: #2b7a78;
                color: white;
                padding: 12px 24px;
                border-radius: 6px;
                text-decoration: none;
                font-weight: 600;
                margin-top: 15px;
            }
            .footer {
                text-align: center;
                background-color: #f0f0f0;
                color: #555;
                padding: 15px;
                font-size: 13px;
            }
            .footer a {
                color: #2b7a78;
                text-decoration: none;
                font-weight: bold;
            }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h2>" . XyZ_val('brand') . "</h2>
                <p>Hello <strong>{$userName}</strong>, your password has been reset!</p>
            </div>
            <div class='content'>
                <p>Your new password is:</p>
                <p class='password'>{$newPassword}</p>
                <p>Use it to log in to your account now.</p>
                <a href='https://{$serverUrl}' class='btn'>Login Now</a>
            </div>
            <div class='footer'>
                &copy; ".date('Y')." " . XyZ_val('baseurl') . ". All rights reserved.
            </div>
        </div>
    </body>
    </html>
    ";

    return $BODY;
}


function renderRechargeServices(array $services, array $udata) {
    foreach ($services as $srv) {
        if (!isset($srv['db']) || !isset($udata[$srv['db']]) || $udata[$srv['db']] !== 'on') {
            continue;
        }

        echo '<div class="col-lg-3 col-md-4 col-sm-6 mb-4">';
        echo '<div class="card h-100 text-center shadow-sm border-0 service-box">';
        echo '<div class="p-3">';
        echo '<img src="https://' . $_SERVER['SERVER_NAME'] . '/template/tngweb/assets/images/' . $srv['img'] . '" 
                  alt="' . $srv['text'] . '" class="img-fluid service-img">';
        echo '</div>';
        echo '<div class="card-body">';
        echo '<h6 class="card-title">' . $srv['text'] . '</h6>';
        echo '<span class="badge bg-success mb-2">LIVE</span>';
        echo '<div class="d-flex justify-content-center gap-2">';
        if (isset($srv['link'])) {
            echo '<a href="' . $srv['link'] . '" class="btn btn-sm btn-primary">Recharge</a>';
        }
        if (isset($srv['list_link'])) {
            echo '<a href="' . $srv['list_link'] . '" class="btn btn-sm btn-outline-secondary">History View</a>';
        }
        echo '</div>'; // d-flex
        echo '</div>'; // card-body
        echo '</div>'; // card
        echo '</div>'; // col
    }
}


function getAllowedServices(array $services, array $userData): array {
    return array_filter($services, function($srv) use ($userData) {
        return isset($srv['db'], $userData[$srv['db']]) && $userData[$srv['db']] === 'on';
    });
}


function renderServiceCards(array $services) {
    $server = $_SERVER['SERVER_NAME'];
    foreach($services as $srv):
        $gridLink = $srv['link'];
        $listLink = $srv['list_link'] ?? null;
        ?>
        <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
            <div class="card h-100 text-center shadow-sm border-0 service-box">
                <div class="p-3">
                    <img src="https://<?= $server; ?>/template/tngweb/assets/images/<?= $srv['img']?>" 
                         alt="<?= $srv['text']?>" class="img-fluid service-img">
                </div>
                <div class="card-body">
                    <h6 class="card-title"><?= $srv['text']?></h6>
                    <span class="badge bg-success mb-2">LIVE</span>
                    <div class="d-flex justify-content-center gap-2">
                        <a href="<?= $gridLink?>" class="btn btn-sm btn-primary">Apply</a>
                        <?php if($listLink){ ?>
                            <a href="<?= $listLink?>" class="btn btn-sm btn-outline-secondary">List View</a>
                        <?php } ?>
                    </div>
                </div>
            </div>
        </div>
    <?php
    endforeach;
}




function getTicketStatus($ticket_number) {
    global $tng_conn;

    $ticket_number = mysqli_real_escape_string($tng_conn, $ticket_number);

    $query = "SELECT cq.*, cr.reply_message, cr.replied_at, cr.replied_by 
              FROM contact_queries cq 
              LEFT JOIN contact_replies cr ON cq.id = cr.contact_id 
              WHERE cq.ticket_number = '$ticket_number' 
              ORDER BY cr.replied_at DESC 
              LIMIT 1";

    $result = mysqli_query($tng_conn, $query);
    if($result && mysqli_num_rows($result) > 0) {
        return mysqli_fetch_assoc($result);
    }

    return null; // ticket not found
}


function submitContactQuery($name, $email, $mobile, $message) {
    global $tng_conn;

    // Escape values
    $name = mysqli_real_escape_string($tng_conn, $name);
    $email = mysqli_real_escape_string($tng_conn, $email);
    $mobile = mysqli_real_escape_string($tng_conn, $mobile);
    $message = mysqli_real_escape_string($tng_conn, $message);

    // Generate unique ticket number
    $ticket_number = 'TKT' . date('YmdHis') . rand(100, 999);

    // Insert into database
    $query = "INSERT INTO contact_queries (ticket_number, name, email, mobile, message, created_at, status) 
              VALUES ('$ticket_number', '$name', '$email', '$mobile', '$message', NOW(), 'open')";

    if(mysqli_query($tng_conn, $query)) {

        // Prepare email
        $user_email_subject = "Contact Request Received - Ticket: " . $ticket_number;
        $user_email_message = "
            <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; }
                    .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                    .header { background: #4361ee; color: white; padding: 20px; text-align: center; }
                    .content { padding: 20px; background: #f9f9f9; }
                    .ticket-box { background: white; padding: 20px; border: 2px dashed #4361ee; text-align: center; margin: 20px 0; }
                </style>
            </head>
            <body>
                <div class='container'>
                    <div class='header'>
                        <h2>Thank You for Contacting Us</h2>
                        <p>" . XyZ_val('brand') . "</p>
                    </div>
                    <div class='content'>
                        <p>Dear <strong>$name</strong>,</p>
                        <p>We have received your message and our team will get back to you within 24 hours.</p>
                        
                        <div class='ticket-box'>
                            <h3 style='color: #4361ee;'>Your Ticket Number</h3>
                            <h1 style='color: #4361ee;'>$ticket_number</h1>
                            <p>Please keep this ticket number for future reference</p>
                        </div>
                        
                        <div style='background: white; padding: 15px; margin: 20px 0;'>
                            <h4 style='color: #4361ee;'>Your Message:</h4>
                            <p style='background: #f8f9fa; padding: 15px;'>" . nl2br(htmlspecialchars($message)) . "</p>
                        </div>
                        
                        <div style='text-align: center; margin: 25px 0;'>
                            <p>You can check the status of your query anytime:</p>
                            <a href='http://" . $_SERVER['SERVER_NAME'] . "/check_status.php?ticket=$ticket_number' 
                               style='background: #4361ee; color: white; padding: 12px 25px; text-decoration: none; border-radius: 5px; display: inline-block;'>
                                Check Status Online
                            </a>
                        </div>
                    </div>
                </div>
            </body>
            </html>
        ";

        // Send email
        SendMail($email, $user_email_subject, $user_email_message);

        return ['success'=>true, 'ticket_number'=>$ticket_number, 'error'=>''];
    } else {
        return ['success'=>false, 'ticket_number'=>'', 'error'=>mysqli_error($tng_conn)];
    }
}


 
function callAadharOrgApi($bio, $aadhar) {

    $tng_apikey = JkL_get('TheNextGenAPI', 'tng_apikey');
    $tng_apiurl = "https://" . JkL_get('TheNextGenAPI', 'tng_apiurl');

    $tng_url = $tng_apiurl . "/aadhar_org_verification";

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $tng_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => [
            'bioenc' => $bio,
            'aadhar' => $aadhar,
            'apikey' => $tng_apikey
        ],
        // ❌ CURLOPT_TIMEOUT removed
        // ❌ CURLOPT_CONNECTTIMEOUT removed
    ]);

    $response = curl_exec($curl);
    curl_close($curl);

    return json_decode($response, true) ?? [];
}


function downloadAadharOrgPdf($token, $type) {

    $tng_apikey = JkL_get('TheNextGenAPI', 'tng_apikey');
    $tng_apiurl = "https://" . JkL_get('TheNextGenAPI', 'tng_apiurl');

    $url = "$tng_apiurl/aadhar_org_pdf_downoad?token=$token&type=$type&apikey=$tng_apikey";

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
    ]);

    $resp = curl_exec($curl);
    curl_close($curl);

    return json_decode($resp, true) ?? [];
}

function fetchAadharCaptcha() {
    $tng_apiurl = "https://" . JkL_get('TheNextGenAPI','tng_apiurl');
    $url = "$tng_apiurl/v1/aadhaar/captcha.php";

    $curl = curl_init($url);
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true
    ]);

    $response = curl_exec($curl);
    curl_close($curl);

    return json_decode($response, true) ?? [];
}

function fetchvotercaptcha() {
    $tng_apiurl = "https://" . JkL_get('TheNextGenAPI','tng_apiurl');
    $url = "$tng_apiurl/v1/voter/captcha.php";

    $curl = curl_init($url);
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true
    ]);

    $response = curl_exec($curl);
    curl_close($curl);

    return json_decode($response, true) ?? [];
}

// ==================== NEOAPI FUNCTIONS (using JkL_get) ====================
function sendAadharOtp($aadhar, $captcha, $captchaSID) {
    $tng_apiurl = "https://" . JkL_get('TheNextGenAPI','tng_apiurl');  // expects "core.neoapi.io"
    $tng_apikey = JkL_get('TheNextGenAPI','tng_apikey');

    // NeoAPI send endpoint
    $url = $tng_apiurl . "/v1/aadhaar/otp/pdf/send.php?apikey={$tng_apikey}&aadhar={$aadhar}&captcha={$captcha}&captchaSID={$captchaSID}";

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // optional
    $response = curl_exec($curl);
    curl_close($curl);

    return json_decode($response, true) ?? [];
}

function verifyAadharOtpPdf($aadhar, $otp, $otpTxnId, $type = 'true') {
    $tng_apiurl = "https://" . JkL_get('TheNextGenAPI','tng_apiurl');
    $tng_apikey = JkL_get('TheNextGenAPI','tng_apikey');

    $typeParam = ($type === 'true') ? 'true' : 'false';

    // NeoAPI verify endpoint
    $url = $tng_apiurl . "/v1/aadhaar/otp/pdf/verify.php?apikey={$tng_apikey}&aadhar={$aadhar}&otp={$otp}&type={$typeParam}&otpTxnId={$otpTxnId}";

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($curl);
    curl_close($curl);

    return json_decode($response, true) ?? [];
}

function downloadAadharPvcPdf($file, $type, $phone, $password) {
    $tng_apiurl = "https://" . JkL_get('TheNextGenAPI','tng_apiurl');
    $tng_apikey = JkL_get('TheNextGenAPI','tng_apikey');

    $url = "$tng_apiurl/v1/aadhaar/pvc/pdf.php?file=$file&type=$type&phone=$phone&password=$password&apikey=$tng_apikey";

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
    ]);

    $response = curl_exec($curl);
    curl_close($curl);

    return json_decode($response, true) ?? [];
}

function curl_get($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $resp = curl_exec($ch);
    $err  = curl_error($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);
    return ['http_code' => $code, 'response' => $resp, 'error' => $err];
}

function http_get($url, $header = array(), $ssl = false) {
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_FOLLOWLOCATION => true
    ]);

    if ($ssl === true) {
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    }

    $response = curl_exec($curl);

    if (curl_errno($curl)) {
        $error_msg = curl_error($curl);
        curl_close($curl);
        return "cURL Error: " . $error_msg;
    }

    curl_close($curl);
    return $response;
}



function baseurl(){
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' 
                 || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";

    $host = str_replace("www.","", $_SERVER['SERVER_NAME']);
    return $protocol . $host;
}

function downloadVoterPDF($voterautoid, $type) {
    global $tng_conn;

    $voterautoid = intval($voterautoid);
    if ($voterautoid <= 0) die("Invalid voterautoid");
    if (!$type) die("Missing type");

    // Fetch voter data
    $sql = "SELECT * FROM `voterauto1` WHERE voterautoid = '$voterautoid' LIMIT 1";
    $result = mysqli_query($tng_conn, $sql);
    if (!$result || mysqli_num_rows($result) == 0) die("No record found");

    $data = mysqli_fetch_assoc($result);
    $postData = [
        "data_base64" => base64_encode(json_encode($data, JSON_UNESCAPED_UNICODE)),
        "type" => $type
    ];

    // Send to external API
    $apiUrl = "https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/request-data/voter-request";
    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    $response = curl_exec($ch);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($curlError) die("Curl error: " . $curlError);

    // Decode API response
    $responseData = json_decode($response, true);
    if (!$responseData || !isset($responseData['pdf'])) die("Invalid API response or PDF missing");

    echo $response;
    exit;
}






//pan_mask_verification_api_run
function pan_mask_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'aadhar' => $request['aadhar'],
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/aadhaar/pan/status.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//aadhar_to_pan_mask_verification_api_run
function aadhar_to_pan_mask_verification_api_run($request){
    $getData = http_build_query([
        'aadhar' => $request['aadhar'],
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/aadhaar/pan/mask.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//uid_to_ration_details_verification_api_run
function uid_to_ration_details_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'uid' => $request['uid'],
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/aadhaar/ration/detail.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//uid_ration_pdf_verification_v1_api_run
function uid_ration_pdf_verification_v1_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'uid' => $request['uid'],
        'rationtype' => $request['rationtype'],
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/aadhaar/ration/pdf.php?$getData");

    return json_decode($resJson, true) ?? [];
}


function checkRegisterStatus() {
    $status = XyZ_val('register_status');
    if ($status !== 'active') {
        header("Location: index.php"); 
        exit;
    }
}


//aadhar_validation
function aadhar_validation_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'aadhar' => $request['aadhar'],
        'captcha' => $request['captcha'],
        'captchaSID' => $request['captchaSID'],
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/aadhaar/validate.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//aadhar_validation_v2_api_run
function aadhar_validation_v2_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'aadhar' => $request['aadhar'],
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v2/aadhaar/validate.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//agri_farmer_card_pdf_verification
function agri_farmer_card_pdf_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'aadhar' => $request['aadhar'],
        'language' => $request['language'],
        'state' => $request['state'],
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/agri/pdf.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//agri_farmer_card_pdf_verification
function agri_farmer_card_pdf_verification_api_v2_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'aadhar' => $request['aadhar'],
        'language' => $request['language'],
        'state' => $request['state'],
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v3/agri/pdf.php?$getData");

    return json_decode($resJson, true) ?? [];
}
//agri_farmer_card_pdf_new_verification_api_run
function agri_farmer_card_pdf_new_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'aadhar' => $request['aadhar'],
        'language' => $request['language'],
        'state' => $request['state'],
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v2/agri/pdf.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//agri_farmer_card_pdf_new_verification_api_run
function agri_farmer_card_status_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'aadhar' => $request['aadhar'],
        'state' => $request['state'],
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/agri/status.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//agri_farmer_card_details_verification_api_run
function agri_farmer_card_details_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'aadhar' => $request['aadhar'],
        'state' => $request['state'],
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/agri/detail.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//aadhar_npci_bank_verification_run
function aadhar_npci_bank_verification_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'aadhar' => $request['aadhar'],
        'state' => $request['state'],
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/aadhaar/npci.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//mobile_to_vehicle_find_verification_api_run
function mobile_to_vehicle_find_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'mobileNumber' => $request['mobileNumber'],
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/mobile/vehicle.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//mobile_to_vehicle_find_verification_api_run
function vehicle_to_owner_history_verification_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'rcno' => $request['rcno'],
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/vehicle/history.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//aadhaar_pdf_download_run
function aadhaar_pdf_download_run($request){
$getData = http_build_query([
    'apikey' => JkL_get('TheNextGenAPI','tng_apikey'),
    'aadhar' => $request['aadhar'] ?? '',
    'lang'   => $request['lang'] ?? 'en',
    'type'   => $request['type'] ?? 'regular'
]);

$resJson = http_get(
    "https://" . JkL_get('TheNextGenAPI','tng_apiurl') . "/v1/aadhaar/pdf.php?$getData"
);

return json_decode($resJson, true) ?? [];

}
//rtps_pdf_verification
function rtps_pdf_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'appRefNum' => urlencode($request['appRefNum']),
        'name' => urlencode($request['name']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/rtps/bihar/pdf.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//chassis-to-rc-verification
function chassis_to_rc_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'chassisNumber' => urlencode($request['chassisNumber']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/chassis-to-rc/v1/chassis-to-rc-verification?$getData");

    return json_decode($resJson, true) ?? [];
}

//reacharge-api-status-check
function reacharge_api_status_check_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'agentid' => urlencode($request['agentid']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/RechargeWebService/v1/reacharge-api-status-check?$getData");

    return json_decode($resJson, true) ?? [];
}

//dbtAgriculture_br_pdf_verification
function dbtAgriculture_br_pdf_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'inputNumber' => urlencode($request['inputNumber']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/dbtAgriculture_br_pdf_verification?$getData");

    return json_decode($resJson, true) ?? [];
}

//dl_find_verification
function dl_find_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'name' => urlencode($request['name']),
        'dob' => urlencode($request['dob']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/dl_find_verification?$getData");

    return json_decode($resJson, true) ?? [];
}

//dl_pdf_verification_v1
function dl_pdf_verification_v1_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'dl_number' => urlencode($request['dl_number']),
        'dob' => urlencode($request['dob']),
        'dltype' => urlencode($request['dltype']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/dl/pdf/secure.php?$getData");

    return json_decode($resJson, true) ?? [];
}

function dl_pdf_only_number_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'dl_number' => urlencode($request['dl_number']),
        'dltype' => urlencode($request['dltype']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/dl/pdf.php?$getData");

    return json_decode($resJson, true) ?? [];
}

function aadhar_to_detail_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'aadhar' => $request['aadhar']
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/aadhaar/detail.php?$getData");

    return json_decode($resJson, true) ?? [];
} 

//dth_reacharge_api_verification_api_run
function dth_reacharge_api_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'mobile' => urlencode($request['mobile']),
        'operator' => urlencode($request['operator']),
        'amount' => urlencode($request['amount']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/RechargeWebService/v1/reacharge-api?$getData");

    return json_decode($resJson, true) ?? [];
}

//mobile_reacharge_api_verification_api_run
function mobile_reacharge_api_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'mobile' => urlencode($request['mobile']),
        'operator' => urlencode($request['operator']),
        'amount' => urlencode($request['amount']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/RechargeWebService/v1/reacharge-api?$getData");

    return json_decode($resJson, true) ?? [];
}


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

//electricBillPDF_Br_verification
function electricBillPDF_Br_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'caNumber' => urlencode($request['caNumber']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/electricity/bihar/pdf.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//engine-to-rc-verification
function engine_to_rc_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'engineNumber' => urlencode($request['engineNumber']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/engine-to-rc/v1/engine-to-rc-verification?$getData");

    return json_decode($resJson, true) ?? [];
}

//enrollment_status_verification
function enrollment_status_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'eid' => urlencode($request['eid']),
        'captcha' => urlencode($request['captcha']),
        'captchaSID' => urlencode($request['captchaSID']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/aadhaar/status.php?$getData");

    return json_decode($resJson, true) ?? [];
}


function familyId_card_pdf_up_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'family_id' => urlencode($request['family_id']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/family/up/pdf.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//gst_to_pan_verification
function gst_to_pan_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'gstin' => urlencode($request['gstin']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/gst/pan.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//gst_to_pan_with_details_verification
function gst_to_pan_with_details_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'gstin' => urlencode($request['gstin']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/gst/detail.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//gstin-to-contact-verification
function gst_to_contact_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'gstin' => urlencode($request['gstin']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/gst/contact.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//ifscCode_to_Bank_verification               
function ifscCode_to_Bank_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'IfscCode' => urlencode($request['IfscCode']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/ifsc/detail.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//janaadharFind_rj_verification
function janaadharFind_rj_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'aadhar' => urlencode($request['aadhar']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/janaadharFind_rj_verification?$getData");

    return json_decode($resJson, true) ?? [];
}

//janaadharpdf_rj_verification
function janaadharpdf_rj_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'janaadhar' => urlencode($request['janaadhar']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/janaadharpdf_rj_verification?$getData");

    return json_decode($resJson, true) ?? [];
}

//mobile_number_look_up_verification
function mobile_number_look_up_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'mobileNumber' => urlencode($request['mobileNumber']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/mobile/lookup.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//mobile_number_to_lpg_verification_api_run
function mobile_number_to_lpg_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'mobileNumber' => urlencode($request['mobileNumber']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/mobile/lpg.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//mobile_number_to_msme_udyam_verification_api_run
function mobile_number_to_msme_udyam_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'mobileNumber' => urlencode($request['mobileNumber']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/mobile/msme-udyam.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//mobile_number_to_pan_verification_api_run
function mobile_number_to_pan_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'mobileNumber' => urlencode($request['mobileNumber']),
        'name' => urlencode($request['name']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/mobile/name_mobile_to_pan.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//msme_udyam_to_pdf_verification_api_run
function msme_udyam_to_pdf_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'udyam_number' => urlencode($request['udyam_number']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/msme-udyam-api/v1/msme-udyam-to-premium-details-verification?$getData");

    return json_decode($resJson, true) ?? [];
}

//nsdl_incomplete_verification_api_run
function nsdl_incomplete_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'order_id' => urlencode($request['order_id']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/nsdl-api/v1/nsdl_incomplete?$getData");

    return json_decode($resJson, true) ?? [];
}

//nsdl_new_pan_apply_verification
function nsdl_new_pan_apply_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'p_order_id' => urlencode($request['p_order_id']),
        'name' => urlencode($request['name']),
        'gender' => urlencode($request['gender']),
        'mobile' => urlencode($request['mobile']),
        'email' => urlencode($request['email']),
        'application_mode' => urlencode($request['application_mode']),
        'application_type' => urlencode($request['application_type']),
        'branch_code' => urlencode($request['branch_code']),
        'redirect_url' => urlencode($request['redirect_url']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/nsdl-api/v1/nsdl_new_pan_apply_verification?$getData");

    return json_decode($resJson, true) ?? [];
}

//nsdl_encrypted_status
function nsdl_encrypted_status_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'encrypted_data' => urlencode($request['encrypted_data']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/nsdl-api/v1/nsdl_encrypted_status?$getData");

    return json_decode($resJson, true) ?? [];
}

//Pan2Uid_Apply
function Pan2Uid_Apply_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'pan' => urlencode($request['pan']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/v2/Pan2Uid/Pan2Uid_Apply?$getData");

    return json_decode($resJson, true) ?? [];
}

//Pan2Uid_CheckStatus_verification_api_run
function Pan2Uid_CheckStatus_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'pan' => urlencode($request['pan']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/v2/Pan2Uid/CheckStatus?$getData");

    return json_decode($resJson, true) ?? [];
}

//pan_verification
function pan_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'pan' => urlencode($request['pan']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/pan/detail.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//pan_verification_premium_api_run
function pan_verification_premium_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'pan' => urlencode($request['pan']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/pan/detail/premium.php?$getData");

    return json_decode($resJson, true) ?? [];
}


//pan_find_verification
function pan_find_verificationapi_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'),
        'aadhar' => urlencode($request['aadhar']),
        'type'   => 'server_1'
    ]);

    $resJson = http_get(
        "https://" . JkL_get('TheNextGenAPI','tng_apiurl') . "/v1/aadhaar/pan.php?$getData"
    );

    return json_decode($resJson, true) ?? [];
}

//pan_find_verification
function pan_find_verificationapi_v2_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'),
        'aadhar' => urlencode($request['aadhar']),
        'type'   => 'server_2'
    ]);

    $resJson = http_get(
        "https://" . JkL_get('TheNextGenAPI','tng_apiurl') . "/v1/aadhaar/pan.php?$getData"
    );

    return json_decode($resJson, true) ?? [];
}

//pan_find_apply_verificationapi_run
function pan_find_apply_verificationapi_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'aadhar' => urlencode($request['aadhar']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/aadhaar/pan_apply.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//pan_find_verification
function pan_find_apply_status_verificationapi_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'aadhar' => urlencode($request['aadhar']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/aadhaar/pan_status.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//pan_to_aadhar_verification
function pan_to_aadhar_verification_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'pan' => urlencode($request['pan']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/pan/aadhaar.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//pan_to_aadhar_mask_verification
function pan_to_aadhar_mask_verification_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'pan' => urlencode($request['pan']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/pan/aadhaar/mask.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//pan_to_gst_verification
function pan_to_gst_verification_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'pan' => urlencode($request['pan']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/pan/gst.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//voter_pdf_status_api
function voter_pdf_status_api($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'application_no' => urlencode($request['application_no']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/voter/pdf/manual_status.php?$getData");

    return json_decode($resJson, true) ?? [];
}


//voter_pdf_org_verification_run
function voter_pdf_org_verification_runy($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'epic_number' => urlencode($request['epic_number']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/voter/pdf/manual.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//pan_to_gst_with_details_verification
function pan_to_gst_with_details_verification_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'pan' => urlencode($request['pan']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/pan/gst/detail.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//pan_to_udyam_msme_find_verification_run
function pan_to_udyam_msme_find_verification_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'pan' => urlencode($request['pan']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/msme-udyam-api/v1/pan-to-msme-udyam-verification?$getData");

    return json_decode($resJson, true) ?? [];
}

//pincode_verification
function pincode_verification_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'pincode' => urlencode($request['pincode']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/pincode/detail.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//postoffice_verification
function postoffice_verification_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'postoffice' => urlencode($request['postoffice']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/postoffice/detail.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//ration-to-uid-all-verification
function ration_to_uid_all_verification_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'ration_no' => urlencode($request['ration_no']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/ration/aadhaar.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//ration_to_aadhar_wb_verification
function ration_to_aadhar_wb_verification_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'ration_no' => urlencode($request['ration_no']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/ration/wb/aadhaar.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//ration_to_aadhar_up_verification
function ration_to_aadhar_up_verification_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'ration_no' => urlencode($request['ration_no']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/ration/up/aadhaar.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//ration_to_aadhar_up_verification
function ration_to_aadhar_up_verification_v1_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'ration_no' => urlencode($request['ration_no']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v2/ration/up/aadhaar.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//ration_pdf_verification_v1
function ration_pdf_verification_v1_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'ration_no' => urlencode($request['ration_no']),
        'rationtype' => urlencode($request['rationtype']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/ration/pdf.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//ration_detail_verification
function ration_detail_verification_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'rcno' => urlencode($request['rcno']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/ration/detail.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//rto_verification
function rto_verification_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'rtoCode' => urlencode($request['rtoCode']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/vehicle/rto/detail.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//samgra_card_pdf_mp_verification
function samgra_card_pdf_mp_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'family_id' => urlencode($request['family_id']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/samagra/pdf.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//sambal_card_pdf_mp_verification
function sambal_card_pdf_mp_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'family_id' => urlencode($request['family_id']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/sambal/pdf.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//uid_eshram_pdf_verification
function uid_eshram_pdf_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'uid' => urlencode($request['uid']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/uid_eshram_pdf_verification?$getData");

    return json_decode($resJson, true) ?? [];
}

//vehicle_2_mobile_verification
function vehicle_2_mobile_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'rcno' => urlencode($request['rcno']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/vehicle/mobile.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//vehicle_chalan_verification
function vehicle_chalan_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'rcno' => urlencode($request['rcno']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/vehicle/chalan.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//vehicle_rcpdf_verification
function vehicle_rcpdf_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'rcno' => urlencode($request['rcno']),
        'rctype' => urlencode($request['rctype']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/vehicle/pdf.php?$getData");

    return json_decode($resJson, true) ?? [];
}



//vehicle_rcpdf_verification
function vehicle_rcpdf_verification_v2_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'rcno' => urlencode($request['rcno']),
        'rctype' => urlencode($request['rctype']),
        'fathername' => urlencode($request['fathername']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v2/vehicle/pdf.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//vehicle_rcpdf_verification_v3_api_run
function vehicle_rcpdf_verification_v3_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'rcno' => urlencode($request['rcno']),
        'rctype' => urlencode($request['rctype']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v3/vehicle/pdf.php?$getData");

    return json_decode($resJson, true) ?? [];
}

 
//Lerning-license-to-pdf-verification
function Lerning_license_to_pdf_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'applNum' => urlencode($request['applNum']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/dl/ll_pdf/pdf.php?$getData");

    return json_decode($resJson, true) ?? [];
}
//vehicle_rc_fasttag_verification_api_run
function vehicle_rc_fasttag_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'rcno' => urlencode($request['rcno']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/vehicle/fasttag/detail.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//voter_captcha_verification
function voter_captcha_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'epicno' => urlencode($request['epicno']),
        'captchaId' => urlencode($request['captchaId']),
        'captcha' => urlencode($request['captcha']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/voter/detail-captcha.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//voter_verification
function voter_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'epicno' => urlencode($request['epicno']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/voter/detail.php?$getData");

    return json_decode($resJson, true) ?? [];
}

// ==================== API FUNCTIONS (exactly your pattern) ====================
// 1. Send Voter OTP
function voter_link_otp_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'mob_number' => urlencode($request['mob_number']),
    ]);
    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/voter/mobile-link/otp/send.php?$getData");
    return json_decode($resJson, true) ?? [];
}

// 2. Verify Voter OTP (returns Token A)
function voter_mob_link_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'mob_number' => urlencode($request['mob_number']),
        'otp' => urlencode($request['otp']),
    ]);
    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/voter/mobile-link/otp/verify.php?$getData");
    return json_decode($resJson, true) ?? [];
}

// 3. Send Aadhaar eSign OTP (using Token A)
function aadhar_esign_otp_send_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'),
        'aadhar' => $request['aadhar'],
        'aadhar_name' => urlencode($request['aadhar_name']),
        'token' => $request['token']
    ]);
    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/voter/mobile-link/otp/send_aadhar.php?$getData");
    return json_decode($resJson, true) ?? [];
}

// 4. Verify Aadhaar OTP (using Token B)
function aadhar_esign_otp_verify_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'),
        'otp' => $request['otp'],
        'token' => $request['token']
    ]);
    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/voter/mobile-link/otp/verify_aadhar.php?$getData");
    return json_decode($resJson, true) ?? [];
}

// ==================== API FUNCTIONS (using JkL_get) ====================
function voter_mob_link_without_otp_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'mob_number' => urlencode($request['mob_number']),
        'epic_number' => urlencode($request['epic_number']),
    ]);
    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/voter/mobile-link/no-otp/verify.php?$getData");
    return json_decode($resJson, true) ?? [];
}

function aadhar_esign_otp_send_without_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'),
        'aadhar' => $request['aadhar'],
        'aadhar_name' => urlencode($request['aadhar_name']),
        'token' => $request['token']
    ]);
    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/voter/mobile-link/no-otp/send_aadhar.php?$getData");
    return json_decode($resJson, true) ?? [];
}

function aadhar_esign_otp_verify_without_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'),
        'otp' => $request['otp'],
        'token' => $request['token']
    ]);
    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/voter/mobile-link/no-otp/verify_aadhar.php?$getData");
    return json_decode($resJson, true) ?? [];
}



// Voter Mobile Link Manual – Submit (No OTP)
function voter_mobile_link_manual_submit_api_run($epic_number, $mob_number) {
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'),
        'epic_number' => urlencode($epic_number),
        'mob_number' => urlencode($mob_number),
    ]);
    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/voter/mobile-link/no-otp/manual.php?$getData");
    return json_decode($resJson, true) ?? [];
}

// Voter Mobile Link Manual – Check Status
function voter_mobile_link_manual_status_api_run($application_no) {
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'),
        'application_no' => urlencode($application_no),
    ]);
    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/voter/mobile-link/no-otp/manual_status.php?$getData");
    return json_decode($resJson, true) ?? [];
}


//voter_otp_verification
function voter_otp_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'epic_number' => urlencode($request['epic_number']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/voter/pdf/otp/send.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//voter_pdf_verification
function voter_pdf_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'epic_number' => urlencode($request['epic_number']),
        'otp' => urlencode($request['otp']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/voter/pdf/otp/verify.php?$getData");

    return json_decode($resJson, true) ?? [];
}

//balance_info
function balance_info_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/balance_info?$getData");

    return json_decode($resJson, true) ?? [];
}


function qr_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('paymentapi','gateway_apikey'), 
        'amount' => urlencode($request['amount']),
    ]);

    $resJson = http_get("https://".JkL_get('paymentapi','gateway_Url')."/qr_verification?$getData");

    return json_decode($resJson, true) ?? [];
}


//upi-to-bank-detail-verification
function upi_to_bank_details_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'upi_id' => urlencode($request['upi_id']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/bank-service/v1/upi-to-bank-detail-verification?$getData");

    return json_decode($resJson, true) ?? [];
}


//mobile-to-detail-verification
function mobile_to_details_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'mobileNumber' => urlencode($request['mobileNumber']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/mobile/detail.php?$getData");

    return json_decode($resJson, true) ?? [];
}



//ayushman_verification_api_run
function ayushman_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'aadhar' => urlencode($request['aadhar']),
        'stateCode' => urlencode($request['stateCode']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/ayushman/png.php?$getData");

    return json_decode($resJson, true) ?? [];
}



//dl_to_mobile_find_verification_api_run
function dl_to_mobile_find_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'dlno' => urlencode($request['dlno']),
        'dob' => urlencode($request['dob']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/v1/dl/mobile/secure.php?$getData");

    return json_decode($resJson, true) ?? [];
}


//ekyc_otp_verification_send_api_run
function ekyc_otp_verification_send_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'mobileNumber' => urlencode($request['mobileNumber']),
        'type' => "send",
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/uid-bioenc/v1/ekyc-otp-verification?$getData");

    return json_decode($resJson, true) ?? [];
}


//ekyc_otp_verification_verify_api_run
function ekyc_otp_verification_verify_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'mobileNumber' => urlencode($request['mobileNumber']),
        'otp' => urlencode($request['otp']),
        'type' => "verify",
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/uid-bioenc/v1/ekyc-otp-verification?$getData");

    return json_decode($resJson, true) ?? [];
}


//nsdl_pan_txn_status_verification
function nsdl_pan_txn_status_verification_api_run($request){
    $getData = http_build_query([
        'apikey' => JkL_get('TheNextGenAPI','tng_apikey'), 
        'order_id' => urlencode($request['order_id']),
    ]);

    $resJson = http_get("https://".JkL_get('TheNextGenAPI','tng_apiurl')."/api/nsdl-api/v1/nsdl_pan_txn_status_verification?$getData");

    return json_decode($resJson, true) ?? [];
}

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

//  Check Admin Here 
function checkServiceStatus($udata, $service_key) {
    $status = $udata[$service_key] ?? 'off';
    if ($status !== 'on') {
        header("Location: index.php");
        exit;
    }
}

    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;
        }
    }



}
$updateApiUrl = base64_decode(
    "aHR0cHM6Ly90aGVuZXh0Z2VuYXBpLmNsb3VkL3VwZGF0ZS91cGRhdGVfaW5mby5qc29u"
);

function sendWhatsAppMessage($phone, $message, $footer)
{
    $whatsapp_apikey = JkL_get('whatsapp_api','whatsapp_apikey');
    $whatsapp_sender = JkL_get('whatsapp_api','whatsapp_sender_no');
    $whatsapp_url    = JkL_get('whatsapp_api','whatsapp_url'); // ✅ DB URL

   
    $message = urlencode($message);
    $footer  = strtoupper($footer);
    $url = str_replace(
        ['{number}', '{message}'],
        ['91'.$phone, $message],
        $whatsapp_url
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        $response = json_encode([
            'status' => false,
            'error'  => curl_error($ch)
        ]);
    }
    curl_close($ch);

    return json_decode($response, true);
}


function getRegistrationFee($userType) {
    return ($userType == "retailer") ? XyZ_val('ret_reg_fee') 
         : (($userType == "distributor") ? XyZ_val('dist_reg_fee') 
         : 999);
}
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
$domain = $protocol . "://" . $_SERVER['HTTP_HOST'];
// -------------------- Commission Function --------------------
function addCommission($tng_conn, $userPhone, $txnAmount, $parentPhone, $serviceName) {
    if (empty($parentPhone)) {
        return; 
    }

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

    
    $parentQ = mysqli_query($tng_conn,
        "SELECT balance, distributer_commission_fee, distributer_commission_status
         FROM users
         WHERE phone = '$parentPhoneEsc'
         LIMIT 1"
    );

    if (!$parentQ) {
        error_log("Commission Error (Parent Query): " . mysqli_error($tng_conn));
        return;
    }

    $parentRow = mysqli_fetch_assoc($parentQ);
    if (!$parentRow) {
       
        return;
    }

   
    if (!isset($parentRow['distributer_commission_status']) || $parentRow['distributer_commission_status'] !== 'on') {
        return; 
    }

    
    $commissionPercent = 3.0;
    if (isset($parentRow['distributer_commission_fee']) && is_numeric($parentRow['distributer_commission_fee'])) {
        $commissionPercent = floatval($parentRow['distributer_commission_fee']);
    }

    $commissionAmount = round(($txnAmount * $commissionPercent) / 100, 2);
    if ($commissionAmount <= 0) {
        return;
    }

    
    $oldBalance = floatval($parentRow['balance'] ?? 0);

    
    $update = mysqli_query($tng_conn,
        "UPDATE users 
         SET balance = balance + $commissionAmount 
         WHERE phone = '$parentPhoneEsc'"
    );

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

    
    $newBalanceQuery = mysqli_query($tng_conn, "SELECT balance FROM users WHERE phone='$parentPhoneEsc' LIMIT 1");
    $newBalanceRow = mysqli_fetch_assoc($newBalanceQuery);
    $newBalance = floatval($newBalanceRow['balance'] ?? $oldBalance + $commissionAmount);

    
    $purpose = "Commission from $userPhone on $serviceName | Old: $oldBalance | New: $newBalance";

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

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

    return true;
}


function upgradeToDistributor($tng_conn, $userid, $currentUser) {
    
   if (!isset($currentUser) || empty($currentUser)) {
    return ['success' => false, 'msg' => 'Session expired, please login again'];
}

$userid = intval($userid); 


$checkUser = mysqli_query($tng_conn, "SELECT id FROM users WHERE id = '$userid' LIMIT 1");

if (!$checkUser || mysqli_num_rows($checkUser) == 0) {
    return ['success' => false, 'msg' => 'Invalid User'];
}

    
    $userQ = mysqli_query($tng_conn, "SELECT type, balance, phone FROM users WHERE id='$userid' LIMIT 1");
    if (!$userQ) {
        return ['success' => false, 'msg' => 'Database error: ' . mysqli_error($tng_conn)];
    }

    $userRow = mysqli_fetch_assoc($userQ);
    if (!$userRow) {
        return ['success' => false, 'msg' => 'User not found'];
    }

    if ($userRow['type'] != 'retailer') {
        return ['success' => false, 'msg' => 'Only retailers can upgrade'];
    }

    
    $upgradeFee = XyZ_val('dist_reg_fee'); 

    if ($userRow['balance'] < $upgradeFee) {
        return ['success' => false, 'msg' => "Insufficient balance. You need ₹$upgradeFee"];
    }

    $oldBalance = floatval($userRow['balance']);
    $newBalance = $oldBalance - $upgradeFee;

    
    $update = mysqli_query($tng_conn, "UPDATE users SET type='distributor', balance='$newBalance' WHERE id='$userid'");
    if (!$update) {
        return ['success' => false, 'msg' => 'Failed to upgrade: ' . mysqli_error($tng_conn)];
    }

   
    $purpose = "Upgrade to Distributor | Fee: ₹$upgradeFee | Old: $oldBalance | New: $newBalance";
    $phoneEsc = mysqli_real_escape_string($tng_conn, $userRow['phone']);

    $insert = mysqli_query($tng_conn,
        "INSERT INTO wallethistory (userid, amount, balance, purpose, status, type)
         VALUES ('$phoneEsc',
                 '" . mysqli_real_escape_string($tng_conn, $upgradeFee) . "',
                 '" . mysqli_real_escape_string($tng_conn, $newBalance) . "',
                 '" . mysqli_real_escape_string($tng_conn, $purpose) . "',
                 '1',
                 'Debit')"
    );

    if (!$insert) {
        error_log("Wallet History Error (Distributor Upgrade): " . mysqli_error($tng_conn));
    }

    return ['success' => true, 'msg' => "You are now a Distributor! Future profit will be calculated from your users."];
}


$part1 = str_pad(mt_rand(1000, 9999), 4, '0', STR_PAD_LEFT);
$part2 = str_pad(mt_rand(10000, 99999), 5, '0', STR_PAD_LEFT);
$part3 = str_pad(mt_rand(10000, 99999), 5, '0', STR_PAD_LEFT);

$enrollment = $part1.'/'.$part2.'/'.$part3;

// Query Execute
function ahkQuery($sql){
    global $tng_conn ;
    $res = mysqli_query($tng_conn,$sql);
    return $res;
}
// Count Row Number
// Count Row Number
function ahkRows($sql) {
    global $tng_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($tng_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 $tng_conn ;
    $res = mysqli_fetch_assoc(ahkQuery($sql));
    return $res;
}
// Get Website data 
function tngweb($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 $tng_conn;
    $safe = mysqli_real_escape_string($tng_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 
}


?>

