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

          if (isset($_POST['submit'])) {
              $vehicalNumber = strtoupper($_POST['vehicalNumber']);
              $fatherName = strtoupper($_POST['fatherName'] ?? '');

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

                  if ($user_data['balance'] >= $amount) {
                      $order_id = order_txn_id();
                      $request = [
                          'vehicalNumber' => $vehicalNumber,
                          'type' => 'old',
                          'fatherName' => $fatherName,
                          'order_id' => $order_id,
                      ];

                      $responseApi = vehicalRcVerification_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'] . "' ");
                          
                          $ownerFatherFromApi = trim($response['ownerFatherName'] ?? '');
                          $ownerFatherFinal = ($ownerFatherFromApi !== '' && strtoupper($ownerFatherFromApi) !== 'NA')
                              ? $ownerFatherFromApi
                              : (trim($fatherName) !== '' ? $fatherName : 'NA');
                              
                          if ($updateSuccess) {
                              $printData = array(
                                  'regNo' => isset($response['regNo']) && !empty($response['regNo']) ? $response['regNo'] : $vehicalNumber,
                                  'owner' => isset($response['owner']) && !empty($response['owner']) ? $response['owner'] : 'NA',
                                  'ownerFatherName' => $ownerFatherFinal,
                                  'chassis' => isset($response['chassis']) && !empty($response['chassis']) ? $response['chassis'] : '',
                                  'engine' => isset($response['engine']) && !empty($response['engine']) ? $response['engine'] : '',
                                  'rcstatus' => isset($response['rcstatus']) && !empty($response['rcstatus']) ? $response['rcstatus'] : '',
                                  'rcStandardCap' => isset($response['rcStandardCap']) && !empty($response['rcStandardCap']) ? $response['rcStandardCap'] : '',
                                  'vehicleInsuranceCompanyName' => isset($response['vehicleInsuranceCompanyName']) && !empty($response['vehicleInsuranceCompanyName']) ? $response['vehicleInsuranceCompanyName'] : '',
                                  'vehicleInsuranceUpto' => isset($response['vehicleInsuranceUpto']) && !empty($response['vehicleInsuranceUpto']) ? $response['vehicleInsuranceUpto'] : '',
                                  'vehicleInsurancePolicyNumber' => isset($response['vehicleInsurancePolicyNumber']) && !empty($response['vehicleInsurancePolicyNumber']) ? $response['vehicleInsurancePolicyNumber'] : '',
                                  'rtoCode' => isset($response['rtoCode']) && !empty($response['rtoCode']) ? $response['rtoCode'] : '',
                                  'permanentAddress' => isset($response['permanentAddress']) && !empty($response['permanentAddress']) ? $response['permanentAddress'] : '',
                                  'presentAddress' => isset($response['presentAddress']) && !empty($response['presentAddress']) ? $response['presentAddress'] : '',
                                  'regDate' => isset($response['regDate']) && !empty($response['regDate']) ? $response['regDate'] : '',
                                  'rcExpiryDate' => isset($response['rcExpiryDate']) && !empty($response['rcExpiryDate']) ? $response['rcExpiryDate'] : '',
                                  'ownerCount' => isset($response['ownerCount']) && !empty($response['ownerCount']) ? $response['ownerCount'] : '',
                                  'type' => 'old',
                                  'fuel_descr' => isset($response['fuel_descr']) && !empty($response['fuel_descr']) ? $response['fuel_descr'] : '',
                                  'normsType' => isset($response['normsType']) && !empty($response['normsType']) ? $response['normsType'] : '',
                                  'monthYearmfg' => isset($response['monthYearmfg']) && !empty($response['monthYearmfg']) ? $response['monthYearmfg'] : '',
                                  'vehicleClass' => isset($response['vehicleClass']) && !empty($response['vehicleClass']) ? $response['vehicleClass'] : '',
                                  'vehicleCylindersNo' => isset($response['vehicleCylindersNo']) && !empty($response['vehicleCylindersNo']) ? $response['vehicleCylindersNo'] : '',
                                  'vehicleManufacturerName' => isset($response['vehicleManufacturerName']) && !empty($response['vehicleManufacturerName']) ? $response['vehicleManufacturerName'] : '',
                                  'model' => isset($response['model']) && !empty($response['model']) ? $response['model'] : '',
                                  'vehicleColour' => isset($response['vehicleColour']) && !empty($response['vehicleColour']) ? $response['vehicleColour'] : '',
                                  'bodyType' => isset($response['bodyType']) && !empty($response['bodyType']) ? $response['bodyType'] : '',
                                  'vehicleSeatCapacity' => isset($response['vehicleSeatCapacity']) && !empty($response['vehicleSeatCapacity']) ? $response['vehicleSeatCapacity'] : '2',
                                  'vehicleSleeperCapacity' => isset($response['vehicleSleeperCapacity']) && !empty($response['vehicleSleeperCapacity']) ? $response['vehicleSleeperCapacity'] : '0',
                                  'vehicleStandingCapacity' => isset($response['vehicleStandingCapacity']) && !empty($response['vehicleStandingCapacity']) ? $response['vehicleStandingCapacity'] : '0',
                                  'unladenWeight' => isset($response['unladenWeight']) && !empty($response['unladenWeight']) ? $response['unladenWeight'] : '',
                                  'vehicleCubicCapacity' => isset($response['vehicleCubicCapacity']) && !empty($response['vehicleCubicCapacity']) ? $response['vehicleCubicCapacity'] : '0',
                                  'vehicleCategory' => isset($response['vehicleCategory']) && !empty($response['vehicleCategory']) ? $response['vehicleCategory'] : '',
                                  'grossVehicleWeight' => isset($response['grossVehicleWeight']) && !empty($response['grossVehicleWeight']) ? $response['grossVehicleWeight'] : '',
                                  'horsepower' => isset($response['horsepower']) && !empty($response['horsepower']) ? $response['horsepower'] : '0',
                                  'wheelbase' => isset($response['wheelbase']) && !empty($response['wheelbase']) ? $response['wheelbase'] : '0',
                                  'rcFinancer' => isset($response['rcFinancer']) && !empty($response['rcFinancer']) ? $response['rcFinancer'] : 'On Cash',
                                  'regAuthority' => isset($response['regAuthority']) && !empty($response['regAuthority']) ? $response['regAuthority'] : '',
                                  'username'      => $user_data['username'],
                              );
                              $name = isset($response['owner']) && !empty($response['owner']) ? $response['owner'] : 'NA';

                               $Mremark = 'Name: ' . $name . " - Vehical Number: " . $vehicalNumber;
                               $insData = [
                                   'order_id'      => $order_id,
                                   'username'      => $user_data['username'],
                                   'name'          => $name,
                                   'idNumber'      => $vehicalNumber,
                                   'service'       => "VEHICALRCPDF",
                                   'date_time'     => current_timestamp(),
                                   'printData'     => base64_encode(str_replace("\\", "", json_encode($printData, JSON_UNESCAPED_UNICODE))),
                                   'photo'         => "",
                               ];

                               $insertIddata = db_insert("printRecords", $insData);
    
                               if ($insertIddata) {
                              $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'       => "VEHICALRCPDF",
                                  'type'          => "Debit",
                                  'account_number'=> $response['regNo'],
                                  'app_type'      => "VEHICALRCPDF",
                                  'amount'        => $amount,
                                  'main_amount'   => $amount,
                                  'old_balance'   => $old_balance,
                                  'new_balance'   => $new_balance,
                                  'txn_id'        => $order_id,
                                  'ref_id'        => $response['regNo'],
                                  'description'   => "Rs.{$amount} Has Been Debit From Wallet for Name {$response['owner']} RC Number ",
                                  'date_time'     => current_timestamp(),
                                  'status'        => "Success"
                              ];

                              $insertId = db_insert("reports", $insData);
                              if ($insertId) {
                                 $fields = [
                                     'regNo' => 'Vehical No',
                                     'owner' => 'Name',
                                     'ownerFatherName' => 'Father',
                                     'permanentAddress' => 'Permanent Address',
                                     'presentAddress' => 'Present Address',
                                 ];

                                 $whamessage = "Dear {$user_data['name']},\nYour Request for Vehical Number *{$vehicalNumber}* 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');
                              }
                              awal_alert_msg("Data Fetch Successful from '.$Mremark.'.", 'success');
                                redirect('printRecord', 3000);
                            } else {
                                 awal_alert_msg("Saving Data 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>Vehical Number</label>
              <input type="text" name="vehicalNumber" placeholder="Enter Vehical Number" maxlength="15" oninput="this.value = this.value.toUpperCase().replace(/\s+/g, '');" class="form-control" onkeypress="if(this.value.length==15) return false;" required>
            </div>
           <div class="col-md-12 mb-3">
             <label>Father/Husband Name <span style="color:red;">(Optional)</span></label>
             <div class="input-group">
              <input type="text" name="fatherName" placeholder="Enter Father/Husband" maxlength="55" class="form-control" >
               <div class="input-group-append">
                 <a href="Rc_Guardian_Find" class="btn btn-info">
                   <i class="fas fa-search"></i> Find
                 </a>
               </div>
             </div>
           </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['vehical_rc_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 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['owner']) && !empty($response['owner'])) { ?>
          <form class="row">
            <div class="col-md-6 mb-3">
              <label>Name</label>
              <input type="text" value="<?= htmlspecialchars($response['owner']) ?>" class="form-control" readonly>
              </div>
            <div class="col-md-6 mb-3">
              <label>Father Name</label>
              <input type="text" value="<?= htmlspecialchars($ownerFatherFinal) ?>" class="form-control" readonly>
            </div>
            <div class="col-md-12 mb-3">
              <label>Address</label>
              <input type="text" value="<?= htmlspecialchars($response['presentAddress']) ?>" class="form-control" readonly>
            </div>
          </form>
        <?php } else { ?>
          <p>No details fetched yet. Submit Vehical Number to 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['owner']) && !empty($response['owner'])) { ?>
    $(document).ready(function() {
      $('#showDetailsModal').modal('show');
    });
  <?php } ?>
</script>

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