<?php
require_once("../layouts/members/head.php");
 if ($user_data['aadhar_manual_service'] == "YES") { 
if (in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])) {
  $getresult = true;
?>
<?php
if (isset($_POST['savedata'])) {
    $order_id = order_txn_id();
    $amount = $user_data['aadhar_manual_print_fee'];
    $old_balance = $user_data['balance'];
    $new_balance = $old_balance - $amount;
    
if ($old_balance >= $amount) {
    
$base64Image = null;
if (isset($_FILES['imageInput']) && $_FILES['imageInput']['error'] === UPLOAD_ERR_OK) {
    $imageFile = $_FILES['imageInput']['tmp_name'];
    $imageType = mime_content_type($imageFile);
    $allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/webp'];
    if (in_array($imageType, $allowedTypes)) {
        $imageData = file_get_contents($imageFile);
        $base64Image = 'data:' . $imageType . ';base64,' . base64_encode($imageData);
    } else {
        alert_msg("Please upload a valid image (JPG, JPEG, or PNG).", 'danger');
    }
} else {
    alert_msg("Image upload failed. Please try again.", 'danger');
}
    $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 = $base64Image;
    $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'] ?? '.';
    
    $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 MANUAL",
         'type'          => "Debit",
         'account_number'=> $aadharno,
         'app_type'      => "AADHAAR MANUAL",
         'amount'        => $amount,
         'main_amount'   => $amount,
         'old_balance'   => $old_balance,
         'new_balance'   => $new_balance,
         'txn_id'        => $order_id,
         'ref_id'        => $aadharno,
         'description'   => "Rs.{$amount} Has Been Debit From Wallet for Name {$name} for AADHAAR MANUAL By UID ",
         'date_time'     => current_timestamp(),
         'status'        => "Success"
     ];

     $insertIds = db_insert("reports", $insData);
     if ($insertIds) {
         //successful insert in records
      } else {
          awal_alert_msg("Insert Server Error!", 'error');
      }
    
    $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,
        'imgdata' => $imgdata,
        'ddate' => $ddate,
        'namelocal' => $namelocal,
        'birthtithilocal' => $birthtithilocal,
        'gender' => $gender,
        'birthtithi' => $birthtithi,
        'pata' => $pata,
        'patalocal' => $patalocal,
        'genderlocal' => $genderlocal,
        'addresslocal' => $addresslocal
    );

    $Mremark = 'Name: ' . $name . " - Aadhar Number: " . $aadharno;
    $insData = [
        'order_id'      => $order_id,
        'username'      => $user_data['username'],
        'name'          => $name,
        'idNumber'      => $aadharno,
        'service'       => "Aadhar Manual",
        '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("Aadhaar Download Successful from '.$Mremark.'.", 'success');
        redirect('printRecord', 3000);
    } else {
         awal_alert_msg("Saving Data Error!", 'error');
     }
} else {
    awal_alert_msg("Balance debited from wallet but not updated in the database. Please contact support!", 'error');
}
} else {
   awal_alert_msg("Insufficient Wallet Balance!", 'error');
} 

}
?>

<div class="container-xxl flex-grow-1 container-p-y">
    <div class="row">
        <div class="col-lg-5">
            <div class="card border">
                <div class="card-header text-white bg-primary">
                    <h6 class="mb-0">Aadhaar Details in English</h6>
                </div><form method="post" action="" id="myForm" enctype="multipart/form-data">
                <div class="card-body">
                        <div class="mb-3">
                            <label for="aadharno" class="form-label">Aadhaar Number:</label>
                            <input type="text" class="form-control" id="aadharno" name="aadharno" maxlength="12" placeholder="9656****6545" autocomplete="off" required>
                        </div>
                        <div class="mb-3">
                            <label for="name" class="form-label">Aadhaar Name:</label>
                            <input type="text" class="form-control" name="name" id="name" placeholder="Enter Name" autocomplete="off" required>
                        </div>
                        <div class="mb-3">
                           <label for="gender" class="form-label">Select Gender:</label>
                           <select class="form-control" id="gender" name="gender" required>
                               <option value="">Select Gender</option>
                               <option value="Male">Male</option>
                               <option value="Female">Female</option>
                               <option value="Transgender">Transgender</option>
                           </select>
                        </div>
                        <div class="mb-3">
                            <label for="dobadhar" class="form-label">Date of Birth:</label>
                            <input class="form-control" name="username" type="hidden" value="<?= isset($userdata['username']) ? time() : ''; ?>" required>
                            <input class="form-control" name="dobadhar" id="dob" type="text" value="" placeholder="01/01/2000" autocomplete="off" required>
                            <input class="form-control" name="houseno" type="hidden" value="">
                            <input class="form-control" name="street" type="hidden" value="">
                            <input class="form-control" name="pincode" type="hidden" value="">
                            <input class="form-control" name="vtcandpost" type="hidden" value="">
                            <input class="form-control" name="dist" type="hidden" value="">
                            <input class="form-control" name="statename" 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="">
                            <?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 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="">
                        </div>
                        <div class="mb-3">
                            <label for="address" class="form-label">Full Address:</label>
                            <textarea class="form-control" id="txtSource" name="address" placeholder="S/O: HKB Singh, Address: Village Balua , Post: Sindhu , Block: Riga, District: Tamil, State: Tamil Nadu, Pincode: 110001" rows="3" style="resize: none;" required></textarea>
                        </div>
                </div>
            </div>
        </div>
        <div class="col-lg-5">
            <div class="card border">
                <div class="card-header text-white bg-primary">
                    <h6 class="mb-0">Aadhaar Details in Regional</h6>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="language" class="form-label">Select Language:</label>
                        <select class="form-control" id="language" name="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="mb-3">
                        <label for="namelocal" class="form-label">Name (Regional):</label>
                        <input type="text" class="form-control" id="name_regional" name="namelocal" autocomplete="off" placeholder="Auto fetched when Language Select" required>
                    </div>
                    <div class="mb-3">
                        <label for="genderlocal" class="form-label">Gender (Regional):</label>
                        <input type="text" class="form-control" name="genderlocal" id="genderlocal" autocomplete="off" placeholder="Auto fetched when Language Select" required>
                    </div>
                    <div class="mb-3">
                        <label for="birthtithilocal" class="form-label">DOB (Regional):</label>
                        <input class="mng_cp form-control" id="birthtithilocal" name="birthtithilocal" autocomplete="off" type="text" placeholder="Auto fetched when Language Select" required>
                    </div>
                    <div class="mb-3">
                        <label for="addresslocal" class="form-label">Full Address (Regional):</label>
                        <textarea type="text" id="txtTarget" class="form-control" name="addresslocal" placeholder="Auto fetched when Language Select" rows="3" required></textarea>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-2">
            <div class="card border">
                <div class="card-header text-white bg-primary">
                    <h6 class="mb-0 text-center">Photo</h6>
                </div>
                <div class="card-body text-center">
                    <div style="width: 150px; height: 150px; border: 1px solid #ccc; display: flex; align-items: center; justify-content: center; margin: auto;">
                        <img id="imagePreview" src="" alt="Selected Image" style="max-width: 100%; max-height: 100%; display: none;">
                    </div>
                    <input type="file" class="form-control mt-3" id="imageInput" name="imageInput" accept="image/*" onchange="previewImage()" required>
                    <small id="errorMessage" class="text-danger" style="display: none;">Please select a valid image file (JPG, PNG, or GIF).</small>
                    <hr>
                    <button class="btn btn-primary" type="submit" name="savedata">Submit / <small><i class="fas fa-inr"></i></small> <?php echo isset($user_data['aadhar_manual_print_fee']) ? $user_data['aadhar_manual_print_fee'] : '0'; ?></button>
                </div>
            </div>
        </div>
     </form>
    </div>
</div>
<script>
  flatpickr("#dob", {
    dateFormat: "d/m/Y", 
    allowInput: true,   
    maxDate: "today",  
    onChange: function(selectedDates, dateStr, instance) {
      console.log("Selected date:", dateStr); 
    }
  });
</script>
<script>
  function closeModal() {
    $('#aadharDownloadModal').modal('hide');
  }
  function setModalSeenCookie() {
    document.cookie = "aadharDownloadModalSeen=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
  }
  function isModalSeen() {
    return document.cookie.indexOf("aadharDownloadModalSeen=true") !== -1;
  }
  $('#aadharDownloadModal').on('hidden.bs.modal', function () {
    setModalSeenCookie();
  });
  if (!isModalSeen()) {
    $(document).ready(function () {
      $('#aadharDownloadModal').modal('show');
    });
  }
  $('#modalHorizontalCarouselControls .carousel-control-next').on('click', function () {
    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 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>
function previewImage() {
    const input = document.getElementById('imageInput');
    const preview = document.getElementById('imagePreview');
    const errorMessage = document.getElementById('errorMessage');
    const file = input.files[0];
    if (file) {
        const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];
        if (allowedTypes.includes(file.type)) {
            const reader = new FileReader();
            reader.onload = function (e) {
                preview.src = e.target.result;
                preview.style.display = 'block';
                errorMessage.style.display = 'none'; 
            };
            reader.readAsDataURL(file);
        } else {
            errorMessage.textContent = 'Please upload a valid image (JPG, JPEG, or PNG).';
            errorMessage.style.display = 'block';
            input.value = ''; 
            preview.src = '';
            preview.style.display = 'none';
        }
    } else {
        preview.src = '';
        preview.style.display = 'none';
        errorMessage.style.display = 'none';
    }
}
</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");
?>