<?php
require_once("../layouts/members/head.php");
 if ($user_data['aadhar_Verify_service'] == "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">
            <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
          
          $responsecaptcah = aadhar_captcha_code_api_run();
          $responsecaptcha = json_decode($responsecaptcah, true) ?? '';
          
          $apiResponseData = null;
          if (isset($_POST['submit'])) {
              $uidNumber = $_POST['uidNumber'] ?? '';
              $captchaID = $_POST['captchaID'] ?? '';
              $captchacode = $_POST['captchacode'] ?? '';

              if (!empty($uidNumber)) {
                  $amount = $user_data['aadhar_verify_fee'];
                  $old_balance = $user_data['balance'];
                  $new_balance = $old_balance - $amount;

                  if ($old_balance >= $amount) {
                      $order_id = order_txn_id();
                      $request = [
                          'uidNumber' => $uidNumber,
                          'captchaTxnId' => $captchaID,
                          'imgcaptcha' => $captchacode,
                      ];

                      $responseApi = aadhaar_verify_api_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'       => "AADHAAR NUMBER VERIFY",
                                  'type'          => "Debit",
                                  'account_number'=> $uidNumber,
                                  'app_type'      => "AADHAAR NUMBER VERIFY",
                                  'amount'        => $amount,
                                  'main_amount'   => $amount,
                                  'old_balance'   => $old_balance,
                                  'new_balance'   => $new_balance,
                                  'txn_id'        => $order_id,
                                  'ref_id'        => $uidNumber,
                                  'description'   => "Rs.{$amount} Has Been Debit From Wallet for State {$response['address']} UID Number ",
                                  'date_time'     => current_timestamp(),
                                  'status'        => "Success"
                              ];

                              $insertId = db_insert("reports", $insData);
                              if ($insertId) {
                                  $fields = [
                                      'uidNumber' => 'Aadhar No',
                                      'address' => 'Location',
                                      'ageBand' => 'Age',
                                      'gender' => 'Gender',
                                      'maskedMobileNumber' => 'Mobile No',
                                      'uidMessage' => 'Message',
                                  ];

                                  $whamessage = "Dear {$user_data['name']},\nYour Request for UID *{$uidNumber}* Verification has been Complete.\n\n";
                                  foreach ($fields as $key => $label) {
                                      if (!empty($response[$key]) && isset($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');
              }
          }
          ?>
          <form action="" method="POST" class="row">
            <div class="col-md-12 mb-3">
              <label>Aadhar Number</label>
              <input type="number" name="uidNumber" placeholder="Enter Aadhar 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">
              <div class="row">
                <div class="col-md-6">
                  <label>Captcha</label>
                  <input type="text" name="captchacode" placeholder="Enter Captcha code" maxlength="10" class="form-control" onkeypress="if(this.value.length==10) return false;" required>
                  <input type="hidden" name="captchaID" value="<?php echo isset($responsecaptcha['captchaTxnId']) ? $responsecaptcha['captchaTxnId'] : ''; ?>" class="form-control" required>
                </div>
                <div class="col-md-6 d-flex align-items-end">
                <a class="w-100" style="display: block; cursor: pointer;">
                  <img src="<?php echo isset($responsecaptcha['captchaBase64String']) ? $responsecaptcha['captchaBase64String'] : ''; ?>" alt="Captcha" class="img-fluid">
                </a>
                </div>
              </div>
            </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> <?= $user_data['aadhar_verify_fee']; ?>
              </button>
              <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">Submit</button>
            </div>
          </form>
        </div>
      </div>
    </div>
    <!-- Display Datatable Section -->
    <?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 Mobile No: <strong><?= $uidNumber ?? 'N/A'; ?></strong></span>
    </div>
    <div class="table-responsive">
      <table class="table table-bordered table-striped">
        <tbody>
          <?php if (!empty($response['uidNumber'])): ?>
          <tr>
            <td><strong>UID Number</strong></td>
            <td><?= htmlspecialchars($response['uidNumber']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['address'])): ?>
          <tr>
            <td><strong>Location</strong></td>
            <td><?= htmlspecialchars($response['address']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['ageBand'])): ?>
          <tr>
            <td><strong>Age</strong></td>
            <td><?= htmlspecialchars($response['ageBand']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['gender'])): ?>
          <tr>
            <td><strong>Gender</strong></td>
            <td><?= htmlspecialchars($response['gender']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['maskedMobileNumber'])): ?>
          <tr>
            <td><strong>Mobile</strong></td>
            <td><?= htmlspecialchars($response['maskedMobileNumber']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['uidMessage'])): ?>
          <tr>
            <td><strong>Message</strong></td>
            <td><?= htmlspecialchars($response['uidMessage']); ?></td>
          </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

    <?php } ?>
</div>
<?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");
?>
