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

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

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

                      $responseApi = pin_code_api_run($request);
                      $response = json_decode($responseApi, true) ?? '';
                      $postOffice = $response['postOffice'] ?? [];
                      if ($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'       => "PINCODEVERIFY",
                                  'type'          => "Debit",
                                  'account_number'=> $postOffice[0]['State'],
                                  'app_type'      => "PINCODEVERIFY",
                                  'amount'        => $amount,
                                  'main_amount'   => $amount,
                                  'old_balance'   => $old_balance,
                                  'new_balance'   => $new_balance,
                                  'txn_id'        => $order_id,
                                  'ref_id'        => $postOffice[0]['State'],
                                  'description'   => "Rs.{$amount} Has Been Debit From Wallet for Name {$postOffice[0]['State']} PIN code ",
                                  'date_time'     => current_timestamp(),
                                  'status'        => "Success"
                              ];

                              $insertId = db_insert("reports", $insData);
                              if ($insertId) {
                                  $fields = [
                                      'name' => 'Name',
                                      'branchtype' => 'Branch',
                                      'circle' => 'Circle',
                                      'district' => 'Distric',
                                      'region' => 'Region',
                                      'block' => 'Block',
                                      'State' => 'State',
                                      'country' => 'Country',
                                      'pincode' => 'Pincode',
                                  ];

                                  $whamessage = "Dear {$user_data['name']},\nYour Request for PIN Code *{$pincode}* Searching has been Complete.\n\n";
                                  foreach ($fields as $key => $label) {
                                      if (!empty($postOffice[0][$key]) && isset($postOffice[0][$key])) {
                                          $whamessage .= "*$label*: {$postOffice[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>Pincode Number</label>
              <input type="text" name="pincode" placeholder="Enter Pincode Number" maxlength="10" oninput="this.value = this.value.toUpperCase().replace(/\s+/g, '');" class="form-control" 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> <?= $user_data['pincode_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-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']; ?></span>
    </div>
    <div class="table-responsive">
      <table class="table table-bordered table-striped">
        <thead>
          <tr style="text-align: center;">
            <th>Sr. No.</th>
            <th>Challan Number</th>
            <th>Name</th>
            <th>Delivery Status</th>
            <th>Circle</th>
            <th>District</th>
            <th>Block</th>
            <th>State</th>
            <th>Country</th>
          </tr>
        </thead>
        <tbody>
          <?php 
          $srNo = 1; // Initialize serial number
          foreach ($postOffice as $postOffices) { ?>
            <tr style="text-align: center;">
              <td><?= $srNo++; ?></td> <!-- Increment serial number -->
              <td><?= $postOffices['pincode']; ?></td>
              <td><?= $postOffices['name']; ?></td>
              <td>
                <?php if ($postOffices['deliverystatus'] == 'Delivery') { ?>
                  <button class="btn btn-success"><b>Delivery</b></button>
                <?php } else { ?>
                  <button class="btn btn-danger"><b><?= $postOffices['deliverystatus']; ?></b></button>
                <?php } ?>
              </td>
              <td><?= $postOffices['circle']; ?></td>
              <td><?= $postOffices['district']; ?></td>
              <td><?= $postOffices['block']; ?></td>
              <td><?= $postOffices['State']; ?></td>
              <td><?= $postOffices['country']; ?></td>
            </tr>
          <?php } ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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

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