<?php
require_once("../layouts/members/head.php");
if (isset($user_data['aadhar_fingerPrint_service']) && $user_data['aadhar_fingerPrint_service'] == "YES") {
if (in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])) {
    $getresult = false;
?>
<?php
if (isset($_POST['bioenc'])) {
    $getresult = true;
    $bio = $_POST['bioenc'];
    $aadhar = $_POST['aadhar'];

    $amount = $user_data['aadhar_advance_fee'];
    $old_balance = $user_data['balance'];
    $new_balance = $old_balance - $amount;

         if ($old_balance >= $amount) {
            $order_id = order_txn_id();
            $response = performAadhaarVerification($aadhar, $bio);
            $json = json_decode($response, true);
            
            //echo $response;
            $img = $json['image'] ?? ''; 
            $uid = $json['uid'] ?? '';
            $name = $json['name'] ?? '';
            $dob = $json['dobadhar'] ?? '';
            $gender=$json['gender'] ?? '';
            $txtadd = $json['address'] ?? '';
            
            if (isset($json['status']) && $json['status'] == '100') {
             $getresult = true;
             $updateSuccess = db_update("members", ["balance" => $new_balance], "user_id='{$user_data['user_id']}'");
            if ($updateSuccess) {
                $insData = [
                    'site_id'       => $site_data['site_id'],
                    'user_id'       => $user_data['user_id'],
                    'username'      => $user_data['username'],
                    'name'          => $user_data['name'],
                    'operator'      => $user_data['usertype'],
                    'parent_id'     => $user_data['parent_id'],
                    'order_id'      => $order_id,
                    'service'       => "AADHAAR FINGERPRINT",
                    'type'          => "Debit",
                    'account_number'=> $json['uid'],
                    'app_type'      => "AADHAAR FINGERPRINT",
                    'amount'        => $amount,
                    'main_amount'   => $amount,
                    'old_balance'   => $old_balance,
                    'new_balance'   => $new_balance,
                    'txn_id'        => $order_id,
                    'ref_id'        => $json['uid'],
                    'description'   => "Rs.{$amount} Has Been Debit From Wallet for Name {$json['name']} for AADHAAR FINGERPRINT PDF By UID ",
                    'date_time'     => current_timestamp(),
                    'status'        => "Success"
                ];

                $insertId = db_insert("reports", $insData);
                if ($insertId) {
                    $fields = [
                        'name' => 'Name',
                        'dobadhar' => 'DOB',
                        'gender' => 'Gender',
                        'address' => 'Location',
                    ];

                     $whamessage = "Dear {$user_data['name']},\nYour Request for UID *{$aadhar}* To Fingerprint Verification has been Complete.\n\n";
                     foreach ($fields as $key => $label) {
                         if (!empty($json[$key]) && isset($json[$key])) {
                             $whamessage .= "*$label*: {$json[$key]}\n";
                         }

                     }
                     $whamessage .= "\nBest Regards,\n_*{$site_data['brand']}.*_";
                     send_sms($user_data['mobile'], $whamessage);
                 } else {
                     awal_alert_msg("Insert Server Error!", 'error');
                 }
             } else {
                 awal_alert_msg("Balance debited from wallet but not updated in the database. Please contact support!", 'error');
             }
        } else {
           $getresult = false;
           awal_alert_msg($json['error'] ?? 'Server Down', 'error');
        }
    } else {
       awal_alert_msg("Insufficient Wallet Balance!", 'error');
    } 

}

// Check if the data saving form is submitted
if (isset($_POST['savedata'])) {
    $name = $_POST['name'];
    $address = $_POST['address'];
    $aadharno = $_POST['aadharno'];
    $username = $_POST['username'];
    $dobadhar = $_POST['dobadhar'];
    $houseno = $_POST['houseno'];
    $street = $_POST['street'];
    $pincode = $_POST['pincode'];
    $vtc = $_POST['vtcandpost'];
    $dist = $_POST['dist'];
    $state = $_POST['statename'];
    $language = $_POST['language'];
    $imgdata = $_POST['imgdata'];
    $ddate = $_POST['ddate'];
    $namelocal = $_POST['namelocal'];
    $birthtithilocal = $_POST['birthtithilocal'];
    $gender = $_POST['gender'];
    $birthtithi = $_POST['birthtithi'];
    $pata = $_POST['pata'];
    $patalocal = $_POST['patalocal'] ?? 'Address';
    $genderlocal = $_POST['genderlocal'];
    $addresslocal = $_POST['addresslocal'];
    $enrollmentlocal = $_POST['enrollmentlocal'] ?? '.';
    $orderID = $_POST['orderID'];
    $printData = array(
        'name' => $name,
        'address' => $address,
        'aadharno' => $aadharno,
        'username' => $username,
        'dobadhar' => $dobadhar,
        'houseno' => $houseno,
        'street' => $street,
        'pincode' => $pincode,
        'vtcandpost' => $vtc,
        'dist' => $dist,
        'statename' => $state,
        'language' => $language,
        'enrollmentlocal' => $enrollmentlocal,
        'ddate' => $ddate,
        'namelocal' => $namelocal,
        'birthtithilocal' => $birthtithilocal,
        'gender' => $gender,
        'birthtithi' => $birthtithi,
        'pata' => $pata,
        'patalocal' => $patalocal,
        'genderlocal' => $genderlocal,
        'addresslocal' => $addresslocal,
        'imgdata' => $imgdata,
    );

    // Set a remark for the transaction
    $Mremark = 'Name: ' . $name . " - Aadhar Number: " . $aadharno;

    // Insert print record into the database
    $insData = [
        'order_id'      => $orderID,
        'username'      => $user_data['username'],
        'name'          => $name,
        'idNumber'      => $aadharno,
        'service'       => "Aadhar_FingerPrint",
        'date_time'     => current_timestamp(),
        'printData'     => base64_encode(str_replace("\\", "", json_encode($printData, JSON_UNESCAPED_UNICODE))),
        'photo'         => $imgdata,
    ];

    $insertId = db_insert("printRecords", $insData);
    
    if ($insertId) {
         awal_alert_msg("Download Successful from '.$Mremark.'.", 'success');
        redirect('printRecord', 3000);
    } else {
         awal_alert_msg("Saving Data Error!", 'error');
     }
}
?>
<style>
.xxctyOkaM8bvp4lm2amz {
    display: block;
    margin-bottom: 50px;
    text-align: center;
    height: 100px;
    margin-top: 3%;
}
.Xj6seOK2KDoCGIvsPERK {
    width: 120px;
}
.LFvZ84K5eG9rZIj8aH7y {
    font-size: 12px;
    text-align: center;
}
</style>
<div class="container-xxl flex-grow-1 container-p-y">
    <div class="row">
<!-- Aadhaar Print biometric capacitor -->
<?php if (!isset($json['name']) || $json['name'] == '') { ?>
<div class="col-lg-4 d-flex align-items-strech m-auto <?php echo $getresult ? 'd-none' : ''; ?> ">
   <div id="errors" class="card text-bg-primary border-0 w-100">
      <div class="card mx-2 mb-2 sprint-box mt-2">
         <div class="card-body">
            <div class="mb-3">
               <div class="d-flex align-items-center">
                  <h5 class="mb-0 mt-0 uidai">Enter Your Aadhaar Number <span style="color:red;">*</span></h5>
               </div>
               <div class="mt-1">
                  <div class="input-group">
                     <button class="btn bg-danger rounded-start" type="button" style="color: #fff">UID</button>
                     <input name="ctl00$ContentPlaceHolder1$txtUID" aria-label="ctl00$ContentPlaceHolder1$txtUID" aria-describedby="basic-addon-search31" type="text" autofocus maxlength="12" oninput="verify()" id="txtUID" class="form-control vd_Required A_AadharNo" aria-describedby="Help" autocomplete="off" autofocus placeholder="9999 XXXX XXXX" required/>
                  </div>
                  <span style="font-size:12px; color:red;" id="basic-addon-search32"></span>
               </div>
               <!--<div class="form-check form-check-inline mt-2">-->
               <!--   <input name="collapsible-address-type" class="form-check-input" type="radio" value="" id="collapsible-address-type-office" required>-->
               <!--   <label class="form-check-label text-primary" for="collapsible-address-type-office"> Terms and Conditions: </label>-->
               <!-- </div>-->
            </div>
            <div class="">
               <div class="">
                  <div id="ready" class="d-none">
                     <a href="javascript:void(0);" class="xxctyOkaM8bvp4lm2amz"><img class="Xj6seOK2KDoCGIvsPERK" id="capture" src="../layouts/members/assets/images/ready.png">
                        <p class="LFvZ84K5eG9rZIj8aH7y" style="color: green;"> <b>Device connected. please capture your right finger</b></p>
                     </a>
                  </div>
                  <div id="successcap" class="d-none">
                     <a href="javascript:void(0)" class="xxctyOkaM8bvp4lm2amz"><img class="Xj6seOK2KDoCGIvsPERK" src="../layouts/members/assets/images/yes.png">
                        <p class="LFvZ84K5eG9rZIj8aH7y" style="color: green;"> <b>Finger Captured successfully</b></p>
                     </a>
                  </div>
                  <div id="scaning" class="d-none">
                     <a href="javascript:void(0)" class="xxctyOkaM8bvp4lm2amz"><img class="Xj6seOK2KDoCGIvsPERK" src="../layouts/members/assets/images/fingerprint-scan.gif">
                        <p class="LFvZ84K5eG9rZIj8aH7y" style="color: green;"> <b>Finger scanned please wait!</b></p>
                     </a>

                  </div>
                  <div id="timeout" class="d-none">
                     <a href="javascript:void(0)" class="xxctyOkaM8bvp4lm2amz"><img class="Xj6seOK2KDoCGIvsPERK" src="../layouts/members/assets/images/not.png">
                        <p class="LFvZ84K5eG9rZIj8aH7y" style="color: green;"> <b>Fingerprint capture timed out. Please try again</b></p>
                     </a>

                  </div>
                  <div id="notready" class="">
                     <a href="javascript:void(0)" class="xxctyOkaM8bvp4lm2amz"><img class="Xj6seOK2KDoCGIvsPERK" src="../layouts/members/assets/images/not.png">
                        <p class="LFvZ84K5eG9rZIj8aH7y" style="color: red;"> <b>Device not connected. Please try again.</b></p>
                     </a>
                  </div>
                  <div id="notplgin" class="">
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>
<!-- End Aadhaar Print biometric capacitor -->

<!-- Hidden Form for Data Submission -->
<form  action="" method="post" name='f1' style="display:none;">
  <input type="hidden" name="aadhar" id="aadhar"/>
  <textarea name="bioenc" id="biodata"></textarea>
</form>
<?php }else{?>
<!-- Aadhaar Details Fetch Success -->
<div class="col-lg-12 m-auto p-t-10 <?= isset($getresult) && $getresult ? '' : 'd-none' ?>">
   <div class="card border">
      <div class="card-body">
          <div class="figure d-block">
            <blockquote class="blockquote"> 
            <b style="color:black;">Your Aadhaar Card Details has been Fetch Successfully</b>
          </div>
         <form method="post" action="" id="myForm">
            <div class="row mb-3">
               <label class="col-sm-2 col-form-label" for="basic-default-name">Aadhaar Name :</label>
               <div class="col-sm-5">
                  <input type="text" class="form-control" name="name" id="name" placeholder="Enter Name" value="<?= isset($name) ? $name : ''; ?>" required readonly>
                  <input type="hidden" class="form-control" name="orderID" id="orderID" value="<?= isset($order_id) ? $order_id : ''; ?>" required readonly>
               </div>
               <div class="col-sm-2">
                  <img src="<?= isset($img) ? $img : ''; ?>" height="100%" width="70">
               </div>
            </div>
            <div class="row mb-3" style="margin-top: -40px">
               <label class="col-sm-2 col-form-label" for="basic-default-name">Full Address</label>
               <div class="col-sm-5">
                  <input type="text" class="form-control" id="txtSource" name="address" value="<?= isset($txtadd) ? $txtadd : ''; ?>" required>
               </div>
            </div>
            <div class="row mb-3">
               <label class="col-sm-2 col-form-label" for="basic-default-company">Aadhaar Number</label>
               <div class="col-sm-5">
                  <input class="form-control" maxlength="12" id="aadharno" name="aadharno" type="text" value="<?= isset($uid) ? $uid : ''; ?>" required readonly>
               </div>
            </div>
            <div class="row mb-3">
               <label class="col-sm-2 col-form-label" for="basic-default-email">Date of Birth</label>
               <div class="col-sm-5">
                  <input class="form-control" name="username" type="hidden" value="<?= isset($userdata['username']) ? time() : ''; ?>" required readonly>
                  <input class="form-control" name="dobadhar" type="text" value="<?= isset($dob) ? $dob : ''; ?>" required readonly>
                  <input class="form-control" name="houseno" type="hidden" value="<?= isset($houseno) ? $houseno : ''; ?>">
                  <input class="form-control" name="street" type="hidden" value="<?= isset($street) ? $street : ''; ?>">
                  <input class="form-control" name="pincode" type="hidden" value="<?= isset($pincode) ? $pincode : ''; ?>">
                  <input class="form-control" name="vtcandpost" type="hidden" value="<?= isset($vtc) ? $vtc : ''; ?>">
                  <input class="form-control" name="dist" type="hidden" value="<?= isset($dist) ? $dist : ''; ?>">
                  <input class="form-control" name="statename" type="hidden" value="<?= isset($state) ? $state : ''; ?>">
               </div>
            </div>
            <div class="row mb-3">
               <label class="col-sm-2 col-form-label" for="basic-default-company">Gender Local</label>
               <div class="col-sm-5">
                  <input type="text" class="form-control" name="genderlocal" id="genderlocal" placeholder="Auto fetched when Language Select" required>
               </div>
            </div>
            <div class="row mb-3">
               <label class="col-sm-2 col-form-label" for="basic-default-company">DOB Local</label>
               <div class="col-sm-5">
                  <input class="mng_cp form-control" id="birthtithilocal" name="birthtithilocal" type="text" placeholder="Auto fetched when Language Select" required>
               </div>
            </div>
            <div class="row mb-3">
               <label class="col-sm-2 col-form-label" for="basic-default-company">Name Local</label>
               <div class="col-sm-5">
                  <input type="text" class="form-control" id="name_regional" name="namelocal" placeholder="Auto fetched when Language Select" required>
               </div>
            </div>
            <div class="row mb-3">
               <label class="col-sm-2 col-form-label" for="basic-default-company">Full Address Local</label>
               <div class="col-sm-5">
                  <input type="text" id="txtTarget" class="form-control" name="addresslocal" placeholder="Auto fetched when Language Select" rows="3" required>
               </div>
            </div>
            <div class="row">
               <label class="col-sm-2 col-form-label" for="basic-default-phone">Language</label>
               <div class="col-sm-5 ">
                  <select autofocus class="form-control" name="language" id="language" required>
                     <option value="">Select Language</option>
                     <option value="HI">Hindi</option>
                     <option value="PA">Punjabi</option>
                     <option value="GU">Gujarati</option>
                     <!--<option value="MR">Marathi</option> -->
                     <!--<option value="TA">Tamil</option>-->
                     <option value="KN">Kannada</option>
                     <option value="BN">Bengali</option>
                     <option value="TE">Telugu</option>
                     <!--<option value="OR">Oriya</option>-->
                     <!--<option value="SD">Sindhi</option>-->
                  </select>
               </div>
               <div class="col-sm-3">
                  <input type="hidden" value="<?= isset($img) ? $img : ''; ?>" name="imgdata">
                  <?php $timestamp = date("Y-m-d"); ?>
                  <input type="hidden" class="form-control" name="ddate" id="exampleFormControlInput1" placeholder="12/12/2019" value="<?= isset($timestamp) ? $timestamp : ''; ?>" required>
                  <input type="hidden" class="form-control" name="gender" id="gender" value="<?= isset($gender) ? $gender : ''; ?>" placeholder="Male">
                  <input class="form-control" id="birthtithi" name="birthtithi" readonly="readonly" type="hidden" value="Birth Tithi">
                  <input class="form-control" id="pata" name="pata" readonly="readonly" type="hidden" value="address">
                  <input class="form-control" id="patalocal" name="patalocal" readonly="readonly" type="hidden" value="address">
                  <input class="form-control" id="enrollment" name="enrollment" readonly="readonly" type="hidden" value="Enrollment Number">
                  <input class="form-control" id="enrollmentlocal" name="enrollmentlocal" readonly="readonly" type="hidden" value="">
                  <button class="btn btn-primary" type="submit" name="savedata">PDF Download</button>
               </div>
            </div>
         </form>
      </div>
   </div>
</div>

<!-- End Aadhaar Details Fetch Success -->
</div>
</div>
    <?php } ?>
 <script>
  document.getElementById('myForm').addEventListener('submit', function() {
    // After submitting the form, wait for 10 seconds and then redirect the page
    setTimeout(function() {
      window.location.href = "aadhar-print-record";
    }, 7000); // 10000 milliseconds = 10 seconds
  });
</script>

<script>
  // Function to close the modal
  function closeModal() {
    $('#aadharDownloadModal').modal('hide');
  }

  // Function to set a cookie to track whether the user has seen the modal
  function setModalSeenCookie() {
    document.cookie = "aadharDownloadModalSeen=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
  }

  // Function to check if the modal has been seen
  function isModalSeen() {
    return document.cookie.indexOf("aadharDownloadModalSeen=true") !== -1;
  }

  // Event listener when modal is hidden
  $('#aadharDownloadModal').on('hidden.bs.modal', function () {
    setModalSeenCookie();
  });

  // Check if the modal has been seen, if not, show it
  if (!isModalSeen()) {
    $(document).ready(function () {
      $('#aadharDownloadModal').modal('show');
    });
  }

  // Event listener for the "Next" button click
  $('#modalHorizontalCarouselControls .carousel-control-next').on('click', function () {
    // Check if it's the last slide
    if ($('#modalHorizontalCarouselControls .carousel-inner .carousel-item:last').hasClass('active')) {
      closeModal();
    }
  });
</script>
<script type="text/javascript">
$('#language').on('change',function(){
if($(this).val() != '' && $(this).val() == 'OR'){
		var langs = $(this).val();
		var lang = langs.toLowerCase();
        var name = $("#name").val();
        var address = $("#txtSource").val();
        $.post("<?php echo "http://" . $_SERVER['SERVER_NAME'].'/admin/';?>test",{lang:lang,name:name,address:address}).done(function (data) {
        $("[name='namelocal']").val(json.name.replace(/"/g,''));
        $("[name='addresslocal']").val(json.address.replace(/"/g,''));
        })
        var dob = $("#birthtithi").val();
if($(this).val() == 'HI' &&  $("#gender").val() =='Male'){
  var gender = $("#gender").val('पुरुष');
}else {
  var gender = $("#gender").val();
}
$.post("<?php echo "http://" . $_SERVER['SERVER_NAME'].'/admin/';?>test",{lang:lang,name:dob,address:gender}).done(function (data) {
$("[name='birthtithilocal']").val(json.name.replace(/"/g,''));
$("[name='genderlocal']").val(json.address.replace(/"/g,''));
})
    
}else{
changelang();   
}
});

</script> 
<script type="text/javascript">
    function changelang() {
            var lang = document.getElementById("language").value;
            var url = "https://translate.googleapis.com/translate_a/single?client=gtx";
            url += "&sl=" + 'EN';
            url += "&tl=" + lang;
            url += "&dt=t&q=" + escape($("#txtSource").val());
            $.get(url, function (data, status) {
                var result= '';
                for(var i=0; i<=500; i++){
			      result += data[0][i][0];
			      $("#txtTarget").val(result);
			      }
            });	



            url = "https://translate.googleapis.com/translate_a/single?client=gtx";
            url += "&sl=" + 'EN';
            url += "&tl=" + lang;
            url += "&dt=t&q=" + escape($("#name").val());
            $.get(url, function (data, status) {
			 var result= '';
			  for(var i=0; i<=500; i++){
			      result += data[0][i][0];
			      $("#name_regional").val(result);
			      }
            });	
            
            var gen = $("#gender").val();
            url ="https://translate.googleapis.com/translate_a/single?client=gtx";
            url += "&sl=" + 'EN';
            url += "&tl=" + lang;
            url += "&dt=t&q=" + escape(gen.toLowerCase());
            $.get(url, function (data, status) {
			 var result= '';
			  for(var i=0; i<=500; i++){
			      result += data[0][i][0];
			      
            if(result == 'नर'){
                result = 'पुरुष';
            }
              $("#genderlocal").val(result);
            }
            });


            url = "https://translate.googleapis.com/translate_a/single?client=gtx";
            url += "&sl=" + 'EN';
            url += "&tl=" + lang;
            url += "&dt=t&q=" + escape($("#enrollment").val());
            $.get(url, function (data, status) {
			 var result= '';
			  for(var i=0; i<=500; i++){
			      result += data[0][i][0];
			      $("#enrollmentlocal").val(result);
			    }
            });


            url = "https://translate.googleapis.com/translate_a/single?client=gtx";
            url += "&sl=" + 'EN';
            url += "&tl=" + lang;
            url += "&dt=t&q=" + escape($("#birthtithi").val());
            $.get(url, function (data, status) {
			 var result= '';
			  for(var i=0; i<=500; i++){
			      result += data[0][i][0];
			      $("#birthtithilocal").val(result);
			    }
            });


            url = "https://translate.googleapis.com/translate_a/single?client=gtx";
            url += "&sl=" + 'EN';
            url += "&tl=" + lang;
            url += "&dt=t&q=" + escape($("#pata").val());
            $.get(url, function (data, status) {
			 var result= '';
			  for(var i=0; i<=500; i++){
			      result += data[0][i][0];
				  $("#patalocal").val(result);
				  
			    }
            });
		};	
</script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.js"></script> 

<script>
$("#eno").mask('9999/99999/999999');
$(document).ready(function() {
        $('#payL').modal({
            backdrop: 'static',
            keyboard: false
        });
    });
</script>

<script type="text/javascript">
   $('#basic-addon-search32').removeClass('d-none');
   const d = [
      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
      [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
      [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
      [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
      [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
      [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
      [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
      [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
      [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
      [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
   ];

   const p = [
      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
      [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],
      [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
      [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],
      [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],
      [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
      [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],
      [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]
   ];

   function validate(aadharNumber) {
      let c = 0;
      let invertedArray = aadharNumber.split('').map(Number).reverse();

      invertedArray.forEach((val, i) => {
         c = d[c][p[(i % 8)][val]];
      });

      return c === 0;
   }

   function verify() {
      var message = document.getElementById("message");
      var aadharNo = document.getElementById("txtUID").value;

      if (validate(aadharNo)) {
         $('#txtUID').removeClass('border border-primary');
         $('.uidai').removeClass('text-danger');
         $('#errors').removeClass('text-bg-danger');
         $('#basic-addon-search32').html(''); // Clear any previous error message
      } else {
         $('#basic-addon-search32').html('Please Enter Valid Aadhar Number');
         $('#errors').addClass('text-bg-danger');

      }
   }
</script>
<script>
   $(document).ready(function() {
      $("#capture").on('click', function() {
         var alen = $("#txtUID").val().length;

         // Reset previous error states
         $('#txtUID').removeClass('border border-primary');
         $('.uidai').removeClass('text-danger');
         $('#basic-addon-search32').html('');

         if ($("#txtUID").val() == '') {
            
            $('#txtUID').addClass('border border-primary');
            $('.uidai').addClass('text-danger');
            $('#errors').removeClass('text-bg-danger');
         } else if (alen != 12) {
            $('#basic-addon-search32').html('Please enter a proper 12-digit Aadhar number');
            $('#errors').addClass('text-bg-danger');
         } else {
            
               // Checkbox is checked, handle the logic here
               var hdnPIDData = $("#hdnPIDData");
               var ssoauth_ver = $.now();
               $('#scaning').removeClass('d-none');
               $('#ready').addClass('d-none');
               var data = {
                  p: 'http',
                  type: 'AUTH',
                  device: 'bio',
                  isHttpsService: 'true'
               };
               initCapture(data);

               function initCapture(d) {
                   $.getScript("https://<?php echo p4pointsapi('p4points_url'); ?>/api/v1/uid/printcapture.js?v=" + ssoauth_ver).done(function (script, textStatus) {
                       if (textStatus === "success") {
                           startCaptureRD({
                               authType: d.type,
                               fpDevice: d.device,
                               env: "P",
                               isHttpsService: d.isHttpsService
                           }, function (data) {
                               // Store the captured data
                               hdnPIDData.val(data.data);
               
                               // Handle specific errors
                               if (data.data === 'Error: Capture timed out (700)') {
                                   handleTimeout();
                               } else if (data.data === 'Error: Capture Stop (-2054)') {
                                   $('#scaning').addClass('d-none');
                                   $('#successcap').addClass('d-none');
                                   showError('There is a technical issue with your device. Please check your device and try again.');
                               } else if (data.data === 'Error: Device needs to be re-initialized (740)') {
                                   $('#scaning').addClass('d-none');
                                   $('#successcap').addClass('d-none');
                                   showError('The device needs to be re-initialized. Please disconnect and reconnect the device, then try again.');
                               } else if (data.data === 'Error: Device not initialized. (-2025)') {
                                   $('#scaning').addClass('d-none');
                                   $('#successcap').addClass('d-none');
                                   showError('The device needs to be re-initialized. Please disconnect and reconnect the device, then try again.');
                               } else if (data.data === 'Error: No Device Present (-1307)') {
                                   $('#scaning').addClass('d-none');
                                   $('#successcap').addClass('d-none');
                                   showError('No biometric device detected. Please connect a device and try again.');
                               } else {
                                   handleCaptureSuccess(data);
                               }
                           });
                       }
                   });
               }

               function showError(message) {
                   $('#timeout').removeClass('d-none');
                   $('#timeout p').html(`<b>${message}</b>`);
               }

               function handleTimeout() {
                  $('#scaning').addClass('d-none');
                  $('#ready').addClass('d-none');
                  $('#successcap').addClass('d-none');
                  $('#timeout').removeClass('d-none');

                  // Redirect after 5 seconds
                  setTimeout(function() {
                     $('#ready').removeClass('d-none');
                     $('#timeout').addClass('d-none');
                  }, 5000);
               }

               function handleCaptureSuccess(data) {
                  $("#biodata").val(data.data);
                  $("#aadhar").val($("#txtUID").val());
                  var otp = $("#txtOTP").val();
                  $("#session_otp").val(otp);

                  $('#scaning').addClass('d-none');
                  $('#ready').addClass('d-none');
                  $('#successcap').removeClass('d-none');
                  document.f1.submit();
               }

               $('#basic-addon-search32').html('');
               $('#errors').removeClass('text-bg-danger');
            
         }
      });
   });
</script>
<script type="text/javascript">
   var txtUID, txtConfirmUID;
   var btnProceed;
   var lblMessage;
   var oData;
   var btnSentOTP;
   var txtVerifyOTP;
   var btnVerifyOTP;
   var oLocalProfile;
   var btnSave;
   var hdnFinalData;
   var IsFreshUID;
   var txtMobile;
   var sValue, cValue;

   var hdnServerMessage, hdnShowServerMessage;
   var txtDOB, txtConfirmDOB;
   var txtSamagraID;
   $(document).ready(function() {
      txtSamagraID = $('#txtSamagraID');
      txtDOB = $('#txtDOB');
      txtConfirmDOB = $('#txtConfirmDOB');

      btnSentOTP = $('#btnSentOTP');
      btnProceed = $('#btnProceed');
      lblMessage = $('#lblMessage');
      btnVerifyOTP = $("#btnVerifyOTP");

      txtMobile = $('#txtMobile');
      btnSave = $('#btnSave');
      hdnFinalData = $('#hdnFinalData');

      hdnServerMessage = $('#hdnServerMessage');
      hdnShowServerMessage = $('#hdnShowServerMessage');

      txtUID = $('#txtUID');
      txtConfirmUID = $('#txtConfirmUID');
      txtVerifyOTP = $('#txtVerifyOTP');

      txtDOB.mask('99-99-9999');
      txtConfirmDOB.mask('99-99-9999');

      txtConfirmUID.blur(function() {

      });
      
      txtSamagraID.blur(function() {
         if (txtSamagraID.val().length == 9) {
            Get_Samagra_Details(txtSamagraID.val());
         } else {
            $("#dvSamagraDetails").html('');
            $("#dvSamagraDetails").fadeOut(100);
         }
      });

   });
</script>
<script>
  // RD Service Check Script
  $(document).ready(function () {
    var notPlginDiv = $('#notplgin');
    var readyDiv = $('#ready');
    var notReadyDiv = $('#notready');

    var executeFlag = true;
    var intervalId = null;

    // Generate all base URLs for ports 11100 to 11120
    var customBaseUrls = [];
    for (let port = 11100; port <= 11120; port++) {
      customBaseUrls.push(
        `http://127.0.0.1:${port}`,
        `https://127.0.0.1:${port}`,
        `https://localhost:${port}`
      );
    }

    function executeButtonClick() {
      if (!executeFlag) {
        clearInterval(intervalId);
        return;
      }

      var pidoptions = "<PidOptions> <Opts fCount=\"1\" fType=\"0\" iCount=\"0\" pCount=\"0\" format=\"0\" pidVer=\"2.0\" timeout=\"20000\" otp=\"\" posh=\"LEFT_INDEX\" env=\"P\" wadh='E0jzJ/P8UopUHAieZn8CKqS4WPMi5ZSYXgfnlfkWjrc=' /> <Demo></Demo>  </PidOptions>";

      customBaseUrls.forEach(function (rdsURL) {
        $.support.cors = true;

        $.ajax({
          type: "RDSERVICE",
          async: true,
          crossDomain: true,
          url: rdsURL,
          data: pidoptions,
          contentType: "text/xml; charset=utf-8",
          processData: false,
          dataType: "text",
          timeout: 2000,

          success: function (data) {
            var parser = new DOMParser();
            var xmlDoc = parser.parseFromString(data, "text/xml");
            var status = xmlDoc.querySelector("RDService")?.getAttribute("status");

            if (status === "READY") {
              executeFlag = false;
              clearInterval(intervalId);
              notPlginDiv.html('');
              readyDiv.removeClass('d-none');
              notReadyDiv.addClass('d-none');
            } else if (status === "NOTREADY") {
              notReadyDiv.removeClass('d-none');
            }
          },
          error: function () {
            notPlginDiv.removeClass('d-none');
          }
        });
      });
    }

    // Start checking every 3 seconds
    intervalId = setInterval(executeButtonClick, 3000);
  });
</script>

<?php
} else {
    require_once("404.php");
}
} else {
      awal_alert_msg('You Do Not Have Any Aadhaar Service Active!', 'info', 'dashboard');
}
require_once("../layouts/members/foot.php");
?>