<?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'])) {
              $ifscCode = strtoupper(trim($_POST['ifscCode']));

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

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

                      $responseApi = ifsc_code_api_run($request);
                      $response = json_decode($responseApi, true) ?? '';

                      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'       => "IFSC_CODE_SEARCH",
                                  'type'          => "Debit",
                                  'account_number'=> $response['ifsc'],
                                  'app_type'      => "IFSC_CODE_SEARCH",
                                  'amount'        => $amount,
                                  'main_amount'   => $amount,
                                  'old_balance'   => $old_balance,
                                  'new_balance'   => $new_balance,
                                  'txn_id'        => $order_id,
                                  'ref_id'        => $response['ifsc'],
                                  'description'   => "Rs.{$amount} Has Been Debit From Wallet for Name {$response['bank']} IFSC code ",
                                  'date_time'     => current_timestamp(),
                                  'status'        => "Success"
                              ];

                              $insertId = db_insert("reports", $insData);
                              if ($insertId) {
                                  $fields = [
                                      'bank' => 'Bank Name',
                                      'bankcode' => 'Bank Code',
                                      'ifsc' => 'IFSC Code',
                                      'branch' => 'Branch Name',
                                      'address' => 'Address',
                                      'city' => 'City',
                                      'centre' => 'Center',
                                      'country' => 'Country',
                                      'contact' => 'Contact',
                                      'country' => 'Country',
                                  ];

                                  $whamessage = "Dear {$user_data['name']},\nYour Request for IFSC Code *{$ifscCode}* Searching has been Complete.\n\n";
                                  foreach ($fields as $key => $label) {
                                      if (!empty($response[$key]) && isset($response[$key])) {
                                          $whamessage .= "*$label*: {$response[$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>IFSC Number</label>
              <input type="text" name="ifscCode" placeholder="Enter IFSC Number" maxlength="15" 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['ifsc_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-8 mb-2">
  <div class="card text-danger">
    <div class="card-header bg-danger text-white py-2">
      <span class="mr-auto">Details Searching Complete IFSC Code: <strong><?= $response['ifsc'] ?? 'N/A'; ?></strong></span>
    </div>
    <div class="table-responsive">
      <table class="table table-bordered table-striped">
        <tbody>
          <?php if (!empty($response['bank'])): ?>
          <tr>
            <td><strong>Bank Name</strong></td>
            <td><?= htmlspecialchars($response['bank']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['bankcode'])): ?>
          <tr>
            <td><strong>Bank Code</strong></td>
            <td><?= htmlspecialchars($response['bankcode']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['branch'])): ?>
          <tr>
            <td><strong>Branch</strong></td>
            <td><?= htmlspecialchars($response['branch']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['address'])): ?>
          <tr>
            <td><strong>Address</strong></td>
            <td><?= htmlspecialchars($response['address']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['city'])): ?>
          <tr>
            <td><strong>City</strong></td>
            <td><?= htmlspecialchars($response['city']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['centre'])): ?>
          <tr>
            <td><strong>Center</strong></td>
            <td><?= htmlspecialchars($response['centre']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['country'])): ?>
          <tr>
            <td><strong>Country</strong></td>
            <td><?= htmlspecialchars($response['country']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['contact'])): ?>
          <tr>
            <td><strong>Contact</strong></td>
            <td><?= htmlspecialchars($response['contact']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['micr'])): ?>
          <tr>
            <td><strong>MICR</strong></td>
            <td><?= htmlspecialchars($response['micr']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (isset($response['rtgs'])): ?>
          <tr>
            <td><strong>RTGS</strong></td>
            <td><?= $response['rtgs'] === true ? 'True' : htmlspecialchars($response['rtgs']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (isset($response['neft'])): ?>
          <tr>
            <td><strong>NEFT</strong></td>
            <td><?= $response['neft'] === true ? 'True' : htmlspecialchars($response['neft']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (isset($response['imps'])): ?>
          <tr>
            <td><strong>IMPS</strong></td>
            <td><?= $response['imps'] === true ? 'True' : htmlspecialchars($response['imps']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (isset($response['upi'])): ?>
          <tr>
            <td><strong>UPI</strong></td>
            <td><?= $response['upi'] === true ? 'True' : htmlspecialchars($response['upi']); ?></td>
          </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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

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