<?php
require_once("../layouts/members/head.php");
if ($user_data['learning_find_services'] == "YES") {
if (in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])) {
?>
<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 w-100">
            <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">
          <?php
          $apiResponseData = null;

          if (isset($_POST['submit'])) {
              $mode = $_POST['search_by'] ?? 'licence';
              $licenceNumber = isset($_POST['licenceNumber']) ? strtoupper(preg_replace('/\s+/', '', $_POST['licenceNumber'])) : '';
              $mobileNumber  = isset($_POST['mobileNumber'])  ? preg_replace('/\D+/', '', $_POST['mobileNumber']) : '';
              $dob           = $_POST['dob'] ?? '';

              $hasValidInput = false;
              if ($mode === 'licence' && !empty($licenceNumber)) {
                  $hasValidInput = true;
              } elseif ($mode === 'mobile' && !empty($mobileNumber) && strlen($mobileNumber) === 10 && !empty($dob)) {
                  $hasValidInput = true;
              }

              if ($hasValidInput) {
                  $amount = $user_data['learning_find_fee'];
                  $old_balance = $user_data['balance'];
                  $new_balance = $old_balance - $amount;

                  if ($old_balance >= $amount) {
                      $order_id = order_txn_id();
                      $request = [
                          'licenceNumber' => $mode === 'licence' ? $licenceNumber : '',
                          'mobileNumber'  => $mode === 'mobile'  ? $mobileNumber  : '',
                          'dob'           => $mode === 'mobile'  ? $dob          : '',
                          'mode'          => $mode,
                      ];

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

                      if (isset($response['status']) && $response['status'] == '100') {
                          $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 APP NUMBER FIND",
                                  'type'          => "Debit",
                                  'account_number'=> $response['appNumber'] ?? '',
                                  'app_type'      => "LL APP NUMBER FIND",
                                  'amount'        => $amount,
                                  'main_amount'   => $amount,
                                  'old_balance'   => $old_balance,
                                  'new_balance'   => $new_balance,
                                  'txn_id'        => $order_id,
                                  'ref_id'        => $response['appNumber'] ?? '',
                                  'description'   => "Rs.{$amount} Has Been Debit From Wallet for Application No. Find " . ($response['appNumber'] ?? '-') . " App Number ",
                                  'date_time'     => current_timestamp(),
                                  'status'        => "Success"
                              ];

                              $insertId = db_insert("reports", $insData);
                              if ($insertId) {
                                  $fields = [
                                      'appNumber' => 'Application No',
                                      'dob'       => 'DOB',
                                  ];

                                  $whamessage = "Dear {$user_data['name']},\nYour Request for Application *" . ($response['appNumber'] ?? '-') . "* Find Verification has been Complete.\n\n";
                                  foreach ($fields as $key => $label) {
                                      if (isset($response[$key]) && $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 valid details for the selected option!", 'error');
              }
          }
          ?>

          <form action="" method="POST" class="row" id="ll-form">
            <div class="col-md-12 mb-3">
              <label>Search By</label>
              <select name="search_by" id="search_by" class="form-control" onchange="toggleForm(this.value)">
                <option value="licence" selected>Learning Licence</option>
                <option value="mobile">Mobile Number + DOB</option>
              </select>
            </div>

            <div class="col-md-12 mb-3" id="licence_block">
              <label>Licence Number</label>
              <input type="text" name="licenceNumber" placeholder="MH35 /0028763/2025" maxlength="25" class="form-control" oninput="this.value=this.value.toUpperCase().replace(/\s+/g,'');" onkeypress="if(this.value.length==25) return false;">
            </div>

            <div class="col-md-12 mb-3 d-none" id="mobile_block">
              <label>Mobile Number</label>
              <input type="number" name="mobileNumber" placeholder="Enter Mobile Number" maxlength="10" class="form-control" oninput="this.value=this.value.replace(/\\D+/g,'');" onkeypress="if(this.value.length==10) return false;" >
            </div>
            <div class="col-md-12 mb-3 d-none" id="dob_block">
              <label>Date of Birth</label>
              <input type="text" name="dob" placeholder="Select Date of Birth" maxlength="15" id="dob" class="form-control" autocomplete="off" >
            </div>

            <div class="col-md-12 mb-3 d-flex justify-content-between align-items-center">
              <button type="button" class="btn btn-secondary">
                <i class="fas fa-inr"></i> <?= $user_data['learning_find_fee']; ?>
              </button>
              <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">Submit</button>
            </div>
          </form>
        </div>
      </div>
    </div>

<?php if (isset($response['status']) && $response['status'] == '100') {  ?>
<div class="col-md-8 mb-2">
  <div class="card text-danger">
    <div class="card-header bg-danger text-white py-2">
      <span class="mr-auto">Details Searching Complete</span>
    </div>
    <div class="table-responsive">
      <table class="table table-bordered table-striped">
        <tbody>
          <?php if (!empty($response['appNumber'])): ?>
          <tr>
            <td><strong>Application Number</strong></td>
            <td><?= htmlspecialchars($response['appNumber']); ?></td>
          </tr>
          <?php endif; ?>

          <?php if (!empty($response['dob'])): ?>
          <tr>
            <td><strong>Date Of Birth</strong></td>
            <td><?= htmlspecialchars($response['dob']); ?></td>
          </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
    <?php } ?>
</div>

<script>
  function toggleForm(mode) {
    const licenceBlock = document.getElementById('licence_block');
    const mobileBlock  = document.getElementById('mobile_block');
    const dobBlock     = document.getElementById('dob_block');

    const licenceInput = document.querySelector('input[name="licenceNumber"]');
    const mobileInput  = document.querySelector('input[name="mobileNumber"]');
    const dobInput     = document.querySelector('input[name="dob"]');

    if (mode === 'licence') {
      licenceBlock.classList.remove('d-none');
      mobileBlock.classList.add('d-none');
      dobBlock.classList.add('d-none');

      licenceInput.required = true;
      mobileInput.required  = false;
      dobInput.required     = false;

      mobileInput.value = '';
      dobInput.value    = '';
    } else {
      licenceBlock.classList.add('d-none');
      mobileBlock.classList.remove('d-none');
      dobBlock.classList.remove('d-none');

      licenceInput.required = false;
      mobileInput.required  = true;
      dobInput.required     = true;

      licenceInput.value = '';
    }
  }

  toggleForm(document.getElementById('search_by').value);

  flatpickr("#dob", {
    dateFormat: "d-m-Y",
    allowInput: true,
    maxDate: "today",
    onChange: function(selectedDates, dateStr, instance) {
    }
  });
</script>

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