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

if (in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])) {
?>
<div class="row">
  <?php if ($user_data['pandetils_service'] == "YES") { ?>
    <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'])) {
              $panNumber = is_valid_pan($_POST['panNumber']);

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

                  if ($user_data['balance'] >= $amount) {
                      $order_id = order_txn_id();
                      $request = [
                          'panNumber' => $panNumber,
                          'order_id' => $order_id
                      ];

                      $responseApi = panDetailsPrememium_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'       => "PANDETAILS",
                                  'type'          => "Debit",
                                  'account_number'=> $panNumber,
                                  'app_type'      => "PANDETAILS",
                                  'amount'        => $amount,
                                  'main_amount'   => $amount,
                                  'old_balance'   => $old_balance,
                                  'new_balance'   => $new_balance,
                                  'txn_id'        => $order_id,
                                  'ref_id'        => $response['name'],
                                  'description'   => "Rs.{$amount} Has Been Debit From Wallet for PAN Details {$panNumber} Name ",
                                  'date_time'     => current_timestamp(),
                                  'status'        => "Success"
                              ];

                              $insertId = db_insert("reports", $insData);
                              if ($insertId) {
                                 $fields = [
                                     'name' => 'Name',
                                     'fathername' => 'Father',
                                     'dob' => 'DOB',
                                     'gender' => 'Gender',
                                     'aadhar' => 'UID',
                                     'address' => 'Address',
                                     'mobileNumber' => 'Mobile',
                                     'emailId' => 'Email'
                                 ];

                                 $whamessage = "Dear {$user_data['name']},\nYour Request for PAN Details *{$panNumber}* has been Complete.\n\n";

                                 foreach ($fields as $key => $label) {
                                     if (!empty($response[$key])) {
                                         $whamessage .= "*$label*: {$response[$key]}\n";
                                     }
                                 }
                                 $whamessage .= "\nBest Regards,\n_*{$site_data['brand']}.*_";
                                  send_sms($user_data['mobile'],$whamessage);
                                //   awal_alert_msg("Pan Details Fetched Successfully!", 'success');
                              } 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>Pan Number</label>
                <input type="text" name="panNumber" placeholder="Enter PAN Number" maxlength="10" class="form-control" 
                pattern="^[A-Z]{5}[0-9]{4}[A-Z]{1}$" title="PAN number must be in the format of AAAAA1234A" oninput="this.value = this.value.toUpperCase()"
                onkeypress="if(this.value.length==10) return false;" required>
            </div>
            <div class="col-md-12 mb-3 d-flex justify-content-between">
              <!-- Application Charge Button -->
              <button type="button" class="btn btn-secondary" ><i class="fas fa-inr"></i> <?php echo $user_data['pandetils_fee'];?></button>
              <!-- Submit 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>
  <?php } else {
      awal_alert_msg('You Do Not Have Any PAN Service Active!', 'info', 'dashboard');
  } ?>
</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['name']) && !empty($response['name'])) { ?>
          <form class="row">
            <div class="col-md-6 mb-3">
              <label>PAN Number</label>
              <input type="text" value="<?= htmlspecialchars($panNumber) ?>" class="form-control" readonly>
            </div>
            <?php if (isset($response['name']) && !empty($response['name'])) { ?>
            <div class="col-md-6 mb-3">
              <label>Full Name</label>
              <input type="text" value="<?= htmlspecialchars($response['name']) ?>" class="form-control" readonly>
            </div>
             <?php } ?>
             <?php if (isset($response['dob']) && !empty($response['dob'])) { ?>
            <div class="col-md-6 mb-3">
              <label>Date of Birth</label>
              <input type="text" value="<?= htmlspecialchars($response['dob']) ?>" class="form-control" readonly>
            </div>
             <?php } ?>
             <?php if (isset($response['fathername']) && !empty($response['fathername'])) { ?>
            <div class="col-md-6 mb-3">
              <label>Father Name</label>
              <input type="text" value="<?= htmlspecialchars($response['fathername']) ?>" class="form-control" readonly>
              </div>
             <?php } ?>
             <?php if (isset($response['gender']) && !empty($response['gender'])) { ?>
            <div class="col-md-6 mb-3">
              <label>Gender</label>
              <input type="text" value="<?= htmlspecialchars($response['gender']) ?>" class="form-control" readonly>
              </div>
             <?php } ?>
             <?php if (isset($response['aadhar']) && !empty($response['aadhar'])) { ?>
            <div class="col-md-6 mb-3">
              <label>Aadhaar Number</label>
              <input type="text" value="<?= htmlspecialchars($response['aadhar']) ?>" class="form-control" readonly>
              </div>
             <?php } ?>
             <?php if (isset($response['mobileNumber']) && !empty($response['mobileNumber'])) { ?>
            <div class="col-md-6 mb-3">
              <label>Mobile</label>
              <input type="text" value="<?= htmlspecialchars($response['mobileNumber']) ?>" class="form-control" readonly>
              </div>
             <?php } ?>
             <?php if (isset($response['emailId']) && !empty($response['emailId'])) { ?>
            <div class="col-md-6 mb-3">
              <label>Email</label>
              <input type="text" value="<?= htmlspecialchars($response['emailId']) ?>" class="form-control" readonly>
              </div>
             <?php } ?>
             <?php if (isset($response['address']) && !empty($response['address'])) { ?>
            <div class="col-md-12 mb-3">
              <label>Address</label>
              <input type="text" value="<?= htmlspecialchars($response['address']) ?>" class="form-control" readonly>
              </div>
             <?php } ?>
          </form>
        <?php } else { ?>
          <p>No details fetched yet. Submit PAN Number 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['panNumber']) && !empty($response['panNumber'])) { ?>
    $(document).ready(function() {
      $('#showDetailsModal').modal('show');
    });
  <?php } ?>
</script>

<?php
} else {
    require_once("404.php");
}

require_once("../layouts/members/foot.php");
?>
