<?php
require_once("../layouts/members/head.php");
if ($user_data['aadhar_otp_service'] == "YES") {
if (in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])) {?>
          <?php
          $apiResponseData = null;
          if (isset($_POST['submit'])) {
              $uidNumber = strtoupper($_POST['uidNumber']);

              if (preg_match('/^\d{12}$/', $uidNumber)) {
                  $amount = $user_data['aadhar_otp_fee'];
                  $old_balance = $user_data['balance'];
                  $new_balance = $old_balance - $amount;

                  if ($user_data['balance'] >= $amount) {
                      $order_id = order_txn_id();
                      $request = [
                          'uidNumber' => $uidNumber,
                      ];

                      $responseApi = aadharOtp_Send_api_run($request);
                      $response = json_decode($responseApi, true) ?? '';

                      if (isset($response['status']) && $response['status'] == '100') {
                          alert_msg($response['message'], 'success', 0);
                      }else{
                          alert_msg($response['error'], 'danger');
                      }
                      } else {
                          awal_alert_msg("Insufficient Wallet Balance!", 'error');
                      }
                  } else {
                      awal_alert_msg("UID Number Incorrect!", 'error');
                  }
              }
              
          if (isset($_POST['submitotp'])) {
              $uidNumberResponse = strtoupper($_POST['uidNumberResponse']);
              $otp = strtoupper($_POST['otp']);
              $token = $_POST['token'] ?? '';

              if (!empty($uidNumberResponse) && !empty($otp) && !empty($token)) {
                  $amount = $user_data['aadhar_otp_fee'];
                  $old_balance = $user_data['balance'];
                  $new_balance = $old_balance - $amount;

                  if ($user_data['balance'] >= $amount) {
                      $order_id = order_txn_id();
                      $request = [
                          'uidNumber' => $uidNumberResponse,
                          'token' => $token,
                          'otp' => $otp,
                      ];

                      $responseApi = aadharOtp_Verify_api_run($request);
                      $response = json_decode($responseApi, true) ?? '';

                      if (isset($response['status']) && $response['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'       => "AADHAR_OTP_VERIFICATION",
                                  'type'          => "Debit",
                                  'account_number'=> $response['uid'],
                                  'app_type'      => "AADHAR_OTP_VERIFICATION",
                                  'amount'        => $amount,
                                  'main_amount'   => $amount,
                                  'old_balance'   => $old_balance,
                                  'new_balance'   => $new_balance,
                                  'txn_id'        => $order_id,
                                  'ref_id'        => $response['uid'],
                                  'description'   => "Rs.{$amount} Has Been Debit From Wallet for Name {$response['name']} Aadhar Number ",
                                  'date_time'     => current_timestamp(),
                                  'status'        => "Success"
                              ];

                              $insertId = db_insert("reports", $insData);
                              if ($insertId) {
                                 $fields = [
                                     'uid'    => 'Aadhar No',
                                     'name'   => 'Name',
                                     'fname'  => 'Father',
                                     'dob'    => 'Dob',
                                     'gender' => 'Gender',
                                     'address'=> 'Address',
                                 ];

                                 $whamessage = "Dear {$user_data['name']},\nYour Request for UID Number *{$uidNumberResponse}* Verification has been Complete.\n\n";

                                 foreach ($fields as $key => $label) {
                                     if (!empty($response[$key])) {
                                         $whamessage .= "*$label*: {$response[$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 {
                          awal_alert_msg($response['error'] ?? 'Server Down', 'error');
                      }
                  } else {
                      awal_alert_msg("Insufficient Wallet Balance!", 'error');
                  }
              } else {
                  awal_alert_msg("Please Fill All Valid Details!", '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'];
    $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_OTP",
        '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');
     }
}
          ?>
          
<?php if ((!isset($response['token']) || $response['token'] == '') && (!isset($response['name']) || trim($response['name']) == '')) { ?>
<div class="row">
    <div class="col-md-4 mb-2">
      <div class="card text-danger">
        <div class="card-header bg-primary text-white py-2">
          <div class="d-flex align-items-center">
            <span class="mr-auto"><?= file_name() ?></span>
             <button class="btn btn-dark btn-sm ml-auto" onclick="history.back()" > <i class="fas fa-arrow-left"></i> Back</button>
          </div>
        </div>
        <div class="p-3 text-dark">
          <form action="" method="POST" class="row">
            <div class="col-md-12 mb-3">
              <label>Aadhar Number</label>
              <input type="number" name="uidNumber" placeholder="Enter UID Number" maxlength="12" oninput="this.value = this.value.toUpperCase().replace(/\s+/g, '');" class="form-control" onkeypress="if(this.value.length==12) return false;" required>
            </div>
            <div class="col-md-12 mb-3 d-flex justify-content-between">
              <button type="button" class="btn btn-secondary" ><i class="fas fa-inr"></i> <?php echo $user_data['aadhar_otp_fee'];?></button>
              <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">Submit</button>
            </div>
          </form>
          
<?php } elseif (isset($response['token']) && $response['token'] != '' && (!isset($response['name']) || trim($response['name']) == '')) { ?>
<div class="row">
    <div class="col-md-4 mb-2">
      <div class="card text-danger">
        <div class="card-header bg-primary text-white py-2">
          <div class="d-flex align-items-center">
            <span class="mr-auto"><?= file_name() ?></span>
             <button class="btn btn-dark btn-sm ml-auto" onclick="history.back()" > <i class="fas fa-arrow-left"></i> Back</button>
          </div>
        </div>
        <div class="p-3 text-dark">
          <form action="" method="POST" class="row">
            <div class="col-md-12 mb-3">
              <label>Secret Code</label>
              <input type="number" name="otp" placeholder="Enter 6 Digit OTP" maxlength="6" class="form-control" onkeypress="if(this.value.length==6) return false;" required>
              <input type="hidden" name="token" value="<?php echo isset($response['token']) ? $response['token'] : ''; ?>" class="form-control" required>
              <input type="hidden" name="uidNumberResponse" value="<?php echo isset($response['uid']) ? $response['uid'] : ''; ?>" class="form-control" required>
            </div>
            <div class="col-md-12 mb-3 d-flex justify-content-between">
              <button type="button" class="btn btn-secondary" ><i class="fas fa-inr"></i> <?php echo $user_data['aadhar_otp_fee'];?></button>
              <button type="submit" name="submitotp" class="btn btn-primary" onclick="return confirm('Are you sure?');">Submit</button>
            </div>
          </form>
<?php } elseif (isset($response['name']) && trim($response['name']) != '') { ?>
<!-- Aadhaar Details Fetch Success -->
<div class="col-lg-12 m-auto p-t-10">
   <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($response['name']) ? $response['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($response['image']) ? $response['image'] : ''; ?>" 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($response['address']) ? $response['address'] : ''; ?>" required readonly>
               </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($response['uid']) ? $response['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($response['dob']) ? $response['dob'] : ''; ?>" required readonly>
                  <input class="form-control" name="houseno" type="hidden" value="<?= isset($response['house']) ? $response['house'] : ''; ?>">
                  <input class="form-control" name="street" type="hidden" value="<?= isset($response['street']) ? $response['street'] : ''; ?>">
                  <input class="form-control" name="pincode" type="hidden" value="<?= isset($response['pincode']) ? $response['pincode'] : ''; ?>">
                  <input class="form-control" name="vtcandpost" type="hidden" value="<?= isset($response['address']) ? $response['address'] : ''; ?>">
                  <input class="form-control" name="dist" type="hidden" value="<?= isset($response['dist']) ? $response['dist'] : ''; ?>">
                  <input class="form-control" name="statename" type="hidden" value="<?= isset($response['state']) ? $response['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($response['image']) ? $response['image'] : ''; ?>" 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($response['gender']) ? $response['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="">
                  <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 } ?>
</div>
</div>
</div>
</div>
<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>
<?php
} else {
    require_once("404.php");
}
} else {
      awal_alert_msg('You Do Not Have Any Aadhar Service Active!', 'info', 'dashboard');
}
require_once("../layouts/members/foot.php");
?>
