<!-- <a href="<?= base_url('assets/qz-tray/digital-certificate.pem'); ?>"><?= base_url('assets/qz-tray/digital-certificate.pem'); ?></a>
<a href="<?= base_url('assets/qz-tray/private-key.pem'); ?>"><?= base_url('assets/qz-tray/private-key.pem'); ?></a> -->
<style>
  #printArea {
    position: relative;
  }
  .ribbon {
    width: 200px;
    padding: 10px 0;
    color: white;
    font-weight: bold;
    font-size: 1.5rem;
    text-align: center;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
    pointer-events: none;
  }
</style>
<div class="row">
  <div class="col-md-9">

    <div class="card">
      <div class="card-body" id="printArea">
        <div class="row">
          <div class="col-md-5 text-left">
            <img src="<?= base_url('uploads/settings/' . ($settings->logo_receipt ?? 'favicon.png')) ?>" style="max-height:55px;">
            <p><?= html_escape($settings->org_address ?? 'Clinic Address') ?><br>
              <?= html_escape($settings->org_phone ?? 'Number') ?>
            </p>
            
          </div>
          <div class="col-md-3">


<?php if (!empty($tokenwithshift)) : ?>
  <?php if ($tokenwithshift->balance > 0 && $tokenwithshift->total_fee != $tokenwithshift->balance) : ?>
    <div class="ribbon bg-warning">Partially Paid</div>
  <?php elseif ($tokenwithshift->total_fee == $tokenwithshift->balance) : ?>
    <div class="ribbon bg-danger">Un-Paid</div>
  <?php endif; ?>
<?php endif; ?>




            
            
          
          </div>
                    
          <div class="col-md-4 text-right" style="text-align: end;">
            <img src="<?= base_url('admin/render/QRcode/' . $print_invoicing->id); ?>" width="100" alt="Invoice QR Code">
          </div>
        </div>
<hr>
        <!-- Header Info -->
        <table class="table table-borderless mb-2">
          <tr class="">
            <td>
              <strong>Date &amp; Time:</strong>
              <small><?= date('d-m-Y - h:i:s A', strtotime($tokenwithshift->created_at)) ?></small><br>
              <strong>Shift:</strong> <?= html_escape($tokenwithshift->shift_name); ?>
            </td>
            <td class="text-end">
              <h1><?= (int)$tokenwithshift->token_number ?></h1>
            </td>
          </tr>
          <tr>
            <td><strong>Patient:</strong> <?= html_escape($tokenwithshift->name); ?></td>
            <td class="text-end"><strong>Sex:</strong> <?= html_escape($tokenwithshift->gender); ?></td>
          </tr>
          <tr>
            <td><strong>Phone:</strong> <?= html_escape($tokenwithshift->phone); ?></td>
            <td class="text-end"><strong>Age:</strong> <?= html_escape(trim($tokenwithshift->age . ' ' . $tokenwithshift->age_unit)); ?></td>
          </tr>
        </table>

        <?php if (!empty($tokenwithshift->funded_by)) : ?>
          <span class="d-block text-center" style="background:#000; color:#fff;">
            Funded By: <?= html_escape($tokenwithshift->funded_by); ?>
          </span>
        <?php endif; ?>

        <!-- Services Table -->
        <table class="table table-bordered">
          <thead>
            <tr>
              <th style="width:50px;">#</th>
              <th>Service</th>
              <th style="width:100px; text-align:right;">Amount</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $computed_total = 0.00;
            if (!empty($services)) {
              foreach ($services as $srv) {
                $computed_total += (float)($srv['fee'] ?? 0.00);
              }
            }

            $currency         = 'PKR';
            $discount_percent = (float)($tokenwithshift->discount_percent ?? 0);
            $discount_amount  = (float)($tokenwithshift->discount_amount ?? 0);
            $balance_amount   = (float)($tokenwithshift->balance ?? 0);


            if ($discount_percent > 0 && ($discount_amount <= 0)) {
              $discount_amount = ($computed_total * $discount_percent) / 100;
            }

            // $final_total = $computed_total - $discount_amount - $balance_amount;

            $paid_amount = $tokenwithshift->total_fee - $balance_amount; 

            ?>
<?php
if (!function_exists('formatServiceName')) {
    function formatServiceName($deptName, $subServiceName, $consultantName) {
        $deptName = strtolower(trim($deptName));
        $subServiceName = trim($subServiceName);
        $consultantName = trim($consultantName);

        if ($deptName === 'opd') {
            return "OPD {$subServiceName} By {$consultantName}";
        } else if ($deptName === 'lab') {
            return "{$subServiceName} By {$consultantName} Lab";
        } else if ($deptName === 'ultrasound') {
            return "{$subServiceName} Ultrasound by {$consultantName}";
        } else if ($deptName === 'physiotherapy') {
            return "Physiotherapy {$subServiceName} by {$consultantName}";
        } else if ($deptName === 'clinical services') {
            return $subServiceName;
        } else {
            return "{$subServiceName} by {$consultantName} {$deptName}";
        }
    }
}
?>
            <?php if (!empty($services)) : ?>
              <?php foreach ($services as $i => $srv) : ?>
                <tr>
                  <td><?= $i + 1 ?></td>



<td>
    <?= html_escape(
        formatServiceName(
            $srv['department_name'] ?? '',        // Make sure this is available, else '' 
            $srv['sub_service_name'] ?? '',
            $srv['service_name'] ?? ''
        )
    ) ?>
</td>


<?php 
$gross_total = $tokenwithshift->total_fee + $tokenwithshift->discount_amount;
?>
                  <td class="text-right"><?= amount_format_pakistani((float)$srv['fee']) ?></td>
                </tr>
              <?php endforeach; ?>
            <?php else : ?>
              <tr>
                <td colspan="3" class="text-center">No services added.</td>
              </tr>
            <?php endif; ?>

            <tr>
              <td colspan="2" class="text-right"><strong>Net Total:</strong></td>
              <td class="text-right"><strong><?= amount_format_pakistani($gross_total) ?></strong></td>
            </tr>


            <?php if ($discount_amount > 0 || $discount_percent > 0): ?>
              <tr>
                <td colspan="2"><strong>Discount Applied: <strong><?= number_format($discount_percent) ?>%</strong></strong></td>
                <!-- <td class="text-right"><strong><?= amount_format_pakistani($discount_percent) ?>%</strong></td> -->
                <!-- <td colspan=""><strong>Discount Amount:</strong></td> -->
                <td class="text-right"><strong><?= amount_format_pakistani($discount_amount) ?></strong></td>
              </tr>
              <!-- <tr>
                <td colspan="2"><strong>Discount Amount:</strong></td>
                <td class="text-right"><?= amount_format_pakistani($discount_amount) ?></td>
              </tr> -->
            <?php endif; ?>
<!-- <pre>
<?php print_r($tokenwithshift); ?>
</pre> -->
            <tr>
              <td colspan="2" class="text-right"><strong>Payable:</strong></td>
              <td class="text-right"><strong><?= amount_format_pakistani($tokenwithshift->total_fee) ?></strong></td>
            </tr>


            <?php if (!empty($tokenwithshift) && $tokenwithshift->balance > 0 ): ?>
              <tr>
                <td colspan="2"><strong>Paid Amount:</strong></td>
                <td class="text-right"><strong><?= amount_format_pakistani($paid_amount) ?></strong></td>
              </tr>
              <tr>
                <td colspan="2"><strong>Balance:</strong></td>
                <td class="text-right"><strong><?= amount_format_pakistani($tokenwithshift->balance) ?></strong></td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- RIGHT COLUMN -->
  <div class="col-md-3">
    <!-- Print Slip Card Button -->
    <div class="card prod-p-card bg-primary mb-3" onclick="printSlip()" style="cursor:pointer;">
      <div class="card-body">
        <div class="row align-items-center m-b-0">
          <div class="col">
            <h5 class="m-b-0 text-white">Print POS Slip </h5>
          </div>
          <div class="col-auto">
            <i class="material-icons-two-tone text-white">print</i>
          </div>
        </div>
      </div>
    </div>

    <a href="<?= base_url('admin/tokens/bill_print_view/' . $print_invoicing->id); ?>" target="_blank"
      class="card prod-p-card bg-primary mb-3" style="cursor:pointer; text-decoration:none;">
      <div class="card-body">
        <div class="row align-items-center m-b-0">
          <div class="col">
            <h5 class="m-b-0 text-white">Print Invoice</h5>
          </div>
          <div class="col-auto">
            <i class="material-icons-two-tone text-white">print</i>
          </div>
        </div>
      </div>
    </a>

    <a href="<?= base_url('admin/tokens/add'); ?>"
      class="card prod-p-card bg-primary mb-3" style="cursor:pointer; text-decoration:none;">
      <div class="card-body">
        <div class="row align-items-center m-b-0">
          <div class="col">
            <h5 class="m-b-0 text-white">Create New Token</h5>
          </div>
          <div class="col-auto">
            <i class="material-icons-two-tone text-white">confirmation_number</i>
          </div>
        </div>
      </div>
    </a>
    <!-- edit badge -->

    <a href="javascript:void(0);" class="card prod-p-card bg-warning mb-3 edit-token-btn" style="cursor:pointer; text-decoration:none;"
      data-id="<?= $tokenwithshift->id ?>"
      data-name="<?= $tokenwithshift->name ?>"
      data-phone="<?= $tokenwithshift->phone ?>"
      data-gender="<?= $tokenwithshift->gender ?>"
      data-age="<?= $tokenwithshift->age ?>"
      data-age_unit="<?= $tokenwithshift->age_unit ?>">
      <div class="card-body">
        <div class="row align-items-center m-b-0">
          <div class="col">
            <h5 class="m-b-0 text-white">Edit Patient Data</h5>
          </div>
          <div class="col-auto">
           <i class="material-icons-two-tone text-white">edit</i>
          </div>
        </div>
      </div>
    </a>


<?php if (empty($tokenwithshift->returned_at)): ?>
    <a href="<?= base_url('admin/tokens/return_token/'.$tokenwithshift->id) ?>"
       class="card prod-p-card bg-danger mb-3"
       style="cursor:pointer; text-decoration:none;"
       onclick="return confirm('Are you sure you want to return this token? Payments will also be refunded!');">

        <div class="card-body">
            <div class="row align-items-center m-b-0">
                <div class="col">
                    <h5 class="m-b-0 text-white">Return Token</h5>
                </div>
                <div class="col-auto">
                    <i class="material-icons-two-tone text-white">undo</i>
                </div>
            </div>
        </div>
    </a>
<?php else: ?>
    <div class="card prod-p-card bg-success mb-3">
        <div class="card-body">
            <div class="row align-items-center m-b-0">
                <div class="col">
                    <h5 class="m-b-0 text-white">Token Returned</h5>
                </div>
                <div class="col-auto">
                    <i class="material-icons-two-tone text-white">check_circle</i>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>





<a href="javascript:void(0);" class="card prod-p-card bg-warning mb-3 edit-payment-btn"
   data-id="<?= $tokenwithshift->id ?>"
   data-total_fee="<?= $tokenwithshift->total_fee ?>"
   data-paid_so_far="<?= $tokenwithshift->total_fee - $tokenwithshift->balance ?>"
   data-balance="<?= $tokenwithshift->balance ?>">
   <div class="card-body">
       <div class="row align-items-center m-b-0">
           <div class="col">
               <h5 class="m-b-0 text-white">Edit Payment</h5>
           </div>
           <div class="col-auto">
               <i class="material-icons-two-tone text-white">edit</i>
           </div>
       </div>
   </div>
</a>


  </div>
</div>


<!-- jQuery and Bootstrap -->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>


<script>
  $(function () {
    $('.edit-payment-btn').click(function () {
      $('#edit_id').val($(this).data('id'));
      $('#edit_name').val($(this).data('name'));
      $('#edit_phone').val($(this).data('phone'));
      $('#edit_gender').val($(this).data('gender'));
      $('#edit_age').val($(this).data('age'));
      $('#edit_age_unit').val($(this).data('age_unit'));

      var modal = new bootstrap.Modal(document.getElementById('editPaymentModal'));
      modal.show();
    });
  });
</script>

<script>
$(document).on('click', '.edit-payment-btn', function () {

    var tokenId   = $(this).data('id');
    var totalFee  = $(this).data('total_fee');
    var paidSoFar = $(this).data('paid_so_far');
    var balance   = $(this).data('balance');

    console.log("TOKEN ID:", tokenId); // DEBUG

    $('#edit_id').val(tokenId);
    $('#edit_total_fee').val(totalFee);
    $('#edit_paid_so_far').val(paidSoFar);
    $('#edit_balance').val(balance);
    $('#edit_paid_amount').attr('max', balance);

    var modal = new bootstrap.Modal(document.getElementById('editPaymentModal'));
    modal.show();
});
</script>


<!-- just put this somewhere in your page -->



<?php $this->load->view('admin/tokens/widgets/edit-tokens-modal'); ?>
<?php $this->load->view('admin/tokens/widgets/edit-payment-modal'); ?>

 <!-- QZ Tray Libraries -->
<!-- QZ Tray Libraries -->
<!-- QZ Tray JS -->
<!-- JS deps -->
<script src="https://cdn.jsdelivr.net/npm/qz-tray/qz-tray.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsrsasign/10.8.6/jsrsasign-all-min.js"></script>

<script>
// === QZ security – disable for testing ===
qz.security.setCertificatePromise((resolve, reject) => resolve(null));
qz.security.setSignaturePromise(toSign => (resolve, reject) => resolve(null));

// === helpers ===
function padRight(str, len){str=str.toString();return str.length>=len?str.slice(0,len):str+' '.repeat(len-str.length);}
function padLeft(str,len){str=str.toString();return str.length>=len?str.slice(0,len):' '.repeat(len-str.length)+str;}
const ESC = '\x1B', GS  = '\x1D';
const center   = () => ESC + 'a' + '\x01';
const left     = () => ESC + 'a' + '\x00';
const boldOn   = () => ESC + 'E' + '\x01';
const boldOff  = () => ESC + 'E' + '\x00';
const doubleOn = () => GS + '!' + '\x11';
const doubleOff= () => GS + '!' + '\x00';
const tallOn   = () => GS + '!' + '\x01';
const normalOn = () => GS + '!' + '\x00';
const cutCmd   = () => GS + 'V' + '\x00';
const line     = () => "-----------------------------------------------\n";

// === slip builders ===
function buildCustomerSlip(){
  let slip = "";
  slip += center() + normalOn();
  slip += "<?= addslashes($settings->org_address ?? 'Address line here'); ?>\n";
  slip += "<?= addslashes($settings->org_phone ?? 'Contact Number'); ?>\n";
  slip += center() + line();

<?php if (!empty($tokenwithshift->funded_by)) : ?>
  slip += center() + boldOn();
  slip += "Funded By: <?= addslashes($tokenwithshift->funded_by); ?>\n";
  slip += boldOff() + center() + line();
<?php endif; ?>





<?php if (!empty($tokenwithshift)) : ?>

  <?php if ($tokenwithshift->balance > 0 && $tokenwithshift->total_fee != $tokenwithshift->balance) : ?>
  
  slip += center() + boldOn();
  slip += "Partially Paid\n";
  slip += boldOff() + center() + line();

  <?php elseif ($tokenwithshift->total_fee == $tokenwithshift->balance) : ?>
  
  slip += center() + boldOn();
  slip += "Un-Paid\n";
  slip += boldOff() + center() + line();

  <?php endif; ?>

<?php endif; ?>




  slip += center() + boldOn() + doubleOn();
  slip += "TOKEN#: <?= (int)$tokenwithshift->token_number ?>\n";
  slip += doubleOff() + boldOff();
  slip += "<?= 'SHIFT: ' . addslashes($tokenwithshift->shift_name)?>\n";
  slip += center() + line();

<?php
  $patientCol = 'Patient: ' . addslashes($tokenwithshift->name);
  $sexCol     = 'Sex: ' . addslashes($tokenwithshift->gender);
  $phoneCol   = 'Phone: ' . addslashes($tokenwithshift->phone);
  $ageCol     = 'Age: ' . (int)$tokenwithshift->age . ' ' . addslashes($tokenwithshift->age_unit);
  $billidCol  = 'Bill ID: ' . addslashes($tokenwithshift->id);
  $fullname   = $this->session->userdata('qurbani_fullname');
  $userCol    = 'User: ' . addslashes($fullname);
  $dateTime   = date('d-m-Y - h:i:s A', strtotime($tokenwithshift->created_at));
?>
  slip += center();
  slip += "Date/Time: <?= $dateTime ?>\n\n";
  slip += left();
  slip += padRight("<?= $patientCol ?>", 30) + padLeft("<?= $sexCol ?>", 16) + "\n";
  slip += padRight("<?= $phoneCol ?>", 30) + padLeft("<?= $ageCol ?>", 16) + "\n\n";
  slip += center() + boldOn() + "SERVICES\n" + boldOff();
  slip += left();
<?php
if (!function_exists('formatServiceName')) {
    function formatServiceName($deptName, $subServiceName, $consultantName) {
        $deptName = strtolower(trim($deptName));
        $subServiceName = trim($subServiceName);
        $consultantName = trim($consultantName);

        if ($deptName === 'opd') {
            return "OPD {$subServiceName} By {$consultantName}";
        } else if ($deptName === 'lab') {
            return "{$subServiceName} By {$consultantName} Lab";
        } else if ($deptName === 'ultrasound') {
            return "{$subServiceName} Ultrasound by {$consultantName}";
        } else if ($deptName === 'physiotherapy') {
            return "Physiotherapy {$subServiceName} by {$consultantName}";
        } else if ($deptName === 'clinical services') {
            return $subServiceName;
        } else {
            return "{$subServiceName} by {$consultantName} {$deptName}";
        }
    }
}

if (!empty($services)) {
    foreach ($services as $i => $srv) {
        $serviceNameFormatted = formatServiceName(
            $srv['department_name'] ?? '',
            $srv['sub_service_name'] ?? '',
            $srv['service_name'] ?? ''
        );
        // Assuming you have amount_format_pakistani() function to format fees like in your table
        $feeFormatted = amount_format_pakistani((float)($srv['fee'] ?? 0));

        // Output JS code with properly escaped values
        echo 'slip += padRight("' . ($i + 1) . '. ' . addslashes($serviceNameFormatted) . '", 30) + padLeft("' . addslashes($feeFormatted) . '", 16) + "\\n";' . "\n";
    }
} else {
    echo 'slip += "No services added\\n";' . "\n";
}
?>
slip += center() + line();
slip += left();

if (<?= (float)$discount_percent ?> > 0 || <?= (float)$discount_amount ?> > 0) {
  slip += padRight("Discount Applied:", 30) + padLeft("<?= number_format($discount_percent) ?>%", 16) + "\n";
  slip += padRight("Discount Rs", 30) + padLeft("<?= amount_format_pakistani($discount_amount) ?>", 16) + "\n";
}

slip += boldOn();
slip += padRight("Net Total:", 30) + padLeft("<?= amount_format_pakistani($gross_total) ?>", 16) + "\n";
slip += boldOff();

slip += boldOn();
slip += padRight("Payable:", 30) + padLeft("<?= amount_format_pakistani($tokenwithshift->total_fee) ?>", 16) + "\n";
slip += boldOff();

<?php if (!empty($tokenwithshift) && $tokenwithshift->balance > 0): ?>
  slip += padRight("Paid Amount:", 30) + padLeft("<?= amount_format_pakistani($paid_amount) ?>", 16) + "\n";
  slip += padRight("Balance:", 30) + padLeft("<?= amount_format_pakistani($tokenwithshift->balance) ?>", 16) + "\n";
<?php endif; ?>

slip += center() + line();
slip += left();
slip += padRight("<?= addslashes($billidCol) ?>", 30) + padLeft("<?= addslashes($userCol) ?>", 16) + "\n";

return slip;

  // slip += center() + line();
  // slip += left();
  // if (<?= (float)$discount_percent ?> > 0 || <?= (float)$discount_amount ?> > 0) {
  //   slip += padRight("Discount %", 30) + padLeft("<?= (float)$discount_percent ?>%", 16) + "\n";
  //   slip += padRight("Discount Rs", 30) + padLeft("<?= number_format($discount_amount,0) ?>", 16) + "\n";
  // }
  // slip += boldOn();
  // slip += padRight("Total Rs", 30) + padLeft("<?= number_format($computed_total - $discount_amount, 0) ?>", 16) + "\n";
  // slip += boldOff();
  // slip += center() + line();
  // slip += left();
  // slip += padRight("<?= $billidCol ?>", 30) + padLeft("<?= $userCol ?>", 16) + "\n";
  // return slip;
}

function buildSlipfoot(){
  let slip="";
  slip += center();
  slip += "<?= addslashes($SlipSettings->slip_footer ?? 'Thank you for visiting!'); ?>\n\n";
  slip += "\n\n\n";
  return slip;
}

function buildClinicSlip(){
  let slip="";
<?php if (!empty($tokenwithshift->funded_by)) : ?>
  slip += center() + line();
  slip += center() + boldOn();
  slip += "Funded By: <?= addslashes($tokenwithshift->funded_by); ?>\n";
  slip += boldOff() + center() + line();
<?php endif; ?>
  slip += center() + boldOn() + doubleOn();
  slip += "TOKEN#: <?= (int)$tokenwithshift->token_number ?>\n";
  slip += doubleOff() + boldOff();
  slip += "<?= 'SHIFT: ' . addslashes($tokenwithshift->shift_name)?>\n";
  slip += "Date/Time: <?= $dateTime ?>\n";
  slip += left();
  slip += padRight("<?= $billidCol ?>", 30) + padLeft("<?= $userCol ?>", 16) + "\n";
  slip += center() + line();    
  slip += left();
  slip += padRight("Patient: <?= addslashes($tokenwithshift->name) ?>",30)+padLeft("Sex: <?= addslashes($tokenwithshift->gender) ?>",16)+"\n";
  slip += padRight("Phone: <?= addslashes($tokenwithshift->phone) ?>",30)+padLeft("Age: <?= (int)$tokenwithshift->age ?> <?= addslashes($tokenwithshift->age_unit) ?>",16)+"\n";
  slip += center() + line();
  slip += center()+boldOn()+"SERVICES\n"+boldOff()+left();
<?php
if (!function_exists('formatServiceName')) {
    function formatServiceName($deptName, $subServiceName, $consultantName) {
        $deptName = strtolower(trim($deptName));
        $subServiceName = trim($subServiceName);
        $consultantName = trim($consultantName);

        if ($deptName === 'opd') {
            return "OPD {$subServiceName} By {$consultantName}";
        } else if ($deptName === 'lab') {
            return "{$subServiceName} By {$consultantName} Lab";
        } else if ($deptName === 'ultrasound') {
            return "{$subServiceName} Ultrasound by {$consultantName}";
        } else if ($deptName === 'physiotherapy') {
            return "Physiotherapy {$subServiceName} by {$consultantName}";
        } else if ($deptName === 'clinical services') {
            return $subServiceName;
        } else {
            return "{$subServiceName} by {$consultantName} {$deptName}";
        }
    }
}

if (!empty($services)) {
    foreach ($services as $i => $srv) {
        $serviceNameFormatted = formatServiceName(
            $srv['department_name'] ?? '',
            $srv['sub_service_name'] ?? '',
            $srv['service_name'] ?? ''
        );
        // Assuming you have amount_format_pakistani() function to format fees like in your table
        $feeFormatted = amount_format_pakistani((float)($srv['fee'] ?? 0));

        // Output JS code with properly escaped values
        echo 'slip += padRight("' . ($i + 1) . '. ' . addslashes($serviceNameFormatted) . '", 30) + padLeft("' . addslashes($feeFormatted) . '", 16) + "\\n";' . "\n";
    }
} else {
    echo 'slip += "No services added\\n";' . "\n";
}
?>
  slip+="\n\n\n";
  return slip;
}

// === embed images from PHP ===
<?php
// Logo path from DB
$logoFile  = !empty($SlipSettings->slip_logo) ? $SlipSettings->slip_logo : 'default.bmp';
$logoPath  = FCPATH.'uploads/settings/'.$logoFile;
$logoData  = file_exists($logoPath)?file_get_contents($logoPath):'';
$logoBase64 = base64_encode($logoData);

// QR resizing — PHP8-safe: agar QR data fetch/parsing fail ho to fatal ki bajaye
// fallback (1x1 transparent PNG) use karein, taake print page crash na ho.
$qrUrl   = base_url('admin/render/QRcode/' . $print_invoicing->id);
$qrData  = @file_get_contents($qrUrl);
$im      = ($qrData !== false && $qrData !== '') ? @imagecreatefromstring($qrData) : false;

if ($im !== false) {
    $desiredWidth  = 70; $desiredHeight = 140;
    $resized = imagecreatetruecolor($desiredWidth, $desiredHeight);
    imagealphablending($resized, false); imagesavealpha($resized, true);
    imagecopyresampled($resized, $im, 0, 0, 0, 0, $desiredWidth, $desiredHeight, imagesx($im), imagesy($im));
    ob_start(); imagepng($resized); $resizedData = ob_get_clean();
    $qrBase64 = base64_encode($resizedData);
    imagedestroy($im); imagedestroy($resized);
} else {
    // Fallback: transparent 1x1 PNG (print layout ki jaga khali rahegi, crash nahi)
    $qrBase64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
}
?>
const logoBase64 = "<?= $logoBase64 ?>";
const qrBase64   = "<?= $qrBase64 ?>";

// === main print ===
async function printSlip() {
  try {
    if (!qz.websocket.isActive()) await qz.websocket.connect();
    const config = qz.configs.create("<?= addslashes($SlipSettings->printer_name ?? 'Black Copper BC-85AC'); ?>");

    let cust = buildCustomerSlip(),
        foot = buildSlipfoot(),
        clin = buildClinicSlip();

    const data = [];

    // logo before customer copy
    data.push({ type: 'raw', data: center() });
    data.push({ type: 'image', format: 'base64', data: logoBase64, options: { language: "ESCPOS", dotDensity: 'double' }});
    data.push({ type: 'raw', data: "\n" });

    // customer slip text
    data.push({ type: 'raw', data: cust });

    // QR code
    data.push({ type: 'raw', data: center() });
    data.push({ type: 'image', format:'base64', data: qrBase64, options:{ language:"ESCPOS"} });
    data.push({ type: 'raw', data: "\n" });

    data.push({ type: 'raw', data: foot });
    data.push({ type: 'raw', data: "\n\n\n" });
    data.push({ type: 'raw', data: cutCmd() });

    // clinic slip text
    data.push({ type: 'raw', data: clin });
    data.push({ type: 'raw', data: "\n\n\n" });
    data.push({ type: 'raw', data: cutCmd() });

    await qz.print(config, data);
    window.location.href = "<?= base_url('admin/tokens/add'); ?>";
  } catch (e) {
    alert("Print error: " + e);
    console.error(e);
  }
}
</script>


<script type="text/javascript">
  function previewSlip() {
  // build same strings you print
  let cust = buildCustomerSlip();
  let foot = buildSlipfoot();
  let clin = buildClinicSlip();

  // combine all parts
  let fullSlip = cust + "\n" + foot + "\n\n" + clin;

  // dump into <pre>
  document.getElementById('slipPreviewArea').textContent = fullSlip;

  // (optional) also log to console
  console.log(fullSlip);
}

</script>