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


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 _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;
    return json_decode($site_data['smtp'], true)[$type];
}


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)
{
    $smsapi_url = smsapi("url");
    $message = urlencode($message);
    $find = array("{NUMBER}", "{MSG}");
    $repls = array($number, $message);
    $url = StrReplace($smsapi_url, $find, $repls);
    $response = http_get($url, [], 30, true);
    return $response;
}

function send_sms($usermobile, $whamessage)
{
    global $site_data;
    if (isset($site_data['whatsaapsms']) && $site_data['whatsaapsms'] == 'active') {
        sendWhatsAppSms($usermobile, $whamessage);
    }
}

$data = main_site_data();
$senderEmail = $data['email'] ?? null; // Safely access 'email'
$webName = $data['brand'] ?? null;     // Safely access 'brand'

function send_hkb_gmail($email, $subject, $message, $headers = '')
{
    global $senderEmail, $webName;

    if (empty($headers)) {
        $headers = 'From: ' . $webName . ' <' . $senderEmail . '>' . "\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    }

    $emailBody = '
<div style="font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 0; margin: 0; max-width: 100%;">
    <div style="background: linear-gradient(to bottom, #0056b3, #003f7f); color: white; padding: 15px; display: flex; justify-content: space-between; align-items: center; max-width: 600px; margin: auto; box-shadow: 0 4px 8px rgba(0,0,0,0.2);">
        <div style="font-weight: bold; font-size: 24px; text-shadow: 1px 1px 2px black;">' . htmlspecialchars($webName) . '</div>
        <div><img src="https://panel.rechargepay.lol/layouts/home/download.png" alt="Government Logo" style="height: 50px; border-radius: 5px; max-width: 120%;"></div>
    </div>
    <div style="text-align: center; background-color: white; padding: 20px; margin: 20px auto; border-radius: 15px; max-width: 600px; box-shadow: 0 6px 12px rgba(0,0,0,0.2);">
        <h1 style="color: #003f7f; text-shadow: 1px 1px 2px gray;">' . htmlspecialchars($subject) . '</h1>
        <p style="font-size: 18px; color: #333; line-height: 1.6; margin: 20px 0;">' . $message . '</p>
    </div>
    <div style="background: linear-gradient(to bottom, #0056b3, #003f7f); color: white; padding: 15px; display: flex; justify-content: space-between; align-items: center; max-width: 600px; margin: auto; box-shadow: 0 4px 8px rgba(0,0,0,0.2);">
        <p>This is an official mail. Please do not reply.</p>
    </div>
</div>';
    return mail($email, $subject, $emailBody, $headers);
}


function send_email($emailsendmail, $emailsubject, $gmailMessage)
{
    global $site_data;
    if (isset($site_data['emailsms']) && $site_data['emailsms'] == 'active') {
        send_hkb_gmail($emailsendmail, $emailsubject, $gmailMessage);
    }
}

// if first mail sender is not working then use smpt mail

// function send_email($email,$subject,$message) {
// $curl = curl_init();
// $from = "Instant Solution <multihub@aisensy.in>";
// $data = array(
//     'to' => array($email),
//     'from' => $from,
//     'subject' => $subject,
//     'content' => array(
//         array(
//             'type' => 'text/html',
//             'value' => $message
//         )
//     )
// );

// $data_string = json_encode($data);

// curl_setopt_array($curl, array(
//     CURLOPT_URL => "https://api.mailazy.com/v1/mail/send",
//     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 => $data_string,
//     CURLOPT_HTTPHEADER => array(
//         "X-Api-Key: cc5cf7qouhjuaf8t2degaSwSBPkLdj",
//         "X-Api-Secret: WwmkTKBcoRLYkGyjRDHpBixlMKE.ucyw7ecJz9Xvn5XXV6bBHa",
//         "Content-Type: application/json"
//     ),
// ));

// $response = curl_exec($curl);

// curl_close($curl);
// return $response;
// }

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. https://" . baseurl();
            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 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;
}

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


//Driving Licence HD PDF api process
function DrivingLicenceHDPdf_run($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?$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 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 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;
}

//IFSC Code 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;
}

//Uidai Captcha api process 
function aadhar_captcha_code_api_run()
{
    $getData = http_build_query([
        'apiKey' => p4pointsapi("p4points_apikey"),
    ]);
    $resJson = http_get("https://" . p4pointsapi("p4points_url") . "/api/v1/eid/captcha?$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'],
        'imgcaptcha' => $request['imgcaptcha'],
        'captchaTxnId' => $request['captchaTxnId'],
    ]);
    $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'],
        'imgcaptcha' => $request['imgcaptcha'],
        'captchaTxnId' => $request['captchaTxnId'],
    ]);
    $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 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;
}

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



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

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


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