<?= $this->extend('layout/main') ?>

<?= $this->section('content_header') ?>
<div class="row">
    <div class="col-sm-6"><h3 class="mb-0">Order</h3></div>
    <div class="col-sm-6">
        <ol class="breadcrumb float-sm-end">
        <li class="breadcrumb-item"><a href="<?=base_url()?>">Home</a></li>
        <li class="breadcrumb-item active" aria-current="page">Checkout</li>
        </ol>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('content') ?>
<div class="row mb-3 g-4">
    <div class="col-lg-12">
        
    </div>
</div>

<div class="checkout">
    <div class="row">
        <div class="col-lg-12">
            <div class="card mb-3">
                <div class="card-body d-flex justify-content-between flex-wrap gap-3">
                    <div>
                        <div class="title h4 mb-0">Checkout</div>
                        <div class="text-muted">Selesaikan pembayaran & simpan transaksi</div>
                    </div>
                    <div class="d-flex flex-wrap gap-4">
                        <div class="kv"><div class="k">Kode Order</div><div class="v" id="kode_order"><?=$order->kode_order?></div></div>
                        <div class="kv"><div class="k">Meja</div><div class="v" id="nama_meja"><?=$order->nama_meja?></div></div>
                        <div class="kv"><div class="k">Tanggal</div><div class="v" id="tanggal_order"><?=$order->tanggal_order?></div></div>
                        <div class="kv"><div class="k">Operator</div><div class="v" id="nama_operator"><?=$order->nama?></div></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-3">
        <div class="col-lg-7">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <div class="title h5 mb-0">Item Pesanan</div>
                        <button id="btnAddNote" class="btn btn-outline-secondary btn-sm d-none">Catatan Struk</button>
                    </div>
                    <div class="table-responsive">
                        <table class="table align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                            <th style="width:48px">#</th>
                            <th>Item</th>
                            <th class="text-center" style="width:96px">Qty</th>
                            <th class="text-end" style="width:140px">Harga</th>
                            <th class="text-end" style="width:150px">Subtotal</th>
                            </tr>
                        </thead>
                        <tbody id="tbody_items">
                            <tr><td colspan="5" class="text-center text-muted">Memuat...</td></tr>
                        </tbody>
                        </table>
                    </div>
                    <div class="mt-3 d-flex justify-content-between">
                        <div class="text-muted">Total item: <span id="total_qty" class="fw-bold">0</span></div>
                        <button id="btnKembali" class="btn btn-outline-primary">← Kembali ke Order</button>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-5">
            <div class="card">
                <div class="card-body">
                    <div class="title h5 mb-3">Ringkasan Pembayaran</div>

                    <div class="row mb-1">
                        <div class="col-6 text-muted">Subtotal</div>
                        <div class="col-6 text-end num" id="sub_total">Rp0</div>
                    </div>

                    <div class="row g-2 align-items-center">
                        <div class="col-6">
                            <div class="text-muted">Diskon</div>
                            <div class="small text-muted">Nominal / %</div>
                        </div>
                        <div class="col-6">
                            <div class="input-group input-group-sm">
                                <input type="number" class="form-control" id="diskon_nominal" placeholder="Rp">
                                <span class="input-group-text">/</span>
                                <input type="number" class="form-control" id="diskon_persen" placeholder="%">
                            </div>
                        </div>
                    </div>

                    <div class="row g-2 align-items-center mt-2">
                        <div class="col-6 text-muted">Pajak (%)</div>
                        <div class="col-6">
                            <div class="input-group input-group-sm">
                                <input type="number" class="form-control" id="pajak_persen" value="<?=$pajak->persen?>">
                                <span class="input-group-text">%</span>
                            </div>
                        </div>
                    </div>

                    <div class="row g-2 align-items-center mt-2">
                        <div class="col-6 text-muted">Service (%)</div>
                        <div class="col-6">
                            <div class="input-group input-group-sm">
                                <input type="number" class="form-control" id="service_persen" value="0">
                                <span class="input-group-text">%</span>
                            </div>
                        </div>
                    </div>

                    <div class="row g-2 align-items-center mt-2">
                        <div class="col-6 text-muted">Pembulatan</div>
                        <div class="col-6">
                            <select id="pembulatan" class="form-select form-select-sm">
                                <option value="0">Tidak ada</option>
                                <option value="100">Ke 100</option>
                                <option value="500">Ke 500</option>
                                <option value="1000">Ke 1.000</option>
                            </select>
                        </div>
                    </div>

                    <hr>
                    <div class="row"><div class="col-6 text-muted">Pajak (Rp)</div><div class="col-6 text-end num" id="pajak_nominal">Rp0</div></div>
                    <div class="row"><div class="col-6 text-muted">Service (Rp)</div><div class="col-6 text-end num" id="service_nominal">Rp0</div></div>
                    <div class="row"><div class="col-6 text-muted">Diskon (Rp)</div><div class="col-6 text-end num" id="diskon_fix">- Rp0</div></div>

                    <div class="row mt-2">
                        <div class="col-6"><strong>Total Akhir</strong></div>
                        <div class="col-6 text-end value-lg num" id="grand_total" data-grand="0">Rp0</div>
                    </div>

                    <hr>

                    <!-- METODE BAYAR -->
                    <div class="mb-2">
                        <label class="form-label">Metode Bayar</label>
                        <select id="pay_method" class="form-select">
                            <option value="cash">cash</option>
                            <option value="qris">qris</option>
                            <option value="debit">debit</option>
                            <option value="lainnya">lainnya</option>
                        </select>
                    </div>

                    <!-- CASH -->
                    <div id="cash_section" class="mt-2">
                        <label class="form-label">Bayar (Tunai)</label>
                        <div class="input-group">
                            <span class="input-group-text">Rp</span>
                            <input type="number" id="bayar_tunai" class="form-control" placeholder="Nominal bayar">
                            <button class="btn btn-outline-secondary" type="button" data-quick="50000">50K</button>
                            <button class="btn btn-outline-secondary" type="button" data-quick="100000">100K</button>
                            <button class="btn btn-outline-secondary" type="button" data-quick="200000">200K</button>
                        </div>
                        <div class="d-flex justify-content-between mt-2">
                            <div class="text-muted">Kembalian</div>
                            <div class="value value-lg num" id="kembalian">Rp0</div>
                        </div>
                    </div>

                    <!-- NON-CASH + BUKTI (UI SAJA) -->
                    <div id="noncash_section" class="mt-3" style="display:none">
                        <label class="form-label">Referensi (opsional)</label>
                        <input type="text" id="ref_no" class="form-control mb-3" placeholder="No approval / catatan">

                        <div class="uploader-area d-none">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <label class="form-label mb-0">Bukti Pembayaran (diunggah terpisah)</label>
                                <div class="btn-group">
                                    <button type="button" id="btnOpenUploader" class="btn btn-sm btn-outline-primary">Pilih / Upload</button>
                                    <button type="button" id="btnClearBukti" class="btn btn-sm btn-outline-secondary">Clear</button>
                                </div>
                            </div>

                            <!-- preview -->
                            <div class="mt-2">
                                <img id="preview_img" class="preview d-none" alt="Preview bukti">
                                <div id="preview_name" class="small text-muted"></div>
                            </div>
                        </div>
                    </div>

                    <div class="sticky-cta">
                        <div class="d-grid gap-2">
                            <button id="btnCheckout" class="btn btn-primary btn-xl">Simpan & Cetak Struk</button>
                            <button id="btnCetakstruk" class="btn btn-outline-success">Cetak Struk</button>
                            <button id="btnBatal" class="btn btn-outline-danger">Batalkan</button>
                        </div>
                    </div>

                    <div class="small text-muted mt-2">
                        * Pajak/Service dihitung dari subtotal setelah diskon. * Pembulatan membulatkan ke atas.
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal Catatan -->
<div class="modal fade" id="modalNote" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form class="modal-content" id="formNote">
      <div class="modal-header">
        <h5 class="modal-title">Catatan di Struk (opsional)</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
      </div>
      <div class="modal-body">
        <textarea class="form-control" id="note_text" rows="4" placeholder="Terima kasih telah berkunjung."></textarea>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal" type="button">Tutup</button>
        <button class="btn btn-primary" type="submit">Simpan Catatan</button>
      </div>
    </form>
  </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('page_script') ?>
<?= $this->include('layout/css/sweetalert') ?>
<?= $this->include('layout/js/sweetalert') ?>

<script>
(() => {
  const API_BASE = '<?= base_url() ?>order/';
  const ORDER_ID = '<?=$order->id_order?>';

  const fmtIDR = n => new Intl.NumberFormat('id-ID',{style:'currency',currency:'IDR',maximumFractionDigits:0}).format(Math.round(n||0));
  const parseNum = v => Math.max(0, Number(v||0));

  let state = { order_id: ORDER_ID, id_transaksi : "0", items: [], note:'', bukti:{ id:'', url:'', name:'' } };

  $(init);

  function init(){
    bindUI();
    if(!ORDER_ID){ alert('Order ID tidak ditemukan'); return; }
    loadOrder(ORDER_ID);
  }

  function bindUI(){
    $('#btnAddNote').on('click', () => new bootstrap.Modal('#modalNote').show());
    $('#formNote').on('submit', e => { e.preventDefault(); state.note = $('#note_text').val().trim(); bootstrap.Modal.getInstance('#modalNote')?.hide(); });

    $('#diskon_nominal, #diskon_persen, #pajak_persen, #service_persen, #pembulatan').on('input change', recalc);
    $('#pay_method').on('change', togglePaySection);

    $('#bayar_tunai').on('input', recalcChange);
    $('[data-quick]').on('click', function(){ const add=parseNum(this.dataset.quick); const cur=parseNum($('#bayar_tunai').val()); $('#bayar_tunai').val(cur+add); recalcChange(); });

    $('#btnKembali').on('click', () => history.back());
    $('#btnCheckout').on('click', submitCheckout);
    $('#btnBatal').on('click', batalTransaksi);
    $('#btnCetakstruk').on('click', cetakstruk);
    // uploader hooks (UI only)
    $('#btnOpenUploader').on('click', () => {
      // Trigger event agar skrip uploader-mu bisa buka dialog
      window.dispatchEvent(new CustomEvent('open-bukti-uploader', { detail:{ mount:'#uploader_mount' } }));
    });
    $('#btnClearBukti').on('click', clearBukti);
    $('#btnPreviewBukti').on('click', () => {
      const url = $('#bukti_url').val().trim();
      if(url){ setPreview(url, $('#preview_name').text() || 'bukti'); }
    });

    // global hook yang bisa dipanggil plupload-mu
    window.handleBuktiUploaded = ({id='', url='', name=''}) => {
      $('#bukti_id').val(id); $('#bukti_url').val(url);
      state.bukti = { id, url, name };
      setPreview(url, name);
    };
  }

  function clearBukti(){
    $('#bukti_id').val(''); $('#bukti_url').val('');
    state.bukti = {id:'', url:'', name:''};
    $('#preview_img').attr('src','').addClass('d-none');
    $('#preview_name').text('');
  }

  function setPreview(url, name){
    $('#preview_img').attr('src', url).removeClass('d-none');
    $('#preview_name').text(name || url);
  }

  function togglePaySection(){
    const pm = $('#pay_method').val();
    if(pm==='cash'){ $('#cash_section').show(); $('#noncash_section').hide(); }
    else { $('#cash_section').hide(); $('#noncash_section').show(); }
    recalcChange();
  }

  // ===== LOAD ITEMS =====
  async function loadOrder(id){
    try{
      const res = await fetch(`${API_BASE}get_order_items/${id}`);
      if(!res.ok) throw new Error('Gagal ambil data order');
      const data = await res.json();
      state.id_transaksi = data.transaksi.id_transaksi;
      state.items = data.items || [];
      renderItems();
      renderInputValue(data.transaksi);
      recalc();
      togglePaySection();
    }catch(e){ console.error(e); alert('Tidak dapat memuat item order.'); }
  }

  function renderItems(){
    const tbody = $('#tbody_items').empty();
    let totalQty = 0;
    if(state.items.length===0){
      tbody.append('<tr><td colspan="5" class="text-center text-muted">Tidak ada item.</td></tr>');
    }
    state.items.forEach((it,i)=>{
      const sub = (it.harga_jual||0)*(it.qty||0);
      totalQty += (it.qty||0);
      tbody.append(`
        <tr class="item-row">
          <td>${i+1}</td>
          <td><div class="fw-semibold">${it.nama_produk||it.kode_produk}</div><div class="text-muted small">${it.kode_produk||''}</div></td>
          <td class="text-center">${it.qty}</td>
          <td class="text-end num">${fmtIDR(it.harga_jual)}</td>
          <td class="text-end num">${fmtIDR(sub)}</td>
        </tr>
      `);
    });
    $('#total_qty').text(totalQty);
  }

  function renderInputValue(data){
    $('#diskon_nominal').val(data.diskon_nominal);
    $('#diskon_persen').val(data.diskon_persen);
    $('#pajak_persen').val(data.pajak_persen);
    $('#service_persen').val(data.service_persen);
    $('#pembulatan').val(data.pembulatan);
    $('#bayar_tunai').val(data.tunai);
    $('#pay_method').val(data.metode);
  }
  // ===== HITUNG =====
  function getSubtotal(){ return state.items.reduce((a,b)=> a + (b.harga_jual||0)*(b.qty||0), 0); }

  function recalc(){
    const sub = getSubtotal();
    const dNom = parseNum($('#diskon_nominal').val());
    const dPct = Math.min(100, parseNum($('#diskon_persen').val()));
    const pajakPct = parseNum($('#pajak_persen').val());
    const servicePct = parseNum($('#service_persen').val());

    const discPctRp = Math.round(sub*(dPct/100));
    const discTotal = Math.min(sub, discPctRp + dNom);
    const subAfter = Math.max(0, sub - discTotal);

    const pajakRp = Math.round(subAfter*(pajakPct/100));
    const serviceRp = Math.round(subAfter*(servicePct/100));

    let grand = subAfter + pajakRp + serviceRp;
    const step = parseNum($('#pembulatan').val());
    if(step>0){ const mod = grand % step; if(mod!==0) grand += (step - mod); }

    $('#sub_total').text(fmtIDR(sub));
    $('#pajak_nominal').text(fmtIDR(pajakRp));
    $('#service_nominal').text(fmtIDR(serviceRp));
    $('#diskon_fix').text('- ' + fmtIDR(discTotal));
    $('#grand_total').text(fmtIDR(grand)).data('grand', grand);
    recalcChange();
  }

  function recalcChange(){
    const pm = $('#pay_method').val();
    const grand = Number($('#grand_total').data('grand')||0);
    if(pm==='cash'){
      const bayar = parseNum($('#bayar_tunai').val());
      $('#kembalian').text(fmtIDR(Math.max(0, bayar - grand)));
    }else{
      $('#kembalian').text(fmtIDR(0));
    }
  }

  // ===== SUBMIT (JSON ONLY, TANPA FILE) =====
  async function submitCheckout(){
    const pm = $('#pay_method').val();
    const grand = Number($('#grand_total').data('grand')||0);
    if(pm==='cash'){
      const bayar = parseNum($('#bayar_tunai').val());
      if(bayar < grand){ alert('Nominal tunai kurang dari total.'); return; }
    }

    const sub = getSubtotal();
    const dNom = parseNum($('#diskon_nominal').val());
    const dPct = Math.min(100, parseNum($('#diskon_persen').val()));
    const pajakPct = parseNum($('#pajak_persen').val());
    const servicePct = parseNum($('#service_persen').val());
    const step = parseNum($('#pembulatan').val());

    const discPctRp = Math.round(sub*(dPct/100));
    const discTotal = Math.min(sub, discPctRp + dNom);
    const subAfter = Math.max(0, sub - discTotal);
    const pajakRp = Math.round(subAfter*(pajakPct/100));
    const serviceRp = Math.round(subAfter*(servicePct/100));
    let grandTotal = subAfter + pajakRp + serviceRp;
    if(step>0){ const mod = grandTotal % step; if(mod!==0) grandTotal += (step - mod); }

    const payload = {
      id_order: state.order_id,
      summary:{
        subtotal: sub, diskon_nominal: dNom, diskon_persen: dPct, diskon_total: discTotal,
        pajak_persen: pajakPct, pajak_nominal: pajakRp,
        service_persen: servicePct, service_nominal: serviceRp,
        pembulatan_step: step, grand_total: grandTotal
      },
      payment:{
        method: pm,
        bayar_tunai: pm==='cash'? parseNum($('#bayar_tunai').val()) : 0,
        kembalian:   pm==='cash'? Math.max(0, parseNum($('#bayar_tunai').val()) - grandTotal) : 0,
        reference:   pm!=='cash'? ($('#ref_no').val().trim()) : ''
      },
      // bukti:{
      //   id: $('#bukti_id').val() || state.bukti.id || '',
      //   url: $('#bukti_url').val().trim() || state.bukti.url || '',
      //   name: state.bukti.name || ''
      // },
      // note: state.note || '',
      // header_dummy:{
      //   kode_order: $('#kode_order').text(),
      //   meja: $('#nama_meja').text(),
      //   tanggal: $('#tanggal_order').text(),
      //   operator: $('#nama_operator').text()
      // }
    };

    try{
      Swal.fire({
          text: 'Processing.. Silahkan tunggu..',
          allowOutsideClick: false
      });
      Swal.showLoading();

      const res = await fetch(`${API_BASE}checkout_submit`, {
        method:'POST',
        headers:{ 'Content-Type':'application/json' },
        body: JSON.stringify(payload)
      });

      if(!res.ok) {
        if(res.statusText == 'data'){
          const resout = await res.json();
          Swal.fire({
              text:resout.messages.error,
              icon : 'error'
          }); 
          return;
        }else{
          throw new Error(res);
        }
      }

      const out = await res.json();
      state.id_transaksi = out.id_transaksi;
      Swal.fire({
          text:'Proses berhasil!',
          icon : 'success'
      }).then(function () {
          cetakstruk();
      });
    }catch(e){ 
      // console.log(e);
      Swal.fire({
                    text:'Terjadi kesalahan sistem!',
                    icon : 'error'
                }); 
    }
  }

  async function batalTransaksi(){
    Swal.fire({
        title:'Cancel Transaction..',
        html: '<p>Batalkan transaksi ini??</p>',
        showDenyButton: true,
        showCancelButton: true,
        confirmButtonText: 'Yes',
        denyButtonText: 'No',
    }).then((result) => {
      if (result.isConfirmed) {
          Swal.fire({
              text: 'Processing.. Silahkan tunggu..',
              allowOutsideClick: false
          });
          Swal.showLoading();

          let payload = { id_transaksi: state.id_transaksi };
          // console.log(state);
          $.ajax({
              url: `${API_BASE}/cancel_transaksi`,
              method: 'POST',
              data: JSON.stringify(payload),
              contentType: 'application/json',
              success: res => {
                  Swal.fire({
                      text:'Proses berhasil!',
                      icon : 'success'
                  }).then(function () {
                      document.location.href=`<?=base_url()?>order/checkout/${state.order_id}`;
                  });
              },
              error: (data) => {
                var pesan_error = 'Pembatalan gagal!';
                if(data.responseJSON.messages.error){
                  pesan_error = data.responseJSON.messages.error;
                }
                  Swal.fire({
                      text:pesan_error,
                      icon : 'error'
                  }); 
              }
          });
      }
    });
  }

  function cetakstruk(){
    openPrintPopup(`<?=base_url()?>/order/print_struk/${ORDER_ID}`, {
            width: 420,
            height: 640,
            autoClose: true
          });
  }
})();

function openPrintPopup(url, opts = {}) {
  const {
    width = 420,   // ukuran popup (px) — pas untuk preview struk 58mm
    height = 640,
    title = 'Print Struk',
    autoClose = true,   // tutup otomatis setelah print
    delay = 300         // jeda sebelum print (ms), memberi waktu render PDF/HTML
  } = opts;

  // Hitung posisi tengah (multi-monitor friendly)
  const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
  const dualScreenTop  = window.screenTop  !== undefined ? window.screenTop  : window.screenY;
  const w = window.innerWidth  || document.documentElement.clientWidth  || screen.width;
  const h = window.innerHeight || document.documentElement.clientHeight || screen.height;
  const left = dualScreenLeft + (w - width) / 2;
  const top  = dualScreenTop  + (h - height) / 2;

  const features = [
    'popup=yes',
    'toolbar=no',
    'location=no',
    'menubar=no',
    'status=no',
    'resizable=yes',
    'scrollbars=yes',
    `width=${width}`,
    `height=${height}`,
    `left=${left}`,
    `top=${top}`
  ].join(',');

  // Penting: panggil dari event user (onclick) agar tidak diblokir popup blocker
  const win = window.open(url, title, features);

  if (!win) {
    // Fallback jika popup diblokir
    alert('Popup diblokir browser. Izinkan popup untuk situs ini.');
    window.open(url, '_blank'); // buka tab biasa sebagai fallback
    return;
  }

  // Fokus & auto print saat konten siap
  const doPrint = () => {
    try {
      win.focus();
      win.print();
    } catch (e) {
      // Jika PDF viewer internal belum siap, coba lagi sebentar
      setTimeout(() => { try { win.focus(); win.print(); } catch(_){} }, 500);
    }
  };

  win.onload = () => setTimeout(doPrint, delay);

  // Tutup otomatis setelah print (kalau diizinkan browser)
  win.onafterprint = () => {
    if (autoClose) { try { win.close(); } catch(_){} }
    window.focus();
  };
}
</script>
<?= $this->endSection() ?>