<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>

<div class="mtop15 preview-top-wrapper">
    <div class="row">
        <div class="col-md-3">
            <div class="mbot30">
                <div class="invoice-html-logo">
                    <?= get_dark_company_logo(); ?>
                </div>
            </div>
        </div>
        <div class="clearfix"></div>
    </div>
    <div class="top" data-sticky data-sticky-class="preview-sticky-header">
        <div class="container preview-sticky-container">
            <div class="sm:tw-flex tw-justify-between -tw-mx-4">
                <div class="sm:tw-self-end">
                    <h3 class="bold tw-my-0 invoice-html-number">
                        <span class="sticky-visible hide tw-mb-2">
                            <?= e(format_invoice_number($invoice->id)); ?>
                        </span>
                    </h3>
                    <span class="invoice-html-status">
                        <?= format_invoice_status($invoice->status, '', true); ?>
                    </span>
                </div>
                <div class="tw-flex tw-items-end tw-space-x-2 tw-mt-3 sm:tw-mt-0">
                    <?php if (is_client_logged_in() && has_contact_permission('invoices')) { ?>
                    <a href="<?= site_url('clients/invoices/'); ?>"
                        class="btn btn-default action-button go-to-portal">
                        <?= _l('client_go_to_dashboard'); ?>
                    </a>
                    <?php } ?>
                    <?= form_open($this->uri->uri_string()); ?>
                    <button type="submit" name="invoicepdf" value="invoicepdf" class="btn btn-default action-button">
                        <i class='fa-regular fa-file-pdf'></i>
                        <?= _l('clients_invoice_html_btn_download'); ?>
                    </button>
                    <?= form_close(); ?>

                      <?php echo '<button type="button" id="offline_payment" class="btn btn-primary"><i class="fa fa-bank"></i> Bank Transfer </button>';?>

                    <a href="#" class="btn btn-success action-button invoice-html-pay-now-top sticky-hidden
                  <?php if (($invoice->status != Invoices_model::STATUS_PAID && $invoice->status != Invoices_model::STATUS_CANCELLED
                     && $invoice->total > 0) && found_invoice_mode($payment_modes, $invoice->id, false)) {
                      echo ' pay-now-top';
                  } ?>">
                        <?= _l('invoice_html_online_payment_button_text'); ?>
                    </a>



                </div>
            </div>
        </div>
    </div>
</div>
<!-- Modal -->
<div class="modal fade" id="offlinePayment" tabindex="-1" role="dialog" aria-labelledby="offlinePaymentLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">        
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
        <h4 class="modal-title" id="offlinePaymentLabel">Offline Payment</h4>
      </div>
      <div class="modal-body">
        <!-- Your static HTML content -->
        <div class="panel panel-default">
  <div class="panel-heading">
    <h4 class="panel-title" style="margin:0;"><?= get_option('companyname');?></h4>
    <small class="text-muted">Payable Accounts</small>
  </div>

  <div class="panel-body">
    <table class="table table-bordered" style="margin-bottom: 0;">
      <tbody>
        <tr>
          <th style="width:35%;">Account No</th>
          <td>5641-5522-1618</td>
        </tr>
        <tr>
          <th>Name</th>
          <td>INCEIF</td>
        </tr>
        <tr>
          <th>SWIFT Code</th>
          <td>MBBEMYKL</td>
        </tr>
        <tr>
          <th>Bank</th>
          <td>Malayan Banking Berhad (Maybank)</td>
        </tr>
        <tr>
          <th>Address</th>
          <td>
            Malayan Banking Berhad, Ground Floor, Menara DBKL 2,<br>
            Jalan Raja Laut, 50350 Kuala Lumpur, Malaysia
          </td>
        </tr>
      </tbody>
    </table>

    <div class="alert alert-warning alert-dismissable" style="margin-top:15px;">
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">&times;</button>
      Please provide the evidence of payment if you made a bank transfer to:
      <strong><a href="mailto:<?= get_option('smtp_email');?>"><?= get_option('smtp_email');?></a></strong>
    </div>
  </div>
</div>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
<div class="clearfix"></div>

<div class="panel_s tw-mt-6">
    <div class="panel-body">
        <?php if (is_invoice_overdue($invoice)) { ?>
        <div class="col-md-10 col-md-offset-1 tw-mb-5">
            <div class="alert alert-danger text-center">
                <p class="tw-font-medium">
                    <?= e(_l('overdue_by_days', get_total_days_overdue($invoice->duedate))); ?>
                </p>
            </div>
        </div>
        <?php } ?>
        <div class="col-md-10 col-md-offset-1">
            <div class="row mtop20">
                <div class="col-md-6 col-sm-6 transaction-html-info-col-left">
                    <h4 class="tw-font-semibold tw-text-neutral-700 invoice-html-number">
                        <?= e(format_invoice_number($invoice->id)); ?>
                    </h4>
                    <address class="invoice-html-company-info tw-text-neutral-500 tw-text-normal">
                        <?= format_organization_info(); ?>
                    </address>
                    <?php hooks()->do_action('after_left_panel_invoicehtml', $invoice); ?>
                </div>
                <div class="col-sm-6 text-right transaction-html-info-col-right">
                    <span class="tw-font-medium tw-text-neutral-700 invoice-html-bill-to">
                        <?= _l('invoice_bill_to'); ?>
                    </span><br>
                    <?php $primaryContactId = get_primary_contact_user_id($invoice->clientid); ?>
<span class="tw-font-medium tw-text-neutral-700 invoice-client-name">
    <?= e(get_contact_full_name($primaryContactId));?>
</span>
                    <address class="invoice-html-customer-billing-info tw-text-neutral-500 tw-text-normal">
                        <?= format_customer_info($invoice, 'invoice', 'billing'); ?>
                    </address>
                    <!-- shipping details -->
                    <?php if ($invoice->include_shipping == 1 && $invoice->show_shipping_on_invoice == 1) { ?>
                    <span class="tw-font-medium tw-text-neutral-700 invoice-html-ship-to">
                        <?= _l('ship_to'); ?>
                    </span>
                    <address class="invoice-html-customer-shipping-info tw-text-neutral-500 tw-text-normal">
                        <?= format_customer_info($invoice, 'invoice', 'shipping'); ?>
                    </address>
                    <?php } ?>
                    <p class="invoice-html-date tw-mb-0 tw-text-normal">
                        <span class="tw-font-medium tw-text-neutral-700">
                            <?= _l('invoice_data_date'); ?>
                        </span>
                        <?= e(_d($invoice->date)); ?>
                    </p>
                    <?php if (! empty($invoice->duedate)) { ?>
                    <p class="invoice-html-duedate tw-mb-0 tw-text-normal">
                        <span class="tw-font-medium tw-text-neutral-700">
                            <?= _l('invoice_data_duedate'); ?>
                        </span>
                        <?= e(_d($invoice->duedate)); ?>
                    </p>
                    <?php } ?>
                    <?php if ($invoice->sale_agent && get_option('show_sale_agent_on_invoices') == 1) { ?>
                    <p class="invoice-html-sale-agent tw-mb-0 tw-text-normal">
                        <span
                            class="tw-font-medium tw-text-neutral-700"><?= _l('sale_agent_string'); ?>:</span>
                        <?= e(get_staff_full_name($invoice->sale_agent)); ?>
                    </p>
                    <?php } ?>
                    <?php if ($invoice->project_id && get_option('show_project_on_invoice') == 1) { ?>
                    <p class="invoice-html-project tw-mb-0 tw-text-normal">
                        <span
                            class="tw-font-medium tw-text-neutral-700"><?= _l('project'); ?>:</span>
                        <?= e(get_project_name_by_id($invoice->project_id)); ?>
                    </p>
                    <?php } ?>
                    <?php $pdf_custom_fields = get_custom_fields('invoice', ['show_on_pdf' => 1, 'show_on_client_portal' => 1]); ?>
                    <?php foreach ($pdf_custom_fields as $field) {
                        $value = get_custom_field_value($invoice->id, $field['id'], 'invoice');
                        if ($value == '') {
                            continue;
                        } ?>
                    <p class="tw-mb-0 tw-text-normal">
                        <span
                            class="tw-font-medium tw-text-neutral-700"><?= e($field['name']); ?>:
                        </span>
                        <?= $value; ?>
                    </p>
                    <?php } ?>
                    <?php hooks()->do_action('after_right_panel_invoicehtml', $invoice); ?>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <div class="table-responsive">
                        <?php $items = get_items_table_data($invoice, 'invoice'); ?>
                        <?= $items->table(); ?>
                    </div>
                </div>
                <div class="col-md-6 col-md-offset-6">
                    <?php

// 1) Get the raw sum (number)
$processing_fee_raw = sum_from_table(
    db_prefix() . 'invoicepaymentrecords',
    [
        'field' => 'processing_fee',
        'where' => ['invoiceid' => $invoice->id],
    ]
);
$processing_fee_raw = (float) $processing_fee_raw;

if ($processing_fee_raw > 0) {
    // 2) Get latest payment record for this invoice
    $CI =& get_instance();
    $CI->db->order_by('id', 'DESC');
    $CI->db->limit(1);
    $last_payment = $CI->db->get_where(
        db_prefix() . 'invoicepaymentrecords',
        ['invoiceid' => $invoice->id]
    )->row();
//$display_subtotal = (float) $invoice->subtotal - $processing_fee_raw;
 
    if ($last_payment) {
        // In Perfex, for online gateways this is usually the gateway ID
        // e.g. 'senangpay', 'payhalal', 'stripe', etc.
        $gateway_id = $last_payment->paymentmode;

        // 3) Try to read configured fee percent for that gateway
        $fee_percent = (float) get_option('paymentmethod_' . $gateway_id . '_fee_percent');

        // Optional fallback: if nothing set in options but we have fee + amount,
        // try to infer the percent from the stored data.
        if ($fee_percent == 0 && isset($last_payment->amount)) {
            $base_amount = (float) $last_payment->amount - $processing_fee_raw;
            if ($base_amount > 0.01) {
                $fee_percent = round($processing_fee_raw / $base_amount * 100, 2);
            }
        }
    }
}
;?>
                    <table class="table text-right tw-text-normal">
                        <tbody>
                            <tr id="subtotal">
                                <td>
                                    <span
                                        class="bold tw-text-neutral-700"><?= _l('invoice_subtotal'); ?></span>
                                </td>
                                <td class="subtotal">
                                    <?= e(app_format_money(($invoice->subtotal - $processing_fee_raw), $invoice->currency_name)); ?>
                                </td>
                            </tr>
                            <?php if (is_sale_discount_applied($invoice)) { ?>
                            <tr>
                                <td>
                                    <span
                                        class="bold tw-text-neutral-700"><?= _l('invoice_discount'); ?>
                                        <?php if (is_sale_discount($invoice, 'percent')) { ?>
                                        (<?= e(app_format_number($invoice->discount_percent, true)); ?>%)
                                        <?php } ?></span>
                                </td>
                                <td class="discount">
                                    <?= e('-' . app_format_money($invoice->discount_total, $invoice->currency_name)); ?>
                                </td>
                            </tr>
                            <?php } ?>
                      

<?php if ($processing_fee_raw > 0) : ?>
    <tr class="tax-area">
        <td class="bold !tw-text-neutral-700">
           Processing fee (<?= e(app_format_number($fee_percent)); ?>%)
        </td>
        <td>
            <?= e(app_format_money($processing_fee_raw, $invoice->currency_name)); ?>
        </td>
    </tr>
<?php endif; ?>

                            <?php 
        foreach ($items->taxes() as $tax) {

            echo '<tr class="tax-area"><td class="bold !tw-text-neutral-700">' . e($tax['taxname']) . ' (' . e(app_format_number($tax['taxrate'])) . '%)</td><td>' . e(app_format_money($tax['total_tax'], $invoice->currency_name)) . '</td></tr>';
        }
?>
                            <?php if ((int) $invoice->adjustment != 0) { ?>
                            <tr>
                                <td>
                                    <span class="bold tw-text-neutral-700">
                                        <?= _l('invoice_adjustment'); ?>
                                    </span>
                                </td>
                                <td class="adjustment">
                                    <?= e(app_format_money($invoice->adjustment, $invoice->currency_name)); ?>
                                </td>
                            </tr>
                            <?php } ?>
                            <tr>
                                <td>
                                    <span
                                        class="bold tw-text-neutral-700"><?= _l('invoice_total'); ?></span>
                                </td>
                                <td class="total">
                                    <?= e(app_format_money($invoice->total, $invoice->currency_name)); ?>
                                </td>
                            </tr>
                            <?php if (count($invoice->payments) > 0 && get_option('show_total_paid_on_invoice') == 1) { ?>
                            <tr>
                                <td>
                                    <span class="bold tw-text-neutral-700">
                                        <?= _l('invoice_total_paid'); ?>
                                    </span>
                                </td>
                                <td>
                                    <?= e('-' . app_format_money(sum_from_table(db_prefix() . 'invoicepaymentrecords', ['field' => 'amount', 'where' => ['invoiceid' => $invoice->id]]), $invoice->currency_name)); ?>
                                </td>
                            </tr>
                            <?php } ?>
                            <?php if (get_option('show_credits_applied_on_invoice') == 1 && $credits_applied = total_credits_applied_to_invoice($invoice->id)) { ?>
                            <tr>
                                <td>
                                    <span
                                        class="bold tw-text-neutral-700"><?= _l('applied_credits'); ?></span>
                                </td>
                                <td>
                                    <?= e('-' . app_format_money($credits_applied, $invoice->currency_name)); ?>
                                </td>
                            </tr>
                            <?php } ?>
                            <?php if (get_option('show_amount_due_on_invoice') == 1 && $invoice->status != Invoices_model::STATUS_CANCELLED) { ?>
                            <tr>
                                <td>
                                    <span
                                        class="<?= $invoice->total_left_to_pay > 0 ? 'text-danger ' : ''; ?> bold">
                                        <?= _l('invoice_amount_due'); ?>
                                    </span>
                                </td>
                                <td>
                                    <span
                                        class="<?= $invoice->total_left_to_pay > 0 ? 'text-danger' : ''; ?>">
                                        <?= e(app_format_money($invoice->total_left_to_pay, $invoice->currency_name)); ?>
                                    </span>
                                </td>
                            </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
                <?php hooks()->do_action('after_total_summary_invoicehtml', $invoice); ?>
                <?php if (get_option('total_to_words_enabled') == 1) { ?>
                <div class="col-md-12 text-center invoice-html-total-to-words">
                    <p class="tw-font-medium">
                        <?= _l('num_word'); ?>:<span
                            class="tw-text-neutral-500">
                            <?= $this->numberword->convert($invoice->total, $invoice->currency_name); ?>
                        </span>
                    </p>
                </div>
                <?php } ?>
                <?php if (count($invoice->attachments) > 0 && $invoice->visible_attachments_to_customer_found == true) { ?>
                <div class="clearfix"></div>
                <div class="invoice-html-files">
                    <div class="col-md-12">
                        <hr />
                        <p><b><?= _l('invoice_files'); ?></b>
                        </p>
                    </div>
                    <?php foreach ($invoice->attachments as $attachment) {
                        // Do not show hidden attachments to customer
                        if ($attachment['visible_to_customer'] == 0) {
                            continue;
                        }
                        $attachment_url = site_url('download/file/sales_attachment/' . $attachment['attachment_key']);
                        if (! empty($attachment['external'])) {
                            $attachment_url = $attachment['external_link'];
                        } ?>
                    <div class="col-md-12 mbot10">
                        <div class="pull-left">
                            <i
                                class="<?= get_mime_class($attachment['filetype']); ?>"></i>
                        </div>
                        <a
                            href="<?= e($attachment_url); ?>"><?= e($attachment['file_name']); ?></a>
                    </div>
                    <?php
                    } ?>
                </div>
                <?php } ?>
                <?php if (! empty($invoice->clientnote)) { ?>
                <div class="col-md-12 invoice-html-note">
                    <p>
                        <b><?= _l('invoice_note'); ?></b>
                    </p>
                    <div class="tw-text-neutral-500 tw-mt-2.5">
                        <?= process_text_content_for_display($invoice->clientnote); ?>
                    </div>
                </div>
                <?php } ?>
                <?php if (! empty($invoice->terms)) { ?>
                <div class="col-md-12 invoice-html-terms-and-conditions">
                    <hr />
                    <p>
                        <b>
                            <?= _l('terms_and_conditions'); ?>
                        </b>
                    </p>
                    <div class="tw-text-neutral-500 tw-mt-2.5">
                        <?= process_text_content_for_display($invoice->terms); ?>
                    </div>
                </div>
                <?php } ?>
                <div class="col-md-12">
                    <hr />
                </div>
                <div class="col-md-12 invoice-html-payments">
                    <p>
                        <b><?= _l('invoice_received_payments'); ?></b>
                    </p>
                    <?php
               $total_payments = count($invoice->payments);

if ($total_payments > 0) { ?>
                    <table class="table table-hover invoice-payments-table tw-mt-2.5">
                        <thead>
                            <tr>
                                <th><?= _l('invoice_payments_table_number_heading'); ?>
                                </th>
                                <th><?= _l('invoice_payments_table_mode_heading'); ?>
                                </th>
                                <th><?= _l('invoice_payments_table_date_heading'); ?>
                                </th>
                                <th><?= _l('invoice_payments_table_amount_heading'); ?>
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($invoice->payments as $payment) { ?>
                            <tr>
                                <td>
                                    <span
                                        class="pull-left"><?= e($payment['paymentid']); ?></span>
                                    <?= form_open($this->uri->uri_string()); ?>
                                    <button type="submit"
                                        value="<?= e($payment['paymentid']); ?>"
                                        class="btn btn-icon btn-default pull-right" name="paymentpdf"><i
                                            class="fa-regular fa-file-pdf"></i></button>
                                    <?= form_close(); ?>
                                </td>
                                <td><?= e($payment['name']); ?>
                                    <?php if (! empty($payment['paymentmethod'])) {
                                        echo ' - ' . $payment['paymentmethod'];
                                    } ?>
                                </td>
                                <td><?= e(_d($payment['date'])); ?>
                                </td>
                                <td><?= e(app_format_money($payment['amount'], $invoice->currency_name)); ?>
                                </td>
                            </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                    <hr />
                    <?php } else { ?>
                    <h5 class="tw-font-medium tw-mt-0 tw-text-neutral-500">
                        <?= _l('invoice_no_payments_found'); ?>
                    </h5>
                    <div class="clearfix"></div>
                    <hr />
                    <?php } ?>
                </div>
                <?php
            // No payments for paid and cancelled
            if (($invoice->status != Invoices_model::STATUS_PAID
                                    && $invoice->status != Invoices_model::STATUS_CANCELLED
                                    && $invoice->total > 0)) { ?>
                <div class="col-md-12">
                    <div class="row">
                        <?php
                                          $found_online_mode = false;
                if (found_invoice_mode($payment_modes, $invoice->id, false)) {
                    $found_online_mode = true; ?>
                        <div class="col-md-6 text-left">
                            <p class="tw-mb-2.5 tw-font-medium">
                               
                                <label class="control-label" style="display:block;">Choose a payment method</label>
                            </p>

                            <?php
// Map gateway IDs to logos (put your images anywhere you like)
$gatewayIcons = [
  
  'paypal_checkout' => base_url('assets/custom/gateways/paypal-icon.jpg'),
  'payhalal'        => base_url('assets/custom/gateways/PayhalalLogo.png'),
  'senangpay'        => base_url('assets/custom/gateways/SenangpayLogo.png'),
];
?>


                            <?= form_open($this->uri->uri_string(), ['id' => 'online_payment_form', 'novalidate' => true]); ?>
                            

<div class="form-group" data-name="payment-gateways">
  <style>
      .gateway-fee-note{
        margin: 5px 0px;
  position: relative;
  cursor: pointer;
  padding: 0.7em 0.5em;
  border-radius: 0.25em;
  background-color: #e7f9f1;
  border: 1px solid #4cd496;
  font-size: 11px;
      }
  </style>

  <div class="gateway-grid">
    <?php foreach ($payment_modes as $mode): ?>
      <?php
        if (!is_numeric($mode['id']) && !empty($mode['id'])) {
          if (!is_payment_mode_allowed_for_invoice($mode['id'], $invoice->id)) { continue; }
          $gid   = e($mode['id']);
          $gname = e($mode['name']);
          $logo  = $gatewayIcons[$mode['id']] ?? base_url('assets/custom/gateways/generic-card.png');

           // 🔹 Get fee settings for this gateway
        $fee_fixed   = (float) get_option('paymentmethod_' . $gid . '_fee_fixed');
        $fee_percent = (float) get_option('paymentmethod_' . $gid . '_fee_percent');

         $feeLabel = '';
        if ($fee_fixed > 0 && $fee_percent > 0) {
            $feeLabel = 'Processing fee: ' .
                app_format_money($fee_fixed, $base_currency->name) . ' + ' .
                $fee_percent . '%';
        } elseif ($fee_fixed > 0) {
            $feeLabel = 'Processing fee: ' .
                app_format_money($fee_fixed, $base_currency->name);
        } elseif ($fee_percent > 0) {
            $feeLabel = 'Processing fee: ' . '+' . $fee_percent . '%';
        }
      ?>

        <!-- hide radio visually but keep it in the DOM for form submit -->
      <input
          type="radio"
          id="gw_<?= $gid; ?>"
          name="paymentmode"
          value="<?= $gid; ?>"
          style="position:absolute; left:-9999px;"
          required
          data-fee-fixed="<?= $fee_fixed; ?>"
          data-fee-percent="<?= $fee_percent; ?>"
      >
      <!-- hide radio visually but keep it in the DOM for form submit -->
      <input type="radio" id="gw_<?= $gid; ?>" name="paymentmode" value="<?= $gid; ?>"
             style="position:absolute; left:-9999px;" required>

      <label for="gw_<?= $gid; ?>" class="gateway-tile" tabindex="0" aria-label="<?= $gname; ?>">
        <img src="<?= $logo; ?>" alt="<?= $gname; ?>">
        <div class="gateway-name"><?= $gname; ?></div>
 <?php if ($feeLabel): ?>
          <div class="gateway-fee-note">
            <?= htmlspecialchars($feeLabel); ?>
          </div>
        <?php endif; ?>
      </label>
    <?php } endforeach; ?>
  </div>
</div>
<script>
(function($){
  $(function(){
    function markSelected(id){
      $('.gateway-tile').removeClass('is-selected');
      if (id) $('label[for="'+id+'"]').addClass('is-selected');
    }
    // on choose via click
    $(document).on('change', 'input[name="paymentmode"]', function(){
      markSelected(this.id);
    });
    // keyboard accessibility (Enter/Space)
    $(document).on('keydown', '.gateway-tile', function(e){
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        var forId = $(this).attr('for');
        var $radio = $('#'+forId);
        $radio.prop('checked', true).trigger('change');
      }
    });
    // pre-select if one is already checked (e.g., postback)
    var $checked = $('input[name="paymentmode"]:checked');
    if ($checked.length) markSelected($checked.attr('id'));
  });
})(window.jQuery);
</script>



<style>
.gateway-grid{display:flex;flex-wrap:wrap;gap:12px;margin-bottom:10px;}
.gateway-tile{
  border:1px solid #e5e5e5;border-radius:8px;background:#fff;
  padding:12px 16px;min-width:160px;cursor:pointer;text-align:center;
  transition:box-shadow .2s, transform .04s;
}
.gateway-tile:hover{box-shadow:0 3px 10px rgba(0,0,0,.08);transform:translateY(-1px);}
.gateway-tile img{max-width:130px;height:40px;object-fit:contain;display:block;margin:0 auto 6px;}
.gateway-name{font-size:13px;color:#555;}

/* highlight the selected tile */
.gateway-tile.is-selected{
  box-shadow:0 0 0 2px #0d6efd inset, 0 4px 12px rgba(13,110,253,.12);
  border-color:#0d6efd;
}

</style>


                            <div class="form-group mtop25">
                                <?php if (get_option('allow_payment_amount_to_be_modified') == 1) { ?>
                                <label for="amount"
                                    class="control-label"><?= _l('invoice_html_amount'); ?></label>
                                <div class="input-group">
                                    <input type="number" required
                                        max="<?= e($invoice->total_left_to_pay); ?>"
                                        data-total="<?= e($invoice->total_left_to_pay); ?>"
                                        name="amount" class="form-control"
                                        value="<?= e($invoice->total_left_to_pay); ?>">
                                    <span class="input-group-addon">
                                        <?= e($invoice->symbol); ?>
                                    </span>
                                </div>
                                 <!-- 👇 New: display-only “Amount incl. fee” (NO name attribute) -->
    <div class="input-group mtop10">
        <input type="text"
               id="amount_with_fee_display"
               class="form-control"
               readonly>
        <span class="input-group-addon">
            <?= e($invoice->symbol); ?>
        </span>
    </div>

    <small class="text-muted">
        <span id="amount_with_fee_note"></span>
    </small>
                                <?php } else {
                                    echo '<h4 class="bold mbot25">' . e(_l('invoice_html_total_pay', app_format_money($invoice->total_left_to_pay, $invoice->currency_name))) . '</h4>';
                                } ?>
                            </div>
                            <div id="pay_button">
                                <input id="pay_now" type="submit" name="make_payment" class="btn btn-success"
                                    value="<?= _l('invoice_html_online_payment_button_text'); ?>">
                            </div>
                            <input type="hidden" name="hash"
                                value="<?= e($hash); ?>">
                            <?= form_close(); ?>
                        </div>
                        <?php
                } ?>
                        <?php if (found_invoice_mode($payment_modes, $invoice->id)) { ?>
                        <div class="invoice-html-offline-payments <?php if ($found_online_mode == true) {
                            echo 'col-md-6 text-right';
                        } else {
                            echo 'col-md-12';
                        } ?>">
                            <p class="tw-mb-2.5 tw-font-medium">
                                <?= _l('invoice_html_offline_payment'); ?>
                            </p>
                            <?php foreach ($payment_modes as $mode) {
                                if (is_numeric($mode['id'])) {
                                    if (! is_payment_mode_allowed_for_invoice($mode['id'], $invoice->id)) {
                                        continue;
                                    } ?>
                            <p class="bold">
                                <?= e($mode['name']); ?>
                            </p>
                            <?php if (! empty($mode['description'])) { ?>
                            <div class="mbot15">
                                <?= process_text_content_for_display($mode['description']); ?>
                            </div>
                            <?php }
                            }
                            } ?>
                        </div>
                        <?php } ?>
                    </div>
                </div>
                <?php } ?>
            </div>
        </div>
    </div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
    var realAmountInput  = document.querySelector('input[name="amount"]');

    var displayInput     = document.getElementById('amount_with_fee_display');
    var noteSpan         = document.getElementById('amount_with_fee_note');

    if (!realAmountInput || !displayInput) {
        return;
    }

    // Base invoice amount – what should go to the gateway
    function getBaseTotal() {
        var v = parseFloat(realAmountInput.getAttribute('data-total'));
        if (!isNaN(v) && v > 0) return v;

        v = parseFloat(realAmountInput.value);
        return isNaN(v) ? 0 : v;
    }

    var baseTotal = getBaseTotal();

    var decimals = (window.app && app.options && app.options.decimal_places)
        ? app.options.decimal_places
        : 2;

    function formatAmount(val) {
        return val.toFixed(decimals);
    }

    function updateDisplayForGateway(radio) {
        var feeText = '';

        if (!radio) {
            displayInput.value = formatAmount(baseTotal);
            if (noteSpan) noteSpan.textContent = '';
            return;
        }

        var feeFixed   = parseFloat(radio.getAttribute('data-fee-fixed'))   || 0;
        var feePercent = parseFloat(radio.getAttribute('data-fee-percent')) || 0;

        var fee = 0;
        if (feeFixed > 0 || feePercent > 0) {
            fee = feeFixed;
            if (feePercent > 0) {
                fee += baseTotal * (feePercent / 100);
            }
        }

        var displayTotal = baseTotal + fee;

        // 👈 ONLY change the display field; do NOT touch realAmountInput.value
        displayInput.value = formatAmount(displayTotal);

        if (noteSpan) {
            if (fee > 0) {
                noteSpan.textContent = 'Amount to be charged (incl. processing fee).';
            } else {
                noteSpan.textContent = 'No processing fee for this payment method.';
            }
        }
    }

    // Handle gateway selection
    var radios = document.querySelectorAll('.gateway-grid input[name="paymentmode"]');
    radios.forEach(function (radio) {
        radio.addEventListener('change', function () {
            if (this.checked) {
                updateDisplayForGateway(this);
            }
        });
    });

    // Initial state – if a gateway is preselected
    var initiallyChecked = document.querySelector('.gateway-grid input[name="paymentmode"]:checked');
    updateDisplayForGateway(initiallyChecked);
});
</script>

<script>
    $(function() {
        new Sticky('[data-sticky]');
        var $payNowTop = $('.pay-now-top');
        if ($payNowTop.length && !$('#pay_now').isInViewport()) {
            $payNowTop.removeClass('hide');
            $('.pay-now-top').on('click', function(e) {
                e.preventDefault();
                $('html,body').animate({
                        scrollTop: $("#online_payment_form").offset().top
                    },
                    'slow');
            });
        }

        $('#online_payment_form').appFormValidator();

        var online_payments = $('.online-payment-radio');
        if (online_payments.length == 1) {
            online_payments.find('input').prop('checked', true);
        }
    });

</script>
<script>
    (function ($) {
  $(function () {
    $('#offline_payment').on('click', function (e) {
      e.preventDefault();
      $('#offlinePayment').modal({
        show: true,
        backdrop: 'static',  // remove if you want to allow click outside to close
        keyboard: true
      });
    });
  });
})(window.jQuery);

</script>
