<?php
require_once("../layouts/members/head.php");
 if ($user_data['ll_service'] == "YES") { 
if (in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])) {
  $getresult = true;
?>
<?php
if (isset($_POST['submit'])) {
    $order_id = order_txn_id();
    $amount = $user_data['ll_apply_fee'];
    $old_balance = $user_data['balance'];
    $new_balance = $old_balance - $amount;
    
if ($old_balance >= $amount) {
    $applicationNumber = $_POST['applicationNumber'];
    $dob = $_POST['dob'];
    $password = $_POST['password'];
    $examsecretpin = $_POST['examsecretpin'] ?? '';
    $state = $_POST['state'];
    
  if (!empty($applicationNumber) && !empty($dob) && !empty($password) && !empty($state)) {
    $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'       => "LL REQUEST",
         'type'          => "Debit",
         'account_number'=> $applicationNumber,
         'app_type'      => "LL REQUEST",
         'amount'        => $amount,
         'main_amount'   => $amount,
         'old_balance'   => $old_balance,
         'new_balance'   => $new_balance,
         'txn_id'        => $order_id,
         'ref_id'        => $applicationNumber,
         'description'   => "Rs.{$amount} Has Been Debit From Wallet for LL TEST By Application Number",
         '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(
        'applicationNumber' => $applicationNumber,
        'dob' => $dob,
        'password' => $password,
        'examsecretpin' => $examsecretpin,
        'state' => $state,
        'order_id' => $order_id,
        'amount' => $amount,
        'username' => $user_data['username'],
    );

    $insData = [
        'order_id'      => $order_id,
        'username'      => $user_data['username'],
        'name'          => $applicationNumber,
        'idNumber'      => $applicationNumber,
        'service'       => "LL_Request",
        'date_time'     => current_timestamp(),
        'printData'     => base64_encode(str_replace("\\", "", json_encode($printData, JSON_UNESCAPED_UNICODE))),
        'photo'         => "",
        'status'         => "Pending",
    ];

    $insertId = db_insert("printRecords", $insData);
    
     $whamessage = "Dear Admin,\nYou have received a LL request Please update immediately.\n\n";
     $whamessage .= "Order ID: *$order_id*\nApplication: *$applicationNumber*\nDOB: $dob\nPassword: $password\nState: $state\n\n";
     $whamessage .= "Best Regards,\n_*{$site_data['brand']}*_";
     send_sms_credentials($site_data['mobile'], $whamessage);

    if ($insertId) {
         awal_alert_msg("Applied Successful", '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("Please Fill All Valid Details!", 'error');
}
} else {
   awal_alert_msg("Insufficient Wallet Balance!", 'error');
} 

}
?>
<style>
  .input-with-tooltip {
    position: relative;
  }

  .tooltip-icon {
    position: absolute;
    top: 50%;
    right: 10px;
    transform: translateY(-50%);
    color: orange;
    cursor: pointer;
    font-size: 18px;
  }

  .tooltip-icon::after {
    content: "Enter Pin, If you have applied LL in Non Aadhar Mode (Specially for State of Assam)";
    position: absolute;
    bottom: 100%;
    right: 0;
    background: #333;
    color: #fff;
    padding: 6px 10px;
    border-radius: 4px;
    font-size: 12px;
    display: none;
    z-index: 999;
    width: 250px; /* responsive width */
    white-space: normal;
    word-wrap: break-word;
  }

  .tooltip-icon:hover::after {
    display: block;
  }

  @media (max-width: 480px) {
    .tooltip-icon::after {
      width: 200px;
      font-size: 11px;
      right: auto;
      left: 0;
    }
  }
</style>
<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"><?= file_name() ?></h6>
                </div><form method="post" action="" id="myForm" enctype="multipart/form-data">
                <div class="card-body">
                        <div class="mb-3">
                            <label for="applicationNumber" class="form-label">Application Number:</label>
                            <input type="text" class="form-control" id="applicationNumber" name="applicationNumber" maxlength="42" placeholder="App****6545" autocomplete="off" required>
                        </div>
                        <div class="mb-3">
                            <label for="dob" class="form-label">Date Of Birth</label>
                            <input class="form-control" name="dob" id="dob" type="text" value="" placeholder="01/01/2000" autocomplete="off" required>
                        </div>
                        <div class="mb-3">
                            <label for="password" class="form-label">Password</label>
                            <input type="text" class="form-control" name="password" id="password" placeholder="Enter Password" autocomplete="off" required>
                        </div>
                        <div class="mb-3">
                          <label for="examsecretpin" class="form-label">Exam Pin <sup style="color:red;">Optional</sup></label>
                          <div class="input-with-tooltip">
                            <input type="number" class="form-control" name="examsecretpin" id="examsecretpin" placeholder="Enter Exam Pin" autocomplete="off">
                            <span class="tooltip-icon">⚠️</span>
                          </div>
                        </div>
                        <div class="mb-3">
                            <label for="state" class="form-label">Select State:</label>
                            <select class="form-control" id="state" name="state" required>
                                <option value="">Select State</option>
                            </select>
                        </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['ll_apply_fee'];?></button>
                          <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">Apply Data <i class="fas fa-check-circle"></i></button>
                        </div>
                </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>
  document.addEventListener("DOMContentLoaded", function () {
    const states = [
      "Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chhattisgarh",
      "Goa", "Gujarat", "Haryana", "Himachal Pradesh", "Jharkhand",
      "Karnataka", "Kerala", "Madhya Pradesh", "Maharashtra", "Manipur",
      "Meghalaya", "Mizoram", "Nagaland", "Odisha", "Punjab",
      "Rajasthan", "Sikkim", "Tamil Nadu", "Telangana", "Tripura",
      "Uttar Pradesh", "Uttarakhand", "West Bengal", "Andaman and Nicobar Islands",
      "Chandigarh", "Dadra and Nagar Haveli and Daman and Diu", "Delhi",
      "Jammu and Kashmir", "Ladakh", "Lakshadweep", "Puducherry"
    ];

    const stateSelect = document.getElementById("state");
    states.forEach(function(state) {
      const option = document.createElement("option");
      option.value = state;
      option.textContent = state;
      stateSelect.appendChild(option);
    });
  });
</script>


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