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

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

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

                      $responseApi = rtpsCertificate_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'       => "RTPS CERTIFICATE PDF",
                                  'type'          => "Debit",
                                  'account_number'=> $response['applicationNumber'],
                                  'app_type'      => "RTPS CERTIFICATE PDF",
                                  'amount'        => $amount,
                                  'main_amount'   => $amount,
                                  'old_balance'   => $old_balance,
                                  'new_balance'   => $new_balance,
                                  'txn_id'        => $order_id,
                                  'ref_id'        => $response['applicationNumber'],
                                  'description'   => "Rs.{$amount} Has Been Debit From Wallet for Name {$response['name']} Rtps Certificate PDF By Application Number ",
                                  'date_time'     => current_timestamp(),
                                  'status'        => "Success"
                              ];

                              $insertId = db_insert("reports", $insData);
                              if ($insertId) {
                                 $fields = [
                                     'applicationNumber' => 'Application No',
                                     'name' => 'Name',
                                 ];

                                 $whamessage = "Dear {$user_data['name']},\nYour Request for Application Number *{$applicationNumber}* PDF 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);
                              } 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>Application Number</label>
              <input type="text" name="applicationNumber" placeholder="Enter Application Number" maxlength="45" class="form-control" required>
            </div>
            <div class="col-md-12 mb-3">
              <label>Name</label>
              <input type="text" name="name" placeholder="Enter Full Name" maxlength="45" 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> <?php echo $user_data['rtps_br_price'];?></button>
              <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">Submit</button>
            </div>
          </form>
        </div>
      </div>
    </div>

<?php if (isset($response['pdf']) && !empty($response['pdf'])) { ?>
  <div class="col-md-8 mb-2">
    <div class="card text-danger">
      <div class="card-header bg-primary text-white py-2">
        <span>your PDF is ready to download...</span>
        <a href="<?php echo htmlspecialchars($response['pdf']); ?>" download="<?php echo htmlspecialchars($response['applicationNumber']); ?>.pdf" class="btn btn-warning">
          <i class="fas fa-download"></i> Download PDF
        </a>
      </div>
      <iframe src="<?php echo htmlspecialchars($response['pdf']); ?>" 
              style="width: 100%; height: 600px; border: 1px solid #ccc;" frameborder="0">
      </iframe>
    </div>
  </div>
<?php } ?>
</div>
<?php
} else {
    require_once("404.php");
}
} else {
    awal_alert_msg('You Do Not Have This Service Active!', 'info', 'dashboard');
}
require_once("../layouts/members/foot.php");
?>
