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

$response = [];
$dlNumber = '';
$dob = '';
$pdfData = '';

if ($user_data['dl_pdf_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
if (isset($_POST['submit'])) {
    $dlNumber = strtoupper(trim($_POST['dlNumber'] ?? ''));
    $dob = trim($_POST['dobenter'] ?? '');

    $background_type = $_POST['background_type'] ?? 'white';
    $type = $_POST['type'] ?? 'nochip';

    if ($background_type == "blue") {
        $type = "chip";
    } elseif ($background_type == "jammu_kashmir") {
        $type = "blue";
    }

    if (!empty($dlNumber) && !empty($dob)) {
        $amount = $user_data['dl_pdf_fee'];
        $old_balance = $user_data['balance'];
        $new_balance = $old_balance - $amount;

        if ($old_balance >= $amount) {
            $order_id = order_txn_id();

            $request = [
                'dlno'     => $dlNumber,
                'dob'      => $dob,
                'type'     => $type,
                'order_id' => $order_id,
            ];

            if ($background_type == "blue") {
                $responseApi = DrivingLicenceHDPdf_run2($request);
            } else {
                $responseApi = DrivingLicenceHDPdf_run($request);
            }

            $response = json_decode($responseApi, true);
            if (!is_array($response)) {
                $response = [];
            }

            if (isset($response['status']) && $response['status'] == '100') {
                $updateSuccess = db_update("members", ["balance" => $new_balance], " user_id='" . $user_data['user_id'] . "' ");

                if ($updateSuccess) {
                    if ($background_type == "blue") {
                        $appType = "DL PDF BLUE BACKGROUND";
                        $bgName = "Blue Background";
                    } elseif ($background_type == "jammu_kashmir") {
                        $appType = "DL PDF JAMMU & KASHMIR";
                        $bgName = "Jammu & Kashmir Card";
                    } else {
                        $appType = "DL PDF WHITE BACKGROUND";
                        $bgName = "White Background";
                    }

                    $insertId = db_insert("reports", [
                        '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'        => "DL PDF",
                        'type'           => "Debit",
                        'account_number' => $response['dlno'] ?? $dlNumber,
                        'app_type'       => $appType,
                        'amount'         => $amount,
                        'main_amount'    => $amount,
                        'old_balance'    => $old_balance,
                        'new_balance'    => $new_balance,
                        'txn_id'         => $order_id,
                        'ref_id'         => $response['dlno'] ?? $dlNumber,
                        'description'    => "Rs.{$amount} Has Been Debit From Wallet for DL PDF By DL Number {$dlNumber}",
                        'date_time'      => current_timestamp(),
                        'status'         => "Success"
                    ]);

                    if ($insertId) {
                        $whamessage = "Dear {$user_data['name']},\nYour Request for DL Number *{$dlNumber}* PDF has been Complete.\n\n";
                        $whamessage .= "*DL No*: " . ($response['dlno'] ?? $dlNumber) . "\n";
                        $whamessage .= "*DOB*: " . ($response['dob'] ?? $dob) . "\n";
                        $whamessage .= "*Background*: {$bgName}\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>DL Number</label>
    <input type="text" name="dlNumber" placeholder="Enter DL Number" maxlength="25"
           oninput="this.value = this.value.toUpperCase().replace(/\s+/g, '');"
           class="form-control" required>
  </div>

  <div class="col-md-12 mb-3">
    <label>Date Of Birth</label>
    <input type="text" name="dobenter" id="dob" placeholder="10-05-2000" class="form-control" autocomplete="off" required>
  </div>

  <div class="col-md-12 mb-3">
    <label>Select Card / Background</label>
    <select name="background_type" id="background_type" class="form-control" required>
      <option value="white" selected>White Background</option>
      <option value="blue">Blue Background</option>
      <option value="jammu_kashmir">Jammu & Kashmir Card</option>
    </select>
  </div>

  <div class="col-md-12 mb-3" id="chipTypeBox">
    <label>Select Type</label>
    <select name="type" id="type" class="form-control">
      <option value="nochip" selected>No Chip</option>
      <option value="chip">Chip</option>
    </select>
  </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['dl_pdf_fee']; ?>
    </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'])) {
    $pdfData = $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 id="downloadPdfBtn" href="<?= htmlspecialchars($pdfData); ?>"
         download="<?= htmlspecialchars($response['dlno'] ?? $dlNumber); ?>.pdf"
         class="btn btn-warning">
        <i class="fas fa-download"></i> Download PDF
      </a>
    </div>

    <iframe id="pdfPreviewFrame"
            style="width:100%; height:600px; border:1px solid #ccc;"
            frameborder="0">
    </iframe>
  </div>
</div>
<?php } ?>

</div>

<script>
flatpickr("#dob", {
  dateFormat: "d-m-Y",
  allowInput: true,
  maxDate: "today"
});

function toggleChipType() {
  var bg = document.getElementById("background_type").value;
  var chipBox = document.getElementById("chipTypeBox");
  var typeSelect = document.getElementById("type");

  if (bg === "white") {
    chipBox.style.display = "block";
  } else {
    chipBox.style.display = "none";

    if (bg === "blue") {
      typeSelect.value = "chip";
    }

    if (bg === "jammu_kashmir") {
      typeSelect.value = "nochip";
    }
  }
}

document.getElementById("background_type").addEventListener("change", toggleChipType);
toggleChipType();

<?php if (!empty($pdfData)) { ?>
(function () {
  var pdfData = <?= json_encode($pdfData); ?>;
  var iframe = document.getElementById("pdfPreviewFrame");

  if (pdfData && pdfData.indexOf("base64,") !== -1) {
    var base64 = pdfData.split("base64,")[1];
    base64 = base64.replace(/\s/g, "");

    var byteCharacters = atob(base64);
    var byteNumbers = new Array(byteCharacters.length);

    for (var i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i);
    }

    var byteArray = new Uint8Array(byteNumbers);
    var blob = new Blob([byteArray], {type: "application/pdf"});
    var blobUrl = URL.createObjectURL(blob);

    iframe.src = blobUrl;
  } else {
    iframe.src = pdfData;
  }
})();
<?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");
?>