<?php
require_once("../layouts/members/head.php");
if ($user_data['janaadhar_member_details_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">
            <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'])) {
              $janaadharNumber = strtoupper(trim($_POST['janaadharNumber']));

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

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

                      $responseApi = janaadharMember_details_find_run($request);
                      $response = json_decode($responseApi, true) ?? '';
                      $data = isset($response['data']) && is_array($response['data']) ? $response['data'] : [];
                      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'       => "JANAADHAAR MEMBER FIND",
                                  'type'          => "Debit",
                                  'account_number'=> $data[0]['name'],
                                  'app_type'      => "JANAADHAAR MEMBER FIND",
                                  'amount'        => $amount,
                                  'main_amount'   => $amount,
                                  'old_balance'   => $old_balance,
                                  'new_balance'   => $new_balance,
                                  'txn_id'        => $order_id,
                                  'ref_id'        => $data[0]['name'],
                                  'description'   => "Rs.{$amount} Has Been Debit From Wallet for Name {$data[0]['name']} JanAadhar {$janaadharNumber} to Details Searching has been Complete.",
                                  'date_time'     => current_timestamp(),
                                  'status'        => "Success"
                              ];

                              $insertId = db_insert("reports", $insData);
                              if ($insertId) {
                                  $fields = [
                                      'name'       => 'Name',
                                      'father'     => 'Father',
                                      'dob'        => 'DOB',
                                      'gender'     => 'Gender',
                                      'jan_aadhar' => 'JanAadhaar No',
                                      'memberType' => 'memberType',
                                  ];

                                  $whamessage = "Dear {$user_data['name']},\nYour Request for Name *{$data[0]['name']}* JanAaadhar Member Verification Searching has been Complete.\n\n";
                                  foreach ($fields as $key => $label) {
                                      if (!empty($data[0][$key]) && isset($data[0][$key])) {
                                          $whamessage .= "*$label*: {$data[0][$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>JanAadhar Number</label>
              <input type="number" name="janaadharNumber" placeholder="Enter JanAadhar Number" class="form-control" required oninput="this.setCustomValidity(this.value.length < 4 ? 'Value must be greater than 4 digits' : ''); this.reportValidity();" min="1000" max="99999999999999999999">
            </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['janaadhar_member_details_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-12 mt-4">
  <div class="card text-danger">
    <div class="card-header bg-primary text-white py-2">
      <span class="mr-auto"><?php echo $response['message'] ?? 'Search List'; ?></span>
    </div>
    <div class="table-responsive">
      <table class="table table-bordered table-striped">
        <thead>
          <tr style="text-align: center;">
            <th>Sr. No.</th>
            <th>Name</th>
            <th>Jan Mem ID</th>
            <th>Dob</th>
            <th>Gender</th>
            <th>Father</th>
            <th>Jan Aadhaar Member</th>
            <th>Jan Aadhar</th>
            <th>Enr Id</th>
            <th>Nfsa Status</th>
            <th>Mobile</th>
            <th>Aadhaar Ref No</th>
            <th>Member Type</th>
          </tr>
        </thead>
        <tbody>
          <?php 
          $srNo = 1; // Initialize serial number
          foreach ($data as $datas) { ?>
            <tr style="text-align: center;">
              <td><?= $srNo++; ?></td> <!-- Increment serial number -->
              <td><?= $datas['name'] ?? 'NA'; ?></td>
              <td><?= $datas['jan_member_id'] ?? 'NA'; ?></td>
              <td><?= $datas['dob'] ?? 'NA'; ?></td>
              <td><?= $datas['gender'] ?? 'NA'; ?></td>
              <td><?= $datas['father'] ?? 'NA'; ?></td>
              <td><?= $datas['janaadhaarmemid'] ?? 'NA'; ?></td>
              <td><?= $datas['jan_aadhar'] ?? 'NA'; ?></td>
              <td><?= $datas['enr_id'] ?? 'NA'; ?></td>
              <td><?= $datas['nfsa_status'] ?? 'NA'; ?></td>
              <td><?= $datas['mobile'] ?? 'NA'; ?></td>
              <td><?= $datas['aadhar_ref_no'] ?? 'NA'; ?></td>
              <td><?= $datas['memberType'] ?? 'NA'; ?></td>
            </tr>
          <?php } ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

    <?php } ?>
</div>
<script>
  flatpickr("#dob", {
    dateFormat: "d-m-Y", 
    allowInput: true,   
    maxDate: "today",  
    onChange: function(selectedDates, dateStr, instance) {
      console.log("Selected date:", dateStr); 
    }
  });
</script>
<?php
} else {
    require_once("404.php");
}

} else {
    awal_alert_msg('You Do Not Have Ration 2 UID Find Service Active!', 'info', 'dashboard');
}
require_once("../layouts/members/foot.php");
?>
