<?php
require_once("../layouts/members/head.php");
if ($user_data['eshram_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;
        $response = [];

        if (isset($_POST['submit'])) {
          $uidNumber = strtoupper($_POST['uidNumber']);

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

            if ($user_data['balance'] >= $amount) {
              $order_id = order_txn_id();
              $request = ['uidNumber' => $uidNumber];
              $responseApi = uid_to_instant_detilas_api_run($request);
              $response = json_decode($responseApi, true) ?? [];

              if (isset($response['status']) && $response['status'] == '100') {
                $data = $response['data'];

                $updateSuccess = db_update("members", ["balance" => $new_balance], " user_id='" . $user_data['user_id'] . "' ");

                if ($updateSuccess) {
                  $printData = [
                    'aadhar' => $data['aadhar'] ?? $uidNumber,
                    'name' => $data['name'] ?? 'NA',
                    'fathername' => $data['co'] ?? 'NA',
                    'uan' => $data['uan'] ?? 'NA',
                    'dob' => $data['dob'] ?? '',
                    'gender' => $data['gender'] ?? '',
                    'address' => $data['address'] ?? '',
                    'mobile' => $data['mobile'] ?? '',
                    'occupation' => $data['occupation'] ?? '',
                    'occupation_family' => $data['occupation_family'] ?? '',
                    'image' => $data['image'] ?? '',
                    'username' => $user_data['username'],
                  ];
                  $name = $data['name'] ?? 'NA';
                  $uan_number = $data['uan'] ?? 'NA';

                  $Mremark = 'Name: ' . $name . " - UID Number: " . $uidNumber;
                  $insData = [
                    'order_id' => $order_id,
                    'username' => $user_data['username'],
                    'name' => $name,
                    'idNumber' => $uidNumber,
                    'service' => "e_Sharm_Verification",
                    'date_time' => current_timestamp(),
                    'printData' => base64_encode(str_replace("\\", "", json_encode($printData, JSON_UNESCAPED_UNICODE))),
                    'photo' => "",
                  ];
                  $insertIddata = db_insert("printRecords", $insData);

                  if ($insertIddata) {
                    $reportData = [
                      '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' => "e_Sharm_Verification",
                      'type' => "Debit",
                      'account_number' => $uan_number,
                      'app_type' => "e_Sharm_Verification",
                      'amount' => $amount,
                      'main_amount' => $amount,
                      'old_balance' => $old_balance,
                      'new_balance' => $new_balance,
                      'txn_id' => $order_id,
                      'ref_id' => $uan_number,
                      'description' => "Rs.{$amount} Has Been Debit From Wallet for e-Sharm Verification {$name} UAN Number ",
                      'date_time' => current_timestamp(),
                      'status' => "Success"
                    ];
                    $insertId = db_insert("reports", $reportData);

                    if ($insertId) {
                      $fields = [
                        'aadhar' => 'Uid No',
                        'name' => 'Name',
                        'dob' => 'Dob',
                        'gender' => 'Gender',
                        'uan' => 'UAN No',
                      ];

                      $whamessage = "Dear {$user_data['name']},\nYour Request for e-Sharm Card By *{$uidNumber}* has been Complete.\n\n";
                      foreach ($fields as $key => $label) {
                        if (!empty($data[$key])) {
                          $whamessage .= "*$label*: {$data[$key]}\n";
                        }
                      }
                      $whamessage .= "\nBest Regards,\n_*{$site_data['brand']}.*_";
                      send_sms($user_data['mobile'], $whamessage);

                      awal_alert_msg("Data Fetch Successful from '{$Mremark}'.", 'success');
                      redirect('printRecord', 3000);
                    }
                  }
                }
              } 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>Aadhaar Number</label>
            <input type="text" name="uidNumber" placeholder="Enter Aadhaar 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 d-flex justify-content-between">
            <button type="button" class="btn btn-secondary"><i class="fas fa-inr"></i> <?php echo $user_data['eshram_print_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 -->
<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">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['data']['name']) && !empty($response['data']['name'])): $data = $response['data']; ?>
        <form class="row">
          <div class="col-md-6 mb-3">
            <label>Name</label>
            <input type="text" value="<?= htmlspecialchars($data['name']) ?>" class="form-control" readonly>
          </div>
          <div class="col-md-6 mb-3">
            <label>Dob</label>
            <input type="text" value="<?= htmlspecialchars($data['dob']) ?>" class="form-control" readonly>
          </div>
          <div class="col-md-12 mb-3">
            <label>Address</label>
            <input type="text" value="<?= htmlspecialchars($data['address']) ?>" class="form-control" readonly>
          </div>
          <?php if (!empty($data['image'])): ?>
          <div class="col-md-12 text-center mb-3">
            <label>Photo</label><br>
            <img src="<?= $data['image']; ?>" alt="User Photo" style="max-width: 150px; border-radius: 8px; border: 1px solid #ccc;">
          </div>
          <?php endif; ?>
        </form>
        <?php else: ?>
          <p>No details fetched yet. Submit UID Number to get details.</p>
        <?php endif; ?>
      </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['data']['name']) && !empty($response['data']['name'])): ?>
  $(document).ready(function() {
    $('#showDetailsModal').modal('show');
  });
<?php endif; ?>
</script>

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