<?php
require_once("autoload.php");
require_once("config.php");

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

function api_token_gen(){ 
return implode('-', str_split(substr(strtolower(md5(microtime().rand(1000, 9999))), 0, 30), 6));
}

function awal_alert_msg($msg,$type='primary',$redirect='javascript:void(0)'){
echo '
<script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function () {
Swal.fire("'.$msg.'", "", "'.$type.'").then(function() { window.location = "'.$redirect.'"; });
});
</script>
';
}

function alert_msg($msg,$type='primary'){
echo '<div class="alert alert-'.$type.' alert-dismissible fade show"><i class="fa fa-bell fa-fw"></i> '.$msg.'</div>';
}


function alert_js($msg){
echo '<script>alert("'.$msg.'");</script>';
}

function data_table($value='#dataTable'){
echo '
<link rel="stylesheet" href="//cdn.datatables.net/1.13.1/css/dataTables.bootstrap4.min.css">
<style>
div.dataTables_wrapper div.dataTables_filter {
    padding: 1rem; 
}
div.dataTables_wrapper div.dataTables_length {
    text-align: left;
    padding: 1rem; 
}
div.dataTables_wrapper div.dataTables_paginate {
    padding-bottom: 1rem;
    padding-right: 1rem;
}
div.dataTables_wrapper div.dataTables_info {
    text-align: left;
    padding-left: 1rem;
}

.table-bordered {
  border: 1px solid #009cff !important;
}
</style>
<script src="//cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script>
<script src="//cdn.datatables.net/1.13.1/js/dataTables.bootstrap5.min.js"></script>
<script>
$(document).ready(function () {
    $("'.$value.'").DataTable();
});
</script>
';
}


function summernote($value='#summernote'){
echo '
<link href="//cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.css" rel="stylesheet">
<script src="//cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.js"></script>
<script>
$(document).ready(function () {
$( "'.$value.'" ).summernote({ placeholder: $( "'.$value.'" ).attr("placeholder"), height: 300 });
});
</script>
';
}

if (!defined('SEARCH_ID_SECRET')) {
    define(
        'SEARCH_ID_SECRET',
        'RAPIDX-AADHAAR-PRINT-2026-MY-PRIVATE-SECRET-KEY'
    );
}

if (!function_exists('searchIdBase64UrlEncode')) {
    function searchIdBase64UrlEncode($data)
    {
        return rtrim(
            strtr(base64_encode($data), '+/', '-_'),
            '='
        );
    }
}

if (!function_exists('searchIdBase64UrlDecode')) {
    function searchIdBase64UrlDecode($data)
    {
        $data = strtr((string)$data, '-_', '+/');

        $remainder = strlen($data) % 4;

        if ($remainder !== 0) {
            $data .= str_repeat('=', 4 - $remainder);
        }

        return base64_decode($data, true);
    }
}

if (!function_exists('encryptSearchId')) {
    function encryptSearchId($searchId)
    {
        $searchId = trim((string)$searchId);

        if ($searchId === '' || !ctype_digit($searchId)) {
            return false;
        }

        if (!function_exists('openssl_encrypt')) {
            return false;
        }

        $cipher = 'AES-256-CBC';
        $key = hash('sha256', SEARCH_ID_SECRET, true);
        $ivLength = openssl_cipher_iv_length($cipher);

        if ($ivLength === false || $ivLength <= 0) {
            return false;
        }

        $iv = openssl_random_pseudo_bytes($ivLength);

        if ($iv === false || strlen($iv) !== $ivLength) {
            return false;
        }

        $encrypted = openssl_encrypt(
            $searchId,
            $cipher,
            $key,
            OPENSSL_RAW_DATA,
            $iv
        );

        if ($encrypted === false) {
            return false;
        }

        $hmac = hash_hmac(
            'sha256',
            $iv . $encrypted,
            $key,
            true
        );

        return searchIdBase64UrlEncode(
            $iv . $hmac . $encrypted
        );
    }
}

if (!function_exists('decryptSearchId')) {
    function decryptSearchId($token)
    {
        $token = trim((string)$token);

        if ($token === '' || strlen($token) > 1000) {
            return false;
        }

        if (!function_exists('openssl_decrypt')) {
            return false;
        }

        $decoded = searchIdBase64UrlDecode($token);

        if ($decoded === false) {
            return false;
        }

        $cipher = 'AES-256-CBC';
        $key = hash('sha256', SEARCH_ID_SECRET, true);
        $ivLength = openssl_cipher_iv_length($cipher);
        $hmacLength = 32;

        if (
            $ivLength === false ||
            $ivLength <= 0 ||
            strlen($decoded) <= ($ivLength + $hmacLength)
        ) {
            return false;
        }

        $iv = substr($decoded, 0, $ivLength);

        $receivedHmac = substr(
            $decoded,
            $ivLength,
            $hmacLength
        );

        $encrypted = substr(
            $decoded,
            $ivLength + $hmacLength
        );

        if (
            strlen($iv) !== $ivLength ||
            strlen($receivedHmac) !== $hmacLength ||
            $encrypted === ''
        ) {
            return false;
        }

        $calculatedHmac = hash_hmac(
            'sha256',
            $iv . $encrypted,
            $key,
            true
        );

        if (!hash_equals($receivedHmac, $calculatedHmac)) {
            return false;
        }

        $decrypted = openssl_decrypt(
            $encrypted,
            $cipher,
            $key,
            OPENSSL_RAW_DATA,
            $iv
        );

        if (
            $decrypted === false ||
            $decrypted === '' ||
            !ctype_digit((string)$decrypted)
        ) {
            return false;
        }

        $searchId = (int)$decrypted;

        return $searchId > 0 ? $searchId : false;
    }
}


function auth_out($status, $message, $action = 'none', $data = array()) {
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
    header('Content-Type: application/json; charset=UTF-8');
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    echo json_encode(array(
        'status' => (bool)$status,
        'message' => (string)$message,
        'action' => (string)$action,
        'data' => is_array($data) ? $data : array()
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function auth_mobile_value($value) {
    $value = preg_replace('/\D+/', '', (string)$value);
    return preg_match('/^[0-9]{10}$/', $value) ? $value : '';
}

function auth_email_value($value) {
    $value = trim((string)$value);
    return filter_var($value, FILTER_VALIDATE_EMAIL) ? $value : '';
}


function datepicker($value='.datepicker'){
echo '
<link href="https://code.jquery.com/ui/1.12.1/themes/cupertino/jquery-ui.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" ></script>
<script>
$(document).ready(function () {
$( "'.$value.'" ).datepicker({
  dateFormat: "dd-mm-yy"
});
});
</script>
';
}


function modal($id,$type){
echo '
<script>
$(document).ready(function () {
$( "'.$id.'" ).modal("'.$type.'");
});
</script>
';
}


function select2($id){
echo '
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet" />
<style>
.select2-container--default .select2-selection--single .select2-selection__rendered {
    color: #444;
    line-height: 1.5;
    margin-top: 7.5px;
}
.select2-container .select2-selection--single {
    height: calc(1.5em + 0.75rem + 2px);
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
    height: 32px;
    position: absolute;
    top: 1px;
    right: 1px;
    width: 20px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.min.js"></script>
<script>
$(document).ready(function() {
$("'.$id.'").select2({
    display: "block",
    width: "100%",
    allowClear: false,
    height: "calc(1.5em + .75rem + 2px)",
});
});
</script>';
}


function file_name(){
return strtoupper(str_replace("_"," ",basename($_SERVER["SCRIPT_FILENAME"], '.php'))); 
}

function page_name(){
return ucwords(str_replace("_"," ",basename(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH), '.html')));   
}



function imgbase64($image){  
if ($image !== false){
    return 'data:image/jpg;base64,'.base64_encode(file_get_contents($image));
} 
}

function getSateName($State){
    
switch ($State) {
        case "2":
        $StateName= "Andhra Pradesh";
        break;
        case "3":
        $StateName= "Arunachal Pradesh";
        break;
        case "4":
        $StateName= "Assam";
        break;
        case "5":
        $StateName= "Bihar";
        break;
        case "33":
        $StateName= "Chhattisgarh";
        break;
        case "10":
        $StateName= "Goa";
        break;
        case "11":
        $StateName= "Gujarat";
        break;
        case "12":
        $StateName= "Haryana";
        break;
        case "13":
        $StateName= "Himachal";
        break;
        case "14":
        $StateName= "Jammu";
        break;
        case "35":
        $StateName= "Jharkhand";
        break;
        case "15":
        $StateName= "Karnataka";
        break;
        case "16":
        $StateName= "Kerala";
        break;
        case "18":
        $StateName= "Madhya Pradesh";
        break;
        case "19":
        $StateName= "Maharashtra";
        break;
        case "20":
        $StateName= "Manipur";
        break;
        case "21":
        $StateName= "Meghalaya";
        break;
        case "22":
        $StateName= "Mizoram";
        break;
        case "24":
        $StateName= "Orissa";
        break;
        case "26":
        $StateName= "Punjab";
        break;
        case "27":
        $StateName= "Rajasthan";
        break;
        case "28":
        $StateName= "Sikkim";
        break;
        case "29":
        $StateName= "Tamil Nadu";
        break;
        case "30":
        $StateName= "Tripura";
        break;
        case "31":
        $StateName= "Uttar Pradesh";
        break;
        case "34":
        $StateName= "Uttarakhand";
        break;
        case "32":
        $StateName= "West Bengal";
        break;
        case "9":
        $StateName= "Delhi";
        break;
        case "6":
        $StateName= "Chandigarh";
        break;
        case "36":
        $StateName= "Telangana";
        break;
        default:
        $StateName= "";
        break;
}   

return strtoupper($StateName);    
}

function auth_member_contact($mobile, $email) {
    $safeMobile = real_escape_string($mobile);
    $safeEmail = real_escape_string($email);
    $rows = db_fetch_all(
        'members',
        "mobile='".$safeMobile."' OR email='".$safeEmail."'",
        'user_id,username,name,email,mobile,password,status'
    );
    return is_array($rows) && count($rows) > 0 ? $rows[0] : null;
}

function auth_member_id($id) {
    $id = (int)$id;
    if ($id <= 0) {
        return null;
    }
    $rows = db_fetch_all(
        'members',
        "user_id='".$id."'",
        'user_id,username,name,email,mobile,password,status'
    );
    return is_array($rows) && count($rows) > 0 ? $rows[0] : null;
}

function auth_new_otp_state($extra = array()) {
    $otp = generateNumericOTP(6);
    $state = array_merge($extra, array(
        'otp_hash' => hash('sha256', (string)$otp),
        'otp_expiry' => time() + 600,
        'otp_attempts' => 0,
        'last_resend_at' => time(),
        'verified' => false
    ));
    return array($state, $otp);
}



function _ago($tm,$rcs = 0) {
$cur_tm = time(); 
$dif = $cur_tm-$tm;
$pds = array('second','minute','hour','day','week','month','year','decade');
$lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);

for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
    $no = floor($no);
    if($no <> 1)
        $pds[$v] .='s';
    $x = sprintf("%d %s ",$no,$pds[$v]);
    if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0))
        $x .= time_ago($_tm);
    return $x;
}

function current_timestamp(){
    return date("Y-m-d H:i:s");
}

function checkIPAddress($ipAddress) 
{
    return preg_match('/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ipAddress);
}
require_once(".db.php");
function generateNumericOTP($n) { 
    $generator = "1357902468"; 
    $result = ""; 
  
    for ($i = 1; $i <= $n; $i++) { 
        $result .= substr($generator, (rand()%(strlen($generator))), 1); 
    } 
  
    // Return result 
    return $result; 
} 

function order_txn_id(){
 return date("ymdHis").generateNumericOTP(8);   
}

function safe_str($value){
    $search = array("\\",  "\x00", "\n",  "\r",  "'",  '"', "\x1a", "-","+","=");
    $replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z", "","","");
    return strip_tags(str_replace($search, $replace, $value));
}

function safe_str_($value){
    $search = array("\\",  "\x00", "\n",  "\r",  "'",  '"', "\x1a", "_","+","=");
    $replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z", " ","","");
    return strip_tags(str_replace($search, $replace, $value));
}

function space_remove($string){
    return strip_tags(preg_replace('/\s+/','',strip_tags(str_replace(' ', '', $string))));
}

function safe_clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9\- ]/', '', $string); // Removes special chars.

   return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}

function divide($x,$y){
 return $x / $y;   
}

function real_escape_string(String $value){
$db = db();
$value = $db->escape_string(strip_tags($value));
$db->close(); 
return $value;
}


function is_valid_pincode($pincode){
if(is_numeric($pincode) && strlen($pincode)==6){
return $pincode;    
}
}

function is_valid_statecode($state){
if(is_numeric($state) && strlen($state)>0){
return $state;    
}
}

function is_valid_mobile($number){
if(is_numeric($number) && strlen($number)==10){
return $number;    
}
}


function is_valid_aadhaar($number){
if(is_numeric($number) && strlen($number)==12){
return $number;    
}
}

function is_valid_pan($number){
if(strlen($number)==10){
return $number;    
}
}


function is_valid_email($email){
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
return $email;    
}
}

function is_valid_amount($amount){
if(is_numeric($amount)){
return safe_str($amount);    
}
}

function is_valid_usertype($usertype){
if(in_array($usertype, ['Master Distributor','Distributor','Retailer'])){
return $usertype;
}
}



function is_access_usertype($user_data,$usertype){

if(in_array($user_data['usertype'], ['Admin'])){
return in_array($usertype,['Master Distributor','Distributor','Retailer'])? $usertype : false;
}else if(in_array($user_data['usertype'], ['Master Distributor'])){
return in_array($usertype,['Distributor','Retailer'])? $usertype : false;
}else if(in_array($user_data['usertype'], ['Distributor'])){
return in_array($usertype,['Retailer'])? $usertype : false;
} 

}


function is_valid_url($url){
if(filter_var($url, FILTER_VALIDATE_URL)){
return $url;    
}
}



function get_safe($string){
   return strip_tags($string);
}

function pt($data){
echo "<pre>";
print_r($data);
echo "</pre>";
}

function redirect($url,$time){
echo '<script>
setTimeout(
function(){
window.location = "'.$url.'" 
},'.$time.');
</script>';
}

function redirect_blank($url,$time){
echo '<script>
setTimeout(
function(){
window.open("'.$url.'");
},'.$time.');
</script>';
}


function baseurl(){
 return str_replace("www.","",$_SERVER['SERVER_NAME']);
}

function StrReplace($str,$fnd,$rep){
return str_replace($fnd,$rep,$str);     
}


function user_ip(){
return $_SERVER['REMOTE_ADDR'];
}

function http_post($url,$post_data,$header=array()){
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $post_data,
  CURLOPT_HTTPHEADER => $header
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}

function http_get($url,$header=array(),$timeout=0,$ssl=false){
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => $timeout,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => $header
));
$response = curl_exec($curl);

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

function db(){
global $dbhost, $dbuser, $dbpass, $dbname;
return new db($dbhost, $dbuser, $dbpass, $dbname);
}

function db_insert($tableName, $insData){
    $db = db();
    $columns = implode(", ",array_keys($insData));
    $escaped_values = array_map(array($db,"escape_string"), array_values($insData));
    foreach ($escaped_values as $idx=>$data) $escaped_values[$idx] = "'".$data."'";
    $values  = implode(", ", $escaped_values);
    $sql = "INSERT INTO $tableName ($columns) VALUES ($values)";
    $lastInsertID = $db->query($sql)->lastInsertID();
    $db->close(); 
    return $lastInsertID;
}

function db_update($tableName, $insData, $condition){
    $db = db();
    $sql = "UPDATE $tableName SET ";
    foreach($insData as $key=>$value) {
    $sql .= $key . " = '".$db->escape_string($value)."', "; 
    }
    $sql = trim($sql, ' ');
    $sql = trim($sql, ',');
    $sql .= " WHERE $condition";
    $affectedRows = $db->query($sql)->affectedRows();
    $db->close(); 
    return $affectedRows;
}

function db_fetch_array($tableName, $condition=false, $select="*"){
    $db = db();
    $sql = "SELECT $select FROM $tableName ";
    if($condition){
    $sql .= " WHERE $condition";
    }
    $fetchArray = $db->query($sql)->fetchArray();
    $db->close(); 
    return $fetchArray;
}

function db_fetch_all($tableName, $condition=false, $select="*"){
    $db = db();
    $sql = "SELECT $select FROM $tableName ";
    if($condition){
    $sql .= " WHERE $condition";
    }
    $fetchArray = $db->query($sql)->fetchAll();
    $db->close(); 
    return $fetchArray;
}

function db_sum($tableName, $columnName, $condition = false) {
    $db = db(); // Assuming db() is a function that initializes the database connection
    $sql = "SELECT SUM($columnName) as total FROM $tableName";
    if ($condition) {
        $sql .= " WHERE $condition";
    }
    $result = $db->query($sql)->fetchArray();
    $db->close();
    return $result['total'] ?? 0; // Return 0 if total is null
}


function db_describe($tableName){
    $db = db();
    $sql = "DESCRIBE $tableName ";
    $affectedRows = $db->query($sql)->fetchAll();
    $db->close(); 
    return $affectedRows;
}

function db_count($tableName, $condition = false) {
    $db = db();
    $sql = "SELECT COUNT(*) as count FROM $tableName";
    if ($condition) {
        $sql .= " WHERE $condition";
    }
    $result = $db->query($sql)->fetchArray();
    $db->close();
    return $result['count'];
}

function db_delete($tableName, $condition=false){
    $db = db();
    $sql = "DELETE FROM $tableName ";
    if($condition){
    $sql .= " WHERE $condition";
    }
    $affectedRows = $db->query($sql)->affectedRows();
    $db->close(); 
    return $affectedRows;
}

function get_username($data){
 return $data;
}

function get_agent_id($pan,$mobile){
 return substr($pan,0,4).substr($mobile,4);
}


function site_data(){
$db = db();
$result = $db->query("SELECT * FROM `sitedata` WHERE baseurl='".baseurl()."' ")->fetchArray();
$db->close(); 
return $result;    
}

function main_site_data(){
$db = db();
$result = $db->query("SELECT * FROM `sitedata` WHERE site_id='1' ")->fetchArray();
$db->close(); 
return $result;    
}

function apis($type){
  global $main_site_data;  
  return json_decode($main_site_data['apis'],true)[$type];
}

function p4pointsapi($type){
  global $main_site_data;  
  return json_decode($main_site_data['p4pointsAPI'],true)[$type];
}

function pvc_Stracture($type){
  global $main_site_data;  
  return json_decode($main_site_data['pvc_stracture'],true)[$type];
}

function paymentapi($type){
  global $main_site_data;  
  return json_decode($main_site_data['paymentapi'],true)[$type];
}

function smsapi($type){
  global $site_data;  
  return json_decode($site_data['smsapi'],true)[$type];
}


function smtp($type) {
    global $site_data;

    if (!isset($site_data['smtp'])) {
        return null; // or return a default value or trigger error log
    }

    $smtpConfig = json_decode($site_data['smtp'], true);
    
    return $smtpConfig[$type] ?? null;
}



function aes_encrypt($string,$password){
  return base64_encode(openssl_encrypt($string,"AES-128-ECB",$password));
}


function aes_decrypt($encrypted,$password){
  return openssl_decrypt(base64_decode($encrypted),"AES-128-ECB",$password); 
}


function sendWhatsAppSms($number, $message) {
    // ✅ Ensure number does not already start with 91
    $number = preg_replace('/^(\+91|)/', '', $number);
    $receiver = "91" . $number;

    // ✅ URL encode number and message
    $encodedReceiver = urlencode($receiver);
    $encodedMessage  = urlencode($message);

    // ✅ Get SMS API URL from config
    $smsapi_url = smsapi("url");

    if (empty($smsapi_url)) {
        error_log("SMS API URL is missing from config.");
        return false;
    }

    // ✅ Replace placeholders in the API URL
    $find  = array("{NUMBER}", "{MSG}");
    $repls = array($encodedReceiver, $encodedMessage);
    $url = str_replace($find, $repls, $smsapi_url);

    // ✅ Send request using cURL
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false, // Set to true in production
        CURLOPT_TIMEOUT => 10,
    ]);

    $response = curl_exec($ch);

    // ✅ Error handling
    if (curl_errno($ch)) {
        error_log("cURL Error: " . curl_error($ch));
        curl_close($ch);
        return false;
    }

    curl_close($ch);

    // ✅ Optional: Log response for debugging
    // error_log("WhatsApp SMS sent to {$receiver}: {$response}");

    return $response;
}

// Login || Register || Forgot WhatsApp SMS
function send_sms_credentials($usermobile, $whamessage) {
    global $site_data; 
    if (isset($site_data['whatsaapsms']) && $site_data['whatsaapsms'] == 'active') {
        sendWhatsAppSms($usermobile, $whamessage);
    }
}

// All Services WhatsApp SMS
function send_sms($usermobile, $whamessage) {
    global $site_data; 
    if (isset($site_data['whatsaapsmsReport']) && $site_data['whatsaapsmsReport'] == 'active') {
        sendWhatsAppSms($usermobile, $whamessage);
    }
}

$data = main_site_data();
$senderEmail = $data['email'] ?? null; // Site sender email
$webName     = $data['brand'] ?? 'One Touch'; // Default fallback name

// === SMTP Email Sender API PROCESS ===
function smtp_Email_SenderApi_Process($to, $subject, $body, $alt_body = null)
{
    if ($alt_body === null) {
        $alt_body = strip_tags($body);
    }

    $main   = main_site_data();
    $p4api  = json_decode($main['p4pointsAPI'] ?? '{}', true);
    $smtp   = json_decode($main['smtp'] ?? '{}', true);

    // Build query safely
    $getData = http_build_query([
        'apiKey'    => $p4api['p4points_apikey'] ?? '',
        'host'      => $smtp['host'] ?? '',
        'user'      => $smtp['username'] ?? '',
        'password'  => $smtp['password'] ?? '',
        'port'      => $smtp['port'] ?? '',
        'from_name' => $smtp['sender'] ?? '',
        'to'        => $to,
        'subject'   => $subject,
        'body'      => $body,
        'alt_body'  => $alt_body,
        'protocol'  => $smtp['protocol'] ?? '',
    ]);

    $urlBase = $p4api['p4points_url'] ?? '';
    if (empty($urlBase)) {
        return json_encode(["status" => "400", "message" => "API URL missing"]);
    }

    $url = "https://" . rtrim($urlBase, '/') . "/api/v1/send-email?" . $getData;

    // === CURL PROCESS ===
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);

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

    if ($error) {
        return json_encode(["status" => "500", "message" => $error]);
    }

    return $response;
}
// === GLOBAL SEND EMAIL FUNCTION ===
if (!function_exists('send_email')) {
    function send_email($emailsendmail, $emailsubject, $gmailMessage)
    {
        global $site_data, $senderEmail, $webName;

        // Check if email service is active
        if (isset($site_data['emailsms']) && $site_data['emailsms'] === 'active') {
            $webName = $webName ?? 'One Touch';
            $link = "https://" . baseurl();

            // HTML Email Template
            $emailBody = '
            <div style="font-family: Arial, sans-serif; background-color: #f9f9f9; padding: 0; margin: 0; max-width: 100%;">
                <table cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px; margin: auto; background-color: #ffffff; box-shadow: 0 5px 15px rgba(0,0,0,0.1); border-radius: 8px; overflow: hidden;">
                    <tr style="background-color: #003f7f;">
                        <td style="padding: 20px 30px; color: #ffffff;">
                            <table width="100%">
                                <tr>
                                    <td style="font-size: 24px; font-weight: bold;">' . htmlspecialchars($webName) . '</td>
                                    <td style="text-align: right;">
                                        <img src="https://pay.rapidxservices.in/layouts/members/assets/download.png" alt="Logo" style="height: 40px; border-radius: 4px;">
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>

                    <tr>
                        <td style="padding: 30px; text-align: center;">
                            <h2 style="color: #003f7f; margin-bottom: 15px;">' . htmlspecialchars($emailsubject) . '</h2>
                            <p style="font-size: 16px; color: #333; line-height: 1.6;">' . $gmailMessage . '</p>

                            <a href="' . $link . '" style="display: inline-block; margin-top: 25px; padding: 12px 24px; background-color: #0056b3; color: white; text-decoration: none; font-weight: bold; border-radius: 6px;">
                                Click to Visit Website
                            </a>
                        </td>
                    </tr>

                    <tr style="background-color: #f0f0f0;">
                        <td style="padding: 20px; text-align: center; font-size: 13px; color: #777;">
                            This is an automated message from <strong>' . htmlspecialchars($webName) . '</strong>. Please do not reply.
                        </td>
                    </tr>
                </table>
            </div>';

            // Send email through API process
            return smtp_Email_SenderApi_Process($emailsendmail, $emailsubject, $emailBody);
        }

        return json_encode([
            "status" => "503",
            "message" => "Email service is disabled."
        ]);
    }
}

function login(String $username, String $password){
$db = db();
$username = $db->escape_string(safe_str($username));
$password = $db->escape_string($password);
$members = $db->query("SELECT * FROM `members` WHERE username='".$username."' and password='".$password."' ")->fetchArray();
$result = array("status"=>false,"is_otp"=>"NO","login_token"=>md5(time()) ,"message"=>"Invalid Username OR Password !");  
if (isset($members['user_id']) && $members['user_id'] > 0 && $members['username'] == $username && $members['password'] == $password) {
$login_otp = generateNumericOTP(6);
$member_status = $members['status'];

if ($member_status != "Active") {
        $result = array(
            "status" => false,
            "message" => "Login failed. Your account is " . ucwords($member_status) . ". Please contact support."
        );
        $db->close();
        return $result;
}
$login_token = md5($login_otp);
if($members['usertype']=="Admin"){
$login_token = md5($members['username']);     
}

if($db->query("UPDATE `members` SET login_token='".$login_token."', login_otp='".$login_otp."' WHERE user_id='".$members['user_id']."' ")->affectedRows()){

if($members['is_otp']=="YES"){
$message = "Dear {$members['name']}, Your Login OTP is: {$login_otp} Please do not share this OTP anyone. https://".baseurl();    
send_sms($members['mobile'],$message);
send_email($members['email'],"Your Login OTP",$message);
}else{
$user_ip = user_ip();
$message = "Dear {$members['name']}, You have accessed {$members['username']} Account? And Login IP is: {$user_ip}, if not please change your password immediately. https://".baseurl();    
send_sms($members['mobile'],$message);
//send_email($members['email'],"User Login Details",$message);   
}


$result = array("status"=>true,"is_otp"=>$members['is_otp'],"login_token"=>$login_token);    
}

}
$db->close();   
return $result;
}


function login_otp_verify(String $login_token, Int $login_otp){
$db = db();
$login_token = $db->escape_string($login_token);
$members = $db->query("SELECT * FROM `members` WHERE login_token='".$login_token."' ")->fetchArray();
$result = array("status"=>false,"login_token"=>md5(time()));  
if($members['user_id']>0 && $members['login_token']==$login_token && $members['login_otp']==$login_otp){
$login_token = md5($login_token);
if($members['usertype']=="Admin"){
$login_token = md5($members['username']);    
}
$login_otp = generateNumericOTP(4);
if($db->query("UPDATE `members` SET login_token='".$login_token."', login_otp='".$login_otp."' WHERE user_id='".$members['user_id']."' ")->affectedRows()){

$user_ip = user_ip();
$message = "Dear {$members['name']}, You have accessed {$members['username']} Account? And Login IP is: {$user_ip}, if not please change your password immediately.";    
send_sms($members['mobile'],$message);
$result = array("status"=>true,"login_token"=>$login_token);    
}

}
$db->close();   
return $result;
}

function forgotpassword(String $username){
$db = db();
$username = $db->escape_string(safe_str($username));
$members = $db->query("SELECT * FROM `members` WHERE username='".$username."' ")->fetchArray();
$result = array("status"=>false);  
if (isset($members['user_id'], $members['username'], $members['usertype']) && $members['user_id'] > 0 && $members['username'] == $username && $members['usertype'] != "Admin") {
$password = generateNumericOTP(6);
if($db->query("UPDATE `members` SET password='".$password."', is_otp='YES' WHERE user_id='".$members['user_id']."' ")->affectedRows()){
$message = "Dear {$members['name']}, Your New Password: {$password} Login https://".baseurl();    
$email =$members['email'];
$subject = "Password Forgot Successfully";
send_email($email,$subject,$message);
send_sms($members['mobile'],$message);
$result = array("status"=>true);    
}
}
$db->close();   
return $result;
}

function resend_login_otp($login_token) {
    $db = db();
    $login_token = $db->escape_string($login_token);
    $members = $db->query("SELECT * FROM `members` WHERE login_token='" . $login_token . "'")->fetchArray();

    if ($members && $members['is_otp'] === 'YES') {
        $login_otp = generateNumericOTP(6);

        if ($db->query("UPDATE `members` SET login_otp='$login_otp' WHERE user_id='" . $members['user_id'] . "'")->affectedRows()) {
            $message = "Dear {$members['name']}, Your Login OTP is: {$login_otp}. Please do not share this OTP.";
            send_sms($members['mobile'], $message);
            send_email($members['email'], "Your Login OTP", $message);
            $db->close();
            return ["status" => true, "message" => "OTP has been resent successfully."];
        }
    }
    $db->close();
    return ["status" => false, "message" => "Unable to resend OTP. Please try again."];
}

function user_data(String $login_token){
global $dbhost, $dbuser, $dbpass, $dbname;
$db = new db($dbhost, $dbuser, $dbpass, $dbname);
$login_token = $db->escape_string($login_token);
$members = $db->query("SELECT * FROM `members` WHERE login_token='".$login_token."' ")->fetchArray();
$db->close();   
return $members;
}


//NSDL PAN APPLY CORRECTION api process
function NSDL_pan_apply_correction_api_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'name' => $request['name'],
    'gender' => $request['gender'],
    'mobileNumber' => $request['phoneNumber'],
    'email' => $request['emailID'],
    'application_mode' => $request['applicationMode'],
    'application_type' => $request['applicationType'],
    'orderID' => $request['orderID'],
    'branchCode' => $request['branchCode'],
    'redirect_url' => "https://".baseurl()."/members/Pan_Apply_Correction",
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v3/newApply?$getData");
return $resJson;
}

//NSDL encription status check api process
function NSDL_pan_encription_Status_api_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'encrypted_data' => $request['encrypted_data'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v3/ecncryptionStatus?$getData");
return $resJson;
}

//NSDL Incomplete Pan regenerate Link api process
function NSDL_incomplete_Pan_api_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'nsdl_orderid' => $request['order_id'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v3/incompletePan?$getData");
return $resJson;
}

//NSDL Pan Fainal Status Check api process
function NSDL_final_Pan_status_api_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'nsdl_orderid' => $request['order_id'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v3/checkStatus?$getData");
return $resJson;
}


//pan find api process
function panfind_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'uidNumber' => $request['aadhaar'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/getPanNumber?$getData");
    return $resJson;
}

//pan find api process
function panfind_run2($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'uidNumber' => $request['aadhaar'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/getPanNumberPremium?$getData");
    return $resJson;
}


//pan detils find api process
function panDetailsPrememium_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'panNumber' => $request['panNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/panVerificationPremium?$getData");
    return $resJson;
}


//pan to mask aadhar api process
function pantoUidfind_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'panNumber' => $request['panNumber'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v1/panAadhar?$getData");
return $resJson;
}

//Vehical Rc PDF api process
function vehicalRcGuardianVerification_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'vehicalNumber' => $request['vehicalNumber'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v1/RcToFatherName?$getData");
return $resJson;
}

//pan to mask aadhar api process
function pantoUidCheck_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'panNumber' => $request['panNumber'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v2/Pan2Uid/CheckStatus?$getData");
return $resJson;
}

//pan to mask aadhar api process
function pantomaskaadhar_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'panNumber' => $request['panNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/maskAadharVerification?$getData");
    return $resJson;
}

//Aadhar to mask pan api process
function aadhartomaskpan_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'uidNumber' => $request['uidNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/maskPanVerification?$getData");
    return $resJson;
}

//pan to mask aadhar api process
function panaadharlinkstatus_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'uidNumber' => $request['uidNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/pan-aadhaar-status?$getData");
    return $resJson;
}

//Vehical Rc PDF api process
function vehicalRcVerification_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'vehicalNumber' => $request['vehicalNumber'],
        'type' => $request['type'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/RcVerification?$getData");
    return $resJson;
}

//Vehical Rc PDF api process
function vehicalRcVerificationPdf_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'rcno' => $request['vehicalNumber'],
        'type' => $request['type'],
        'FatherName' => $request['fatherName'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/RcPDF?$getData");
    return $resJson;
}


//Driving Licence HD PDF api process
function DrivingLicenceHDPdf_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'dlNo' => $request['dlno'],
        'dob' => $request['dob'],
        'type' => $request['type'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/dlVerificationPdfPremium?$getData");
    return $resJson;
}

function DrivingLicenceHDPdf_run2($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'dlNo' => $request['dlno'],
        'dob' => $request['dob'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/dlVerificationPDF-Chip?$getData");
    return $resJson;
}

//Driving Licence CHIP PDF 2 api process
function DrivingLicenceCHipPdf_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'dlNo' => $request['dlno'],
        'dob' => '01-01-2000',
        'type' => $request['type'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/dlVerification?$getData");
    return $resJson;
}

//CHALLAN FIND api process
function Challanfind_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'vehicle' => $request['vehicalNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/challanVerification?$getData");
    return $resJson;
}

//Ration 2 Aadhaar find All State api process
function ration2uid_find_allstate_api_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'rationNumber' => $request['rationNumber'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v2/Ration2Uid/Apply?$getData");
return $resJson;
}

//Ration 2 Aadhaar find All State api process
function ration2uid_find_allstate_check_status_api_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'rationNumber' => $request['rationNumber'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v2/Ration2Uid/CheckStatus?$getData");
return $resJson;
}


//Ration 2 Aadhaar find api process
function ration2uid_finder_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'rationNumber' => $request['rationNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/Ration2Uid-up?$getData");
    return $resJson;
}

//Driving Find by name & dob api process
function dl_find_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'name' => $request['name'],
        'dob' => $request['dob'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/dlFind?$getData");
    return $resJson;
}

//Ration pdf api process
function rationpdf_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'rationNumber' => $request['rcNo'],
        'type' => $request['type'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/RationVerification?$getData");
    return $resJson;
}

//Ration pdf BY aadhar api process
function rationpdf_by_uid_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'uidNumber' => $request['uidNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/RationVerification_uid?$getData");
    return $resJson;
}

//Voter captcha details api process
function voter_captch_api_run($request)
{
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/v-Addition/captcha");
    return $resJson;
}

//Voter Advance api process
function voterAdvance_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'epicNumber' => $request['voterNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/voterVerification?$getData");
    return $resJson;
}

//Voter Mobile Link serch voter api process
function vcmserch_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'epic' => $request['voterNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/v-Addition/data-fetch?$getData");
    return $resJson;
}

//Voter Mobile Link Without OTP Manual api process
function VoterMobileLink_DataUpload_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'epicNumber'  => $request['voterNumber'],
    'mobileNumber' => $request['mobileNumber'],
]); 
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v2/VoterMobile/Apply?$getData");
return $resJson;
}

//Voter Mobile Link Without OTP Manual Status Check api process
function VoterMobileLink_DataCheckstatus_run($request){
$getData = http_build_query([
    'apiKey'       => p4pointsapi("p4points_apikey"),
    'epicNumber'   => $request['voterNumber'],
    'mobileNumber' => $request['mobileNumber'],
]); 
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v2/VoterMobile/CheckStatus?$getData");
return $resJson;
}


//Voter Mobile Link serch voter api process
function vcm_sendotp_api_run($request)
{
    $getData = http_build_query([
        'epic' => $request['voterNumber'],
        'nmobile' => $request['phoneNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/v-Addition/send-otp?nmobile=phoneNumber&epic=voterNumber");
    return $resJson;
}

//Voter Mobile Link serch voter api process
function vcm_Verifyotp_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'epic' => $request['voterNumber'],
        'mobileNo' => $request['mobileNo'],
        'otp' => $request['otp'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/v-Addition/verify-otp?$getData");
    return $resJson;
}

//Voter Original Pdf send otp api process 
function voter_pdf_send_otp_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'epic' => $request['voterNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/v-Addition/Pdf-Download/send-otp?$getData");
    return $resJson;
}

//Voter Original Pdf Verify otp api process 
function voter_pdf_verify_otp_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'epic' => $request['epic'],
        'type' => $request['otpv'],
        'otp' => $request['otp'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/serviceApi/V1/Voter-pdf.php?$getData");
    return $resJson;
}

//IFSC Code api process 
function ifsc_code_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'ifsc' => $request['ifscCode'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/ifscVerification?$getData");
    return $resJson;
}

//IFSC Code api process 
function pin_code_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'pincode' => $request['pincode'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/PincodeVerification?$getData");
    return $resJson;
}

//Mobile Number Verification api process 
function mobile_operator_verify_api_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'Mobileno' => $request['phoneNumber'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v1/mobileLookup?$getData");
return $resJson;
}

//Recharge Plan fetch api process 
function mobileRecharge_plan_api_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'mobileNumber' => $request['mobileNumber'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v1/mobileRecharge/plan?$getData");
return $resJson;
}

//Recharge Request api process 
function Quick_Recharge_api_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'number' => $request['number'],
    'amount' => $request['amount'],
    'opcode' => $request['opcode'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v1/mobileRecharge/recharge?$getData");
return $resJson;
}

//Recharge Request api process 
function Quick_Recharge_status_api_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'orderid' => $request['order_id']
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v1/mobileRecharge/statusCheck?$getData");
return $resJson;
}


//Uidai aadhar verification api process 
function aadhaar_verify_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'uidNumber' => $request['uidNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/eid/verifyUid?$getData");
    return $resJson;
}

//Uidai Enrollment api process 
function enrollment_status_verify_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'eid' => $request['eidNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/eid/enrollment-Status?$getData");
    return $resJson;
}

//Uidai Enrollment api process 
function Api_balance_info_api_run()
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/Balance_info?$getData");
    return $resJson;
}

//Uid to instant details without otp finger api process 
function uid_to_instant_detilas_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'aadhaar' => $request['uidNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/eshramVerification?$getData");
    return $resJson;
}

//sharmadhan card api process 
function sharmadhad_card_detilas_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'registration_no' => $request['registration_no'],
    ]);
    // http_get returns JSON string response
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v2/sharmadhan_card_details?$getData");
    return $resJson;
}

//Ayushman api process 
function ayushmanVerify_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'aadhaar' => $request['uidNumber'],
        'stateCode' => $request['stateCode'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/PmjayVerification?$getData");
    return $resJson;
}


// Aadhaar verification API function
function performAadhaarVerification($aadhar, $bioenc)
{

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://" . p4pointsapi("p4points_url") . "/api/v1/uid/ekycVerification",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => array('apiKey' => p4pointsapi("p4points_apikey"), 'bioenc' => $bioenc, 'aadhar' => $aadhar, 'bioenc' => $bioenc),
    ));
    $response = curl_exec($curl);
    return $response;
}
//Driving Licence HD PDF api process
function rtpsCertificate_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'applicationNumber' => $request['applicationNumber'],
        'name' => $request['name'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/RtpsCertificate-Br?$getData");
    return $resJson;
}
//Family Id Hariyana api process
function familyIdVerification_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'familyid' => $request['familyid'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/Hr_Services/familyVerification?$getData");
    return $resJson;
}

//JanAadhaar Member Details find api process
function janaadharMember_details_find_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'janaadhar' => $request['janaadharNumber'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v1/janadharVerification?$getData");
return $resJson;
}

//Application find by Learning Licence & Mobile No. api process
function ApplicationNo_find_by_LearningLicence_mobile_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'licenceNumber' => $request['licenceNumber'],
    'mobileNumber'  => $request['mobileNumber'],
    'dob'           => $request['dob'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v1/LL_application_find?$getData");
return $resJson;
}

//Learning Licence PDF api process
function LearningLicenceHDPdf_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'idNumber' => $request['idNumber'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v1/LL_application_pdf?$getData");
return $resJson;
}

//Chassis to rc find api process
function chassis2Rc_find_api_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'chassisNumber' => $request['chassisNumber'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v1/chassis_to_Rc?$getData");
return $resJson;
}

//Dl To Mobile find api process
function Dl2_Mobile_find_api_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'dlNo' => $request['dlNumber'],
    'dob' => $request['dob'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v1/dlMobileFind?$getData");
return $resJson;
}


//JanAadhaar PDF api process
function janaadharfind_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'uidNumber' => $request['uidNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/janadharFind?$getData");
    return $resJson;
}

//Farmer DBT Verification api process 
function farmerDbt_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'inputNumber' => $request['inputNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/dbtAgricultureVerification?$getData");
    return $resJson;
}

//NPCI BANK LINK Status api process 
function NpciLinkCheckStatus_api_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'uidNumber' => $request['uidNumber'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v1/uidSeedingStatus?$getData");
return $resJson;
}

//Bihar Electric Bill PDF api process 
function biharElectricPDF_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'caNumber' => $request['caNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/elctricBillPDF?$getData");
    return $resJson;
}

//Electric Bill All Indai Verification api process 
function ElectricBill_fetch_AllIndia_Opertor_Fetach_run()
{
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/electricBill_Operator");
    return $resJson;
}

//Electric Bill All Indai Verification api process 
function ElectricBill_fetch_AllIndia_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'bill_number' => $request['caNumber'],
        'operator_code' => $request['operator'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/electricBillFetch?$getData");
    return $resJson;
}

//JanAadhaar PDF api process
function JanAadharPdf_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'janaadhar' => $request['janaadhar'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/janadharPdf?$getData");
    return $resJson;
}



/*
|--------------------------------------------------------------------------
| New Farmer Certificate API
|--------------------------------------------------------------------------
*/
function farmeragri_api_run($request)
{
    $getData = http_build_query([
        'apiKey'    => p4pointsapi("p4points_apikey"),
        'uidNumber' => trim($request['uidNumber'] ?? ''),
        'language' => "hi",
    ]);

    $apiUrl = "https://" . p4pointsapi("p4points_url")
        . "/api/v1/AgriStak/approvedFarmersPdf?"
        . $getData;

    return http_get($apiUrl);
}

/*
|--------------------------------------------------------------------------
| Old Farmer Certificate API
|--------------------------------------------------------------------------
*/
function farmeragri_api_run2($request)
{
    $getData = http_build_query([
        'apiKey'    => p4pointsapi("p4points_apikey"),
        'uidNumber' => trim($request['uidNumber'] ?? ''),
        'language'  => trim($request['language'] ?? ''),
    ]);

    $apiUrl = "https://" . p4pointsapi("p4points_url")
        . "/api/v1/AgriStak/approvedFarmersPdf2?"
        . $getData;

    return http_get($apiUrl);
}

/*
|--------------------------------------------------------------------------
| Advance Farmer Certificate API
|--------------------------------------------------------------------------
*/
function farmeragri_api_run3($request)
{
    $getData = http_build_query([
        'apiKey'    => p4pointsapi("p4points_apikey"),
        'uidNumber' => trim($request['uidNumber'] ?? ''),
        'language' => "hi",
    ]);

    $apiUrl = "https://" . p4pointsapi("p4points_url")
        . "/api/v1/AgriStak/approvedFarmersPdfA?"
        . $getData;

    return http_get($apiUrl);
}

function farmeragri_state_server_api($request = [])
{
    $getData = http_build_query([
        'apiKey'    => p4pointsapi("p4points_apikey"),
        'uidNumber' => trim($request['uidNumber'] ?? ''),
    ]);

    $apiUrl = "https://" . p4pointsapi("p4points_url")
        . "/api/v1/AgriStak/stateServer.php?"
        . $getData;

    return http_get($apiUrl);
}



function farmeragri_state_check_api($request)
{
    $getData = http_build_query([
        'apiKey'    => p4pointsapi("p4points_apikey"),
        'uidNumber' => trim($request['uidNumber'] ?? ''),
        'state'     => strtolower(trim($request['state'] ?? '')),
    ]);

    $apiUrl = "https://" . p4pointsapi("p4points_url")
        . "/api/v1/AgriStak/stateCheck.php?"
        . $getData;

    return http_get($apiUrl);
}

// Aadhaar Pvc

function aadhaar_pdf_convert_api($filePath, $fileName, $type, $password, $mobile = "")
{
    $url = "https://" . p4pointsapi("p4points_url") . "/serviceApi/FlexSecureV1/Aadhaar/AadharPdfconvert";

    $postData = [
        "file" => new CURLFile($filePath, "application/pdf", $fileName),
        'apiKey' => p4pointsapi("p4points_apikey"),
        "type" => $type,
        "password" => $password,
        "mobile" => $mobile
    ];

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 120,
        CURLOPT_SSL_VERIFYPEER => false
    ]);

    $result = curl_exec($ch);
    $error  = curl_error($ch);
    curl_close($ch);

    if ($error) {
        return json_encode([
            "status" => false,
            "statusMessage" => $error
        ]);
    }

    return $result;
}

//Farmer Agri Status api process 
function farmeragriCheckStatus_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'uidNumber' => $request['uidNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/AgriStak/checkStatus?$getData");
    return $resJson;
}



//Aadhar Download Send OTP api process 
function aadharOtp_Send_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'aadhar' => $request['uidNumber'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/uid/otp/send_otp?$getData");
    return $resJson;
}

//Aadhar Download Verify OTP api process 
function aadharOtp_Verify_api_run($request)
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
        'aadhar' => $request['uidNumber'],
        'token' => $request['token'],
        'otp' => $request['otp'],
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/uid/otp/Verify_otp?$getData");
    return $resJson;
}


//JanAadhaar Status Checking api process
function janaadhar_Status_run($request){
$getData = http_build_query([
    'apiKey' => p4pointsapi("p4points_apikey"),
    'janaadhar' => $request['janaadhar'],
]);
$resJson = http_get("https://".p4pointsapi("p4points_url")."/api/v1/janadharStatus?$getData");
return $resJson;
}

// Aadhaar verification API function
function performAadhaarVerification_Server1($aadhar, $bioenc, $esMobile, $authToken) {
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://".p4pointsapi("p4points_url")."/api/v1/uid/ekyc_Otp/ekycVerification",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 60,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'POST',
      CURLOPT_POSTFIELDS => array('apiKey' => p4pointsapi("p4points_apikey"),'aadhar' => $aadhar,'bioenc' => $bioenc, 'mobileNumber' => $esMobile, 'authToken' => $authToken),
    ));
    $response = curl_exec($curl);
    return $response;
}


// Aadhaar Mobile OTP send API function
function aadhaar_otpSend_mobile_api_run($Mobile) {
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://".p4pointsapi("p4points_url")."/api/v1/uid/ekyc_Otp/send_otp",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 60,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'POST',
      CURLOPT_POSTFIELDS => array('apiKey' => p4pointsapi("p4points_apikey"),'mobileNumber' => $Mobile),
    ));
    $response = curl_exec($curl);
    return $response;
}

// Aadhaar Mobile OTP Verification API function
function aadhaar_otpVerify_mobile_api_run($Mobile, $otp) {
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://".p4pointsapi("p4points_url")."/api/v1/uid/ekyc_Otp/verify_otp",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 60,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'POST',
      CURLOPT_POSTFIELDS => array('apiKey' => p4pointsapi("p4points_apikey"),'mobileNumber' => $Mobile,'otp' => $otp),
    ));
    $response = curl_exec($curl);
    return $response;
}



// Aadhaar verification API function
function performAadhaarVerification_Server2($aadhar, $bioenc)
{

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://" . p4pointsapi("p4points_url") . "/api/v1/uid/ekycVerification_Server2",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => array('apiKey' => p4pointsapi("p4points_apikey"), 'aadhar' => $aadhar, 'bioenc' => $bioenc),
    ));
    $response = curl_exec($curl);
    return $response;
}
?>
