<?php
require_once("../layouts/members/head.php");

if ($user_data['npci_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
          $apiResponseData = null;
          $aadhaar = '';
          $response = [];

          if (isset($_POST['submit'])) {
              $aadhaar = is_valid_aadhaar($_POST['aadhaar']);

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

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

                      $responseApi = NpciLinkCheckStatus_api_run($request);
                      $response = json_decode($responseApi, true);

                      if (isset($response['code']) && $response['code'] == '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'       => "NPCI BANK LINK STATUS",
                                  'type'          => "Debit",
                                  'account_number'=> $aadhaar,
                                  'app_type'      => "NPCI BANK LINK STATUS",
                                  'amount'        => $amount,
                                  'main_amount'   => $amount,
                                  'old_balance'   => $old_balance,
                                  'new_balance'   => $new_balance,
                                  'txn_id'        => $order_id,
                                  'ref_id'        => $response['message'],
                                  'description'   => "Rs.{$amount} Has Been Debited From Wallet for Aadhaar {$aadhaar} UID to NPCI Link Status.",
                                  'date_time'     => current_timestamp(),
                                  'status'        => "Success"
                              ];

                              $insertId = db_insert("reports", $insData);

                              if ($insertId) {
                                  $whamessage = "Dear {$user_data['name']},\n" .
                                  "Aadhaar no: *{$aadhaar}*\n" .
                                  "Bank: *{$response['bankName']}*\n" .
                                  "Status: *{$response['message']}*\n" .
                                  "Updated: *{$response['lastupdatedate']}*\n\n" .
                                  "Best Regards,\n" .
                                  "_*{$site_data['brand']}*_";

                                  send_sms($user_data['mobile'], $whamessage);
                              } else {
                                  awal_alert_msg("Server Error! Report not inserted.", 'error');
                              }
                          } else {
                              awal_alert_msg("Balance debited but database update failed. Contact support!", 'error');
                          }
                      } else {
                          awal_alert_msg($response['error'] ?? "Unknown error occurred", 'error');
                      }
                  } else {
                      awal_alert_msg("Insufficient Wallet Balance!", 'error');
                  }
              } else {
                  awal_alert_msg("Please Enter a Valid Aadhaar Number!", 'error');
              }
          }
          ?>
          <form action="" method="POST" class="row">
            <div class="col-md-12 mb-3">
              <label>Aadhaar Number</label>
              <input type="number" name="aadhaar" placeholder="Enter Aadhaar Number" maxlength="12" 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['npci_link_status_fee'];?>
              </button>
              <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">Submit</button>
              <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#showDetailsModal">Show</button>
            </div>
          </form>
        </div>
      </div>
    </div>
</div>

<!-- Modal to show fetched details -->
<div class="modal fade" id="showDetailsModal" tabindex="-1" role="dialog" aria-labelledby="showDetailsModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="showDetailsModalLabel">Fetched Details</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <?php if (isset($response['message']) && !empty($response['message'])) { ?>
          <form class="row">
            <div class="col-md-6 mb-3">
              <label>Aadhaar Number</label>
              <input type="text" value="<?= htmlspecialchars($response['uidNumber'] ?? $aadhaar) ?>" class="form-control" readonly>
            </div>
            <div class="col-md-6 mb-3">
              <label>Bank Name</label>
              <input type="text" value="<?= htmlspecialchars($response['bankName'] ?? 'N/A') ?>" class="form-control" readonly>
            </div>
            <div class="col-md-12 mb-3">
              <label>Status</label>
              <input type="text" value="<?= htmlspecialchars($response['message']) ?>" class="form-control bg-green" readonly>
            </div>
            <div class="col-md-12 mb-3">
              <label>Last Updated</label>
              <input type="text" value="<?= htmlspecialchars($response['lastupdatedate'] ?? 'N/A') ?>" class="form-control" readonly>
            </div>
          </form>
        <?php } else { ?>
          <p>No details fetched yet. Submit Aadhaar to fetch details.</p>
        <?php } ?>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<script>
  <?php if (isset($response['message']) && !empty($response['message'])) { ?>
    $(document).ready(function() {
      $('#showDetailsModal').modal('show');
    });
  <?php } ?>
</script>

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