<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<style>
:root {
  --primary: #4a90e2;
  --light-bg: #f8f9fa;
  --soft-border: #dcdcdc;
  --hover-bg: #e6f0ff;
  --success: #27ae60;
  --danger: #e74c3c;
}

body {
  background-color: var(--light-bg);
  color: #333;
}

.form-control, .form-select {
  border-radius: 0.5rem;
}

.table thead {
  background-color: var(--primary);
  color: white;
}

.btn {
  border-radius: 0.5rem;
}

#searchResult, #barcodeResult {
  max-height: 200px;
  overflow-y: auto;
  background-color: white;
  border: 1px solid var(--soft-border);
}

#searchResult div, #barcodeResult div {
  transition: background 0.2s;
}

#searchResult div:hover, #barcodeResult div:hover {
  background-color: var(--hover-bg);
}

@media (max-width: 768px) {
  h4, h5 { font-size: 1.2rem; }
  table { font-size: 0.85rem; }
  .btn { font-size: 0.85rem; padding: 6px 10px; }
  .modal-dialog { max-width: 95%; }
}
</style>

<div class="container-fluid py-3">
  <h4 class="mb-4 fw-semibold text-primary">🧾 Transaksi Penjualan</h4>

  <?php if (session()->getFlashdata('error')): ?>
    <div class="alert alert-danger"><?= session()->getFlashdata('error') ?></div>
  <?php endif; ?>

  <form action="<?= base_url('admin/sales/save') ?>" method="post" id="salesForm">
  <div class="row g-3">
    <div class="col-md-4">
      <label class="form-label">Scan Barcode</label>
      <input type="text" id="barcodeInput" class="form-control" placeholder="Scan barcode atau ketik manual" autocomplete="off">
      <div id="barcodeResult" class="position-absolute w-100 mt-1 shadow-sm rounded"></div>
    </div>
    <div class="col-md-4">
      <label class="form-label">Cari Nama Item</label>
      <input type="text" id="searchItemInput" class="form-control" placeholder="Ketik nama item">
      <div id="searchResult" class="position-absolute w-100 mt-1 shadow-sm rounded"></div>
    </div>
    <div class="col-md-4">
      <label class="form-label">Jenis Pesan</label>
      <select name="jenis_pesan" id="jenis_pesan" class="form-select" required>
        <option value="">-- Pilih --</option>
        <option value="dine_in">Dine In</option>
        <option value="take_away">Take Away</option>
      </select>
    </div>

    <div class="col-md-4 d-none" id="no_meja_group">
      <label class="form-label">No Meja</label>
      <input type="text" name="no_meja" id="no_meja" class="form-control" placeholder="Nomor meja">
    </div>

    <div class="col-md-4">
      <label class="form-label">Customer</label>
      <select name="customer_id" class="form-select">
        <option value="">Pilih Customer</option>
        <?php foreach ($customers as $c): ?>
          <option value="<?= $c['id'] ?>"><?= esc($c['nama']) ?></option>
        <?php endforeach; ?>
      </select>
      <input type="text" name="customer_manual" class="form-control mt-2" placeholder="Atau isi nama customer baru">
    </div>

    <div class="col-md-4">
      <label class="form-label">Metode Pembayaran</label>
      <select name="payment_method" class="form-select" required>
        <option value="cash">Cash</option>
        <option value="transfer">Transfer</option>
      </select>
    </div>
  </div>

  <hr class="my-4">

  <h5 class="mb-3">🛒 Daftar Item</h5>
  <div class="table-responsive">
    <table class="table table-bordered align-middle" id="item-table">
      <thead>
        <tr class="text-center">
          <th>Nama Item</th>
          <th>Qty</th>
          <th>Harga</th>
          <th>Subtotal</th>
          <th></th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </div>

  <div class="row justify-content-end mt-3">
    <div class="col-md-6">
      <div class="mb-2 d-flex justify-content-between">
        <span>Subtotal</span>
        <span id="subtotal-value">Rp 0</span>
      </div>
      <div class="mb-2 d-flex justify-content-between <?= $activeTax ? '' : 'd-none' ?>">
        <span>Pajak (<?= $activeTaxPercent ?>%)</span>
        <span id="tax-value">Rp 0</span>
      </div>
      <div class="mb-2 d-flex justify-content-between">
        <span>
          Diskon (%)
          <input type="number" class="form-control d-inline-block w-auto ms-2" id="diskon-input" value="0" min="0" max="100" style="width: 80px;">
        </span>
        <span id="diskon-value">Rp 0</span>
      </div>
      <hr>
      <div class="d-flex justify-content-between fw-bold fs-5">
        <span>Total Bayar</span>
        <span id="total-bayar-value" class="text-success">Rp 0</span>
      </div>

      <!-- ✅ Input hidden hanya satu kali -->
      <input type="hidden" name="subtotal" id="input-subtotal">
<input type="hidden" name="diskon_persen" id="input-diskon-persen">
<input type="hidden" name="diskon_nominal" id="input-diskon-nominal">
<input type="hidden" name="pajak_nominal" id="input-pajak-nominal">
<input type="hidden" name="total_final" id="input-total-final">
<input type="hidden" name="total" id="input-grand-total"> 
<input type="hidden" name="paid" id="input-paid">

    </div>
  </div>

  <div class="d-flex gap-2">
    <button type="button" class="btn btn-success" onclick="showSummaryModal()">💾 Simpan Transaksi</button>
    <button type="submit" id="realSubmit" class="d-none">Submit</button>
    <a href="<?= base_url('admin/sales/create') ?>" class="btn btn-outline-secondary">Batal</a>
  </div>
</form>


<!-- Modal Ringkasan -->
<div class="modal fade" id="summaryModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content shadow">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">💡 Ringkasan Transaksi</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3 <?= $activeTax ? '' : 'd-none' ?>">
          <label class="form-label">Pajak (%)</label>
          <input type="number" class="form-control" id="tax-rate" value="<?= $activeTaxPercent ?>" <?= $activeTax ? '' : 'readonly' ?>>
        </div>
        <div class="mb-3">
          <label class="form-label">Dibayar (Rp)</label>
          <input type="number" class="form-control" id="paid-amount" placeholder="Masukkan nominal">
        </div>
        <pre id="summaryContent" class="bg-light p-2 rounded border" style="font-family: monospace;"></pre>
        <div id="changeResult" class="text-success fw-bold mt-2"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-success w-100" onclick="submitTransaction()">✅ Simpan & Cetak</button>
      </div>
    </div>
  </div>
</div>

<script>
const items = <?= json_encode($items) ?>;
const itemTableBody = document.querySelector("#item-table tbody");
const activeTax = <?= $activeTax ? 'true' : 'false' ?>;
const activeTaxPercent = <?= (float) $activeTaxPercent ?>;

barcodeInput.addEventListener('input', () => {
    const keyword = barcodeInput.value.toLowerCase().trim();
    barcodeResult.innerHTML = '';
    if (keyword.length < 1) return;

    const found = items.filter(i => i.barcode.toLowerCase().includes(keyword));
    found.forEach(item => {
        const div = document.createElement('div');
        div.className = 'py-1 px-2 border-bottom';
        div.style.cursor = 'pointer';
        div.textContent = `${item.barcode} - ${item.nama}`;
        div.onclick = () => {
            addItemToTable(item);
            barcodeInput.value = '';
            barcodeResult.innerHTML = '';
        };
        barcodeResult.appendChild(div);
    });
});

searchItemInput.addEventListener('input', () => {
    const keyword = searchItemInput.value.toLowerCase();
    searchResult.innerHTML = '';
    if (keyword.length < 1) return;

    items.filter(i => i.nama.toLowerCase().includes(keyword)).forEach(item => {
        const div = document.createElement('div');
        div.className = 'py-1 px-2 border-bottom';
        div.style.cursor = 'pointer';
        div.textContent = `${item.nama} - Stok: ${item.stok}`;
        div.onclick = () => {
            addItemToTable(item);
            searchItemInput.value = '';
            searchResult.innerHTML = '';
        };
        searchResult.appendChild(div);
    });
});

document.addEventListener('click', e => {
    if (!searchResult.contains(e.target) && e.target !== searchItemInput) {
        searchResult.innerHTML = '';
    }
    if (!barcodeResult.contains(e.target) && e.target !== barcodeInput) {
        barcodeResult.innerHTML = '';
    }
});

document.getElementById('jenis_pesan').addEventListener('change', function () {
    const noMejaGroup = document.getElementById('no_meja_group');
    if (this.value === 'dine_in') {
        noMejaGroup.classList.remove('d-none');
        document.getElementById('no_meja').required = true;
    } else {
        noMejaGroup.classList.add('d-none');
        document.getElementById('no_meja').required = false;
        document.getElementById('no_meja').value = '';
    }
});

function addItemToTable(item) {
    const existing = [...itemTableBody.querySelectorAll('tr')].find(r => r.dataset.id == item.id);
    if (existing) {
        const qty = existing.querySelector('.qty');
        qty.value = parseInt(qty.value) + 1;
        updateSubtotal(existing);
        return;
    }

    const row = document.createElement('tr');
    row.dataset.id = item.id;
    row.innerHTML = `
        <td>${item.nama} - ${item.diskon}%<input type="hidden" name="item_id[]" value="${item.id}"></td>
        <td><input type="number" name="qty[]" class="form-control qty" value="1" min="1" required></td>
        <td><span>${formatRupiah(item.total_harga)}</span><input type="hidden" name="total_harga[]" value="${item.total_harga}"></td>
        <td class="subtotal" data-subtotal="${item.total_harga}">${formatRupiah(item.total_harga)}</td>
        <td><button type="button" class="btn btn-danger btn-sm" onclick="this.closest('tr').remove(); calculateTotal()">X</button></td>
    `;
    itemTableBody.appendChild(row);
    row.querySelector('.qty').addEventListener('input', () => updateSubtotal(row));
    calculateTotal();
}

function formatRupiah(number) {
    return new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR' }).format(number);
}

function updateSubtotal(row) {
    const qty = parseInt(row.querySelector('.qty').value) || 0;
    const harga = parseInt(row.querySelector('input[name="total_harga[]"]').value);
    const subtotal = qty * harga;
    row.querySelector('.subtotal').innerText = formatRupiah(subtotal);
    row.querySelector('.subtotal').dataset.subtotal = subtotal;
    calculateTotal();
}

function calculateTotal() {
    let subtotal = 0;
    document.querySelectorAll('.subtotal').forEach(s => {
        subtotal += parseInt(s.dataset.subtotal || 0);
    });

    const taxRate = activeTax ? parseFloat(activeTaxPercent) : 0;
    const pajak = subtotal * (taxRate / 100);

    const diskonPersen = parseFloat(document.getElementById('diskon-input')?.value || 0);
    const diskon = subtotal * (diskonPersen / 100);

    const totalFinal = subtotal + pajak - diskon;

    // Update tampilan
    document.getElementById('subtotal-value').innerText = formatRupiah(subtotal);
    document.getElementById('tax-value').innerText = formatRupiah(pajak);
    document.getElementById('diskon-value').innerText = formatRupiah(diskon);
    document.getElementById('total-bayar-value').innerText = formatRupiah(totalFinal);

    // Update input tersembunyi
    const setHidden = (id, val) => {
        const el = document.getElementById(id);
        if (el) el.value = val;
    };

    setHidden('input-subtotal', subtotal);
    setHidden('input-diskon-persen', diskonPersen);
    setHidden('input-diskon-nominal', diskon);
    setHidden('input-pajak-nominal', pajak);
    setHidden('input-total-final', totalFinal);
}


function showSummaryModal() {
    const rows = document.querySelectorAll('#item-table tbody tr');
    if (rows.length === 0) return alert('Belum ada item ditambahkan');

    let summary = '';
    let subtotal = 0;

    rows.forEach(row => {
        const nama = row.children[0].innerText.trim();
        const qty = row.querySelector('.qty').value;
        const harga = row.querySelector('input[name="total_harga[]"]').value;
        const subtotalItem = qty * harga;
        subtotal += subtotalItem;
        summary += `${nama.padEnd(15)} x${qty} = ${formatRupiah(subtotalItem)}\n`;
    });
    
    const taxRate = activeTax ? parseFloat(activeTaxPercent) : 0;
    const pajak = subtotal * (taxRate / 100);
    const diskonTransaksi = parseFloat(document.getElementById('diskon-input')?.value || 0);
    const diskonTotal = subtotal * (diskonTransaksi / 100);
    const totalBayar = subtotal - diskonTotal + pajak;

    summary += '\n-----------------------------\n';
    summary += `Subtotal       : ${formatRupiah(subtotal)}\n`;
    summary += `Pajak ${taxRate}%  : ${formatRupiah(pajak)}\n`;
    summary += `Diskon ${diskonTransaksi}%: ${formatRupiah(diskonTotal)}\n`;
    summary += `TOTAL          : ${formatRupiah(totalBayar)}`;

    document.getElementById('summaryContent').innerText = summary;
    document.getElementById('changeResult').innerText = '';
    new bootstrap.Modal(document.getElementById('summaryModal')).show();
    calculateTotal();
}

function submitTransaction() {
    const paid = parseInt(document.getElementById('paid-amount')?.value);
    const total = parseInt(document.getElementById('input-total-final')?.value || 0);

    if (isNaN(paid) || paid < total) {
        alert('Nominal dibayar tidak cukup.');
        return;
    }

    const kembalian = paid - total;
    document.getElementById('input-paid').value = paid;
    document.getElementById('changeResult').innerText = 'Kembalian: Rp ' + formatRupiah(kembalian);

    setTimeout(() => {
        document.getElementById('realSubmit').click();
    }, 500);
}

// Cetak otomatis setelah simpan
<?php if ($print_sale_id): ?>
window.onload = function () {
    const isAndroid = /android/i.test(navigator.userAgent);
    const printUrl = "<?= base_url('admin/sales/print/' . $print_sale_id) ?>";
    window.open(printUrl, '_blank');
};
<?php endif; ?>

document.getElementById('diskon-input').addEventListener('input', calculateTotal);
</script>


<style>
#searchResult, #barcodeResult {
    max-height: 200px;
    overflow-y: auto;
    border: 1px solid #ddd;
}
@media (max-width: 768px) {
    h4, h5 { font-size: 1.2rem; }
    table { font-size: 0.85rem; }
    .btn { font-size: 0.85rem; padding: 6px 10px; }
}
</style>

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