<?php 
error_reporting(0);
date_default_timezone_set("Asia/Jakarta");
$tanggalSekarang = date("Y-m-d");
$jamSekarang = date("h:i a");

if (isset($_POST['simpan'])) {
  insert_transaksi();
} 
if (isset($_POST['update_qty'])) {
    global $koneksi;
    $id = (int)$_POST['id'];
    $action = $_POST['action'];
    $kdbarang = mysqli_real_escape_string($koneksi, $_POST['kdbarang']);
    $kasir_id = (int)$_SESSION['idkaskit'];
    
    $q = mysqli_query($koneksi, "SELECT jumlah_beli, total FROM transaksi_temp WHERE id='$id' AND kasir_id='$kasir_id'");
    $r = mysqli_fetch_array($q);
    if($r) {
        $harga_satuan = $r['total'] / $r['jumlah_beli'];
        $new_qty = ($action == 'plus') ? $r['jumlah_beli'] + 1 : $r['jumlah_beli'] - 1;
        if($new_qty > 0) {
            $new_total = $new_qty * $harga_satuan;
            mysqli_query($koneksi, "UPDATE transaksi_temp SET jumlah_beli='$new_qty', total='$new_total' WHERE id='$id'");
        } else {
            mysqli_query($koneksi, "DELETE FROM transaksi_temp WHERE id='$id'");
        }
    }
}
if (isset($_POST['checkout'])) {
    $total = $_POST['total'];
    $bayar = $_POST['bayar'];
    $kembalian = $_POST['kembalian'];
    $diskon = $_POST['diskon'] ?? 0;
    $no_inv = proses_checkout($total, $bayar, $kembalian, $diskon);
    header("location: fungsi/print.php?no_inv=" . urlencode($no_inv));
    exit;
}
  include 'comp/header.php'; ?> 
  
<?php
global $koneksi;
$kasir_id = (int)$_SESSION['idkaskit'];
?>

<style>
  body, html { overflow-y: auto !important; margin: 0; }
  .main-footer { display: none !important; }

  /* ── KASIR TWO-COLUMN LAYOUT ── */
  .kasir-page {
    display: flex;
    gap: 20px;
    align-items: flex-start;
    padding: 20px;
    min-height: calc(100vh - var(--topbar-h, 64px));
  }

  /* LEFT: product area — grows to fill space, scrolls naturally */
  .kasir-left {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  /* RIGHT: cart — sticky, compact */
  .kasir-right {
    width: 380px;
    flex-shrink: 0;
  }

  @media (min-width: 992px) {
    .kasir-right {
      position: sticky;
      top: calc(var(--topbar-h, 64px) + 20px);
      display: flex;
      flex-direction: column;
      max-height: calc(100vh - 40px);
    }
    .kasir-right .pm-card {
      display: flex;
      flex-direction: column;
      flex: 1;
      overflow: hidden;
    }
    .kasir-cart-items {
      min-height: 220px;
      max-height: 220px;
      overflow-y: auto !important;
    }
    .kasir-cart-footer {
      flex-shrink: 0;
    }
  }

  @media (max-width: 991px) {
    .kasir-page  { flex-direction: column; padding: 12px; }
    .kasir-right { width: 100%; }
    .kasir-cart-items { max-height: 45vh; overflow-y: auto !important; }
  }

  /* Product grid */
  .product-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(155px, 1fr));
    gap: 12px;
  }

  .product-card {
    border: 1px solid var(--border);
    border-radius: 12px;
    background: var(--surface);
    padding: 12px;
    display: flex;
    flex-direction: column;
    gap: 6px;
    transition: box-shadow 0.2s, transform 0.2s;
  }
  .product-card:hover {
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
  }
</style>

<div class="content-wrapper" style="background-color: var(--bg-main);">
  <div class="kasir-page">

    <!-- ═══════════════════════════════ LEFT: Search + Products ═══════════════════════════════ -->
    <div class="kasir-left">

      <!-- Search Box -->
      <div class="pm-card">
        <div class="pm-card-body" style="padding:14px 16px;">
          <form action="" method="POST" style="margin:0;">
            <div style="display:flex;gap:0;">
              <input type="text" class="form-control" autofocus name="cari"
                placeholder="Cari nama barang..."
                style="background:var(--surface-2);border-radius:10px 0 0 10px;border-right:none;font-size:0.9rem;height:40px;flex:1;">
              <button type="submit" name="go" class="btn btn-primary"
                style="border-radius:0 10px 10px 0;padding:0 18px;font-weight:600;height:40px;display:flex;align-items:center;">
                <i class="fas fa-search" style="margin-right:4px;"></i> Cari
              </button>
            </div>
          </form>

          <!-- Category Tabs -->
          <div style="margin-top:12px;display:flex;gap:8px;overflow-x:auto;padding-bottom:4px;-webkit-overflow-scrolling:touch;">
            <a href="index.php"
              class="btn btn-sm <?= !isset($_GET['kategori']) ? 'btn-primary' : 'btn-light' ?>"
              style="border-radius:20px;font-weight:600;white-space:nowrap;padding:4px 16px;">Semua</a>
            <?php
              $kat_query = mysqli_query($koneksi, "SELECT DISTINCT a.kategori as id_kat, b.kategori as nama_kat FROM tb_barang a JOIN tb_kat b ON a.kategori = b.id ORDER BY b.kategori ASC");
              while($k = mysqli_fetch_array($kat_query)):
                $active = (isset($_GET['kategori']) && $_GET['kategori'] == $k['id_kat']) ? 'btn-primary' : 'btn-light';
            ?>
              <a href="index.php?kategori=<?= urlencode($k['id_kat']) ?>"
                class="btn btn-sm <?= $active ?>"
                style="border-radius:20px;font-weight:600;white-space:nowrap;padding:4px 16px;"><?= $k['nama_kat'] ?></a>
            <?php endwhile; ?>
          </div>
        </div>
      </div>

      <!-- Product Results -->
      <div class="pm-card">
        <div class="pm-card-header">
          <span class="pm-card-title">
            <i class="fas fa-box-open" style="margin-right:8px;color:var(--primary);"></i>
            Hasil Pencarian
          </span>
        </div>
        <div class="pm-card-body">
          <?php
            if (isset($_POST['go']) && $_POST['cari'] != '') {
              $cari = mysqli_real_escape_string($koneksi, $_POST['cari']);
              $select_c = mysqli_query($koneksi, "SELECT tb_barang.*, tb_kat.kategori as nama_kategori FROM tb_barang LEFT JOIN tb_kat ON tb_barang.kategori = tb_kat.id WHERE nm_barang LIKE '%".$cari."%' OR kdbarang LIKE '%".$cari."%' ORDER BY nm_barang ASC");
            } elseif (isset($_GET['kategori']) && $_GET['kategori'] != '') {
              $kategori = (int)$_GET['kategori'];
              $select_c = mysqli_query($koneksi, "SELECT tb_barang.*, tb_kat.kategori as nama_kategori FROM tb_barang LEFT JOIN tb_kat ON tb_barang.kategori = tb_kat.id WHERE tb_barang.kategori='$kategori' ORDER BY nm_barang ASC");
            } else {
              $select_c = mysqli_query($koneksi, "SELECT tb_barang.*, tb_kat.kategori as nama_kategori FROM tb_barang LEFT JOIN tb_kat ON tb_barang.kategori = tb_kat.id ORDER BY nm_barang ASC");
            }
            $jml = mysqli_num_rows($select_c);
          ?>

          <?php if ($jml > 0): ?>
            <div class="product-grid">
              <?php foreach ($select_c as $res): ?>
              <div class="product-card">
                <!-- Header: kode + kategori -->
                <div style="display:flex;justify-content:space-between;align-items:center;">
                  <code style="font-size:0.68rem;color:var(--text-muted);"><?= $res['kdbarang']; ?></code>
                  <span style="background:var(--surface-2);padding:2px 6px;border-radius:4px;font-size:0.62rem;font-weight:700;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:58%;"
                    title="<?= isset($res['nama_kategori']) ? $res['nama_kategori'] : 'Umum'; ?>">
                    <?= isset($res['nama_kategori']) ? $res['nama_kategori'] : 'Umum'; ?>
                  </span>
                </div>
                <!-- Nama barang -->
                <div style="font-weight:700;color:var(--text-main);font-size:0.88rem;line-height:1.3;flex:1;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;">
                  <?= $res['nm_barang']; ?>
                </div>
                <!-- Harga -->
                <div style="font-weight:800;color:var(--primary);font-size:0.9rem;">
                  Rp <?= number_format($res['harga_jual'], 0, ',', '.'); ?>
                </div>
                <!-- Tombol Tambah -->
                <form action="" method="POST" style="margin:0;">
                  <input type="hidden" name="kdbarang"  value="<?= $res['kdbarang']; ?>">
                  <input type="hidden" name="nm_barang" value="<?= $res['nm_barang']; ?>">
                  <input type="hidden" name="kategori"  value="<?= isset($res['nama_kategori']) ? $res['nama_kategori'] : ''; ?>">
                  <input type="hidden" name="harga"     value="<?= $res['harga_jual']; ?>">
                  <input type="hidden" name="tanggal"   value="<?= $tanggalSekarang; ?>">
                  <input type="hidden" name="jam"       value="<?= $jamSekarang; ?>">
                  <input type="hidden" name="kasir"     value="<?= $key['nama']; ?>">
<button type="submit" name="simpan" class="btn btn-primary btn-sm w-100"
    style="border-radius:8px;padding:7px 0;font-weight:700;font-size:0.8rem;">
                    <i class="fas fa-plus" style="margin-right:4px;"></i> Tambah
                  </button>
                </form>
              </div>
              <?php endforeach; ?>
            </div>

          <?php else: ?>
            <div style="padding:60px 20px;text-align:center;color:var(--text-muted);">
              <i class="fas fa-box-open" style="font-size:2.5rem;margin-bottom:12px;opacity:0.3;display:block;"></i>
              <p style="margin:0;font-size:0.9rem;">Barang tidak ditemukan.</p>
            </div>
          <?php endif; ?>
        </div>
      </div>

    </div><!-- /kasir-left -->

    <!-- ═══════════════════════════════ RIGHT: Cart & Payment ═══════════════════════════════ -->
    <div class="kasir-right">
      <div class="pm-card" style="display:flex;flex-direction:column;">

        <!-- Cart Header -->
        <div class="pm-card-header" style="flex-shrink:0;padding:10px 16px;">
          <span class="pm-card-title" style="font-size:0.9rem;">
            <i class="fas fa-shopping-cart" style="margin-right:6px;color:var(--primary);"></i>
            Keranjang Pesanan
          </span>
          <div style="font-size:0.65rem;color:var(--text-muted);font-weight:500;">
            <i class="far fa-clock" style="margin-right:2px;"></i><?= $jamSekarang; ?>
          </div>
        </div>

        <!-- Cart Items (scrollable, compact) -->
        <div class="kasir-cart-items" style="padding:0;overflow-x:hidden;flex:1;">
          
          <?php 
            $select = mysqli_query($koneksi, "SELECT * FROM transaksi_temp WHERE kasir_id='$kasir_id'");
            if(mysqli_num_rows($select) > 0):
              foreach ($select as $krj):
          ?>
            <div style="display:flex;align-items:center;padding:6px 14px;border-bottom:1px solid var(--border);gap:4px;">
              <div style="flex:1;min-width:0;">
                <div style="font-weight:600;font-size:0.8rem;line-height:1.2;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text-main);">
                  <?= $krj['nm_barang']; ?>
                </div>
                <div style="font-size:0.7rem;color:var(--text-muted);margin-top:1px;">
                  @ Rp <?= number_format($krj['total']/$krj['jumlah_beli'], 0, ',', '.'); ?>
                </div>
              </div>
              <div style="display:flex;align-items:center;gap:2px;flex-shrink:0;">
                <form action="" method="POST" style="margin:0;display:flex;align-items:center;">
                  <input type="hidden" name="id" value="<?= $krj['id']; ?>">
                  <input type="hidden" name="kdbarang" value="<?= $krj['kdbarang']; ?>">
                  <input type="hidden" name="update_qty" value="1">
                  <button type="submit" name="action" value="minus" 
                    style="width:20px;height:20px;padding:0;border:1px solid var(--border);border-radius:4px;background:var(--surface-2);font-weight:700;color:var(--text-main);font-size:0.75rem;line-height:1;cursor:pointer;">−</button>
                  <span style="display:inline-block;width:20px;text-align:center;font-weight:700;font-size:0.78rem;"><?= $krj['jumlah_beli']; ?></span>
                  <button type="submit" name="action" value="plus"
                    style="width:20px;height:20px;padding:0;border:1px solid var(--border);border-radius:4px;background:var(--surface-2);font-weight:700;color:var(--text-main);font-size:0.75rem;line-height:1;cursor:pointer;">+</button>
                </form>
              </div>
              <div style="width:80px;flex-shrink:0;text-align:right;font-weight:700;font-size:0.78rem;color:var(--primary);white-space:nowrap;padding-right:6px;">
                <?= number_format($krj['total'], 0, ',', '.'); ?>
              </div>
              <div style="flex-shrink:0;">
                <a href="fungsi/delete.php?id=<?= $krj['id']; ?>" 
                  style="display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:4px;background:var(--danger-bg);color:var(--danger-text);font-size:0.55rem;text-decoration:none;">
                  <i class="fas fa-times"></i>
                </a>
              </div>
            </div>
          <?php 
              endforeach;
            else:
          ?>
            <?php for ($_e = 1; $_e <= 5; $_e++): ?>
            <div style="display:flex;align-items:center;padding:6px 14px;border-bottom:1px solid var(--border);gap:4px;opacity:0.2;">
              <div style="flex:1;"><div style="height:12px;width:60%;background:var(--border);border-radius:4px;"></div></div>
              <div style="display:flex;align-items:center;gap:2px;">
                <span style="width:20px;height:20px;background:var(--border);border-radius:4px;display:inline-block;"></span>
                <span style="width:20px;height:12px;background:var(--border);border-radius:3px;display:inline-block;"></span>
                <span style="width:20px;height:20px;background:var(--border);border-radius:4px;display:inline-block;"></span>
              </div>
              <div style="width:80px;height:12px;background:var(--border);border-radius:3px;margin-right:6px;"></div>
              <div style="width:18px;height:18px;background:var(--border);border-radius:4px;"></div>
            </div>
            <?php endfor; ?>
          <?php endif; ?>
        </div>

        <!-- Payment Footer (compact) -->
        <?php 
          $query = mysqli_query($koneksi, "SELECT sum(total) as jtotal FROM transaksi_temp WHERE kasir_id='$kasir_id'");
          $r = mysqli_fetch_array($query);
          $total_belanja = $r['jtotal'] ? $r['jtotal'] : 0;
        ?>
        <div class="kasir-cart-footer" style="background:var(--surface-2);padding:10px 14px 12px;border-top:1px solid var(--border);flex-shrink:0;">

          <!-- Total -->
          <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px;">
            <span style="font-size:0.8rem;font-weight:700;color:var(--text-secondary);">Total Tagihan</span>
            <span style="font-size:1.15rem;font-weight:800;color:var(--primary);white-space:nowrap;">
              Rp <?= number_format($total_belanja, 0, ',', '.'); ?>
            </span>
          </div>

          <!-- Baris Bayar + Kembali (sama panjang) -->
          <div style="display:flex;gap:6px;margin-bottom:4px;">
            <div style="flex:1;">
              <label style="font-size:0.6rem;font-weight:700;color:var(--text-muted);text-transform:uppercase;display:block;margin-bottom:2px;">Bayar (Rp)</label>
              <input type="text" id="inputBayar" class="form-control form-control-sm" placeholder="0" inputmode="numeric"
                style="font-size:0.85rem;font-weight:700;height:32px;border-radius:6px;padding:0 8px;width:100%;" oninput="hitungKembalian()">
            </div>
            <div style="flex:1;">
              <label style="font-size:0.6rem;font-weight:700;color:var(--text-muted);text-transform:uppercase;display:block;margin-bottom:2px;">Kembali</label>
              <input type="text" id="inputKembalian" readonly class="form-control form-control-sm"
                style="font-size:0.85rem;font-weight:700;height:32px;border-radius:6px;padding:0 8px;width:100%;background:var(--bg-main);color:var(--success-text);">
            </div>
          </div>

          <!-- Diskon di bawah -->
          <div style="margin-bottom:6px;">
            <label style="font-size:0.6rem;font-weight:700;color:var(--text-muted);text-transform:uppercase;display:block;margin-bottom:2px;">Diskon (Rp)</label>
            <input type="text" id="inputDiskon" class="form-control form-control-sm" placeholder="0" value="0"
              style="font-size:0.85rem;font-weight:700;height:32px;border-radius:6px;padding:0 8px;width:100%;" oninput="hitungKembalian()">
          </div>

          <!-- Quick amounts — klik tambah nominal -->
          <div style="display:flex;gap:4px;margin-bottom:6px;">
            <button type="button" class="btn btn-sm" onclick="tambahNominal(20000)"
              style="flex:1;padding:2px 0;font-size:0.65rem;height:24px;background:var(--bg-main);border:1px solid var(--border);border-radius:4px;font-weight:600;">20K</button>
            <button type="button" class="btn btn-sm" onclick="tambahNominal(50000)"
              style="flex:1;padding:2px 0;font-size:0.65rem;height:24px;background:var(--bg-main);border:1px solid var(--border);border-radius:4px;font-weight:600;">50K</button>
            <button type="button" class="btn btn-sm" onclick="tambahNominal(100000)"
              style="flex:1;padding:2px 0;font-size:0.65rem;height:24px;background:var(--bg-main);border:1px solid var(--border);border-radius:4px;font-weight:600;">100K</button>
            <button type="button" class="btn btn-sm" onclick="tambahNominal(500000)"
              style="flex:1;padding:2px 0;font-size:0.65rem;height:24px;background:var(--bg-main);border:1px solid var(--border);border-radius:4px;font-weight:600;">500K</button>
            <button type="button" class="btn btn-sm" onclick="setNominal(<?= $total_belanja ?>)"
              style="flex:1;padding:2px 0;font-size:0.65rem;height:24px;background:var(--accent-light);border:1px solid var(--accent);border-radius:4px;font-weight:700;color:var(--primary);">Pas</button>
          </div>

          <!-- Checkout -->
          <form action="" method="POST" id="formCheckout" style="margin:0;">
            <input type="hidden" name="total"      value="<?= $total_belanja; ?>">
            <input type="hidden" name="bayar"       id="hiddenBayar"     value="">
            <input type="hidden" name="kembalian"   id="hiddenKembalian" value="">
            <input type="hidden" name="diskon"      id="hiddenDiskon"    value="0">
            <button type="submit" name="checkout" id="btnCetak" class="btn btn-primary w-100" disabled
              style="height:38px;font-size:0.9rem;font-weight:700;border-radius:8px;display:flex;align-items:center;justify-content:center;gap:6px;text-align:center;">
              <i class="fas fa-print"></i> Cetak Struk &amp; Selesaikan
            </button>
          </form>
        </div>

      </div><!-- /pm-card -->
    </div><!-- /kasir-right -->

  </div><!-- /kasir-page -->
</div><!-- /content-wrapper -->

<script>
  const totalBelanja   = <?= $total_belanja ?>;
  const inputBayar     = document.getElementById('inputBayar');
  const inputKembalian = document.getElementById('inputKembalian');
  const hiddenBayar    = document.getElementById('hiddenBayar');
  const hiddenKembalian= document.getElementById('hiddenKembalian');
  const hiddenDiskon   = document.getElementById('hiddenDiskon');
  const btnCetak       = document.getElementById('btnCetak');
  const inputDiskon    = document.getElementById('inputDiskon');

  function getNumeric(val) { return parseInt(val.replace(/[^0-9]/g, '')) || 0; }
  function formatRibuan(val){ return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.'); }

  inputBayar.addEventListener('input', function() {
    var cursor = this.selectionStart;
    var prevLen = this.value.length;
    var raw = this.value.replace(/[^0-9]/g, '');
    var formatted = raw === '' ? '' : formatRibuan(raw);
    this.value = formatted;
    var diff = this.value.length - prevLen;
    this.setSelectionRange(cursor + diff, cursor + diff);
    hitungKembalian();
  });

  inputBayar.addEventListener('keydown', function(e) {
    if (e.key === 'Backspace') {
      var cursor = this.selectionStart;
      var val = this.value;
      if (cursor > 0 && val.charAt(cursor - 1) === '.') {
        this.value = val.slice(0, cursor - 1) + val.slice(cursor);
        this.setSelectionRange(cursor - 1, cursor - 1);
        e.preventDefault();
        hitungKembalian();
      }
    }
  });

  inputDiskon.addEventListener('input', function() {
    var cursor = this.selectionStart;
    var prevLen = this.value.length;
    var raw = this.value.replace(/[^0-9]/g, '');
    var formatted = raw === '' ? '' : formatRibuan(raw);
    this.value = formatted;
    var diff = this.value.length - prevLen;
    this.setSelectionRange(cursor + diff, cursor + diff);
    hitungKembalian();
  });

  inputDiskon.addEventListener('keydown', function(e) {
    if (e.key === 'Backspace') {
      var cursor = this.selectionStart;
      var val = this.value;
      if (cursor > 0 && val.charAt(cursor - 1) === '.') {
        this.value = val.slice(0, cursor - 1) + val.slice(cursor);
        this.setSelectionRange(cursor - 1, cursor - 1);
        e.preventDefault();
        hitungKembalian();
      }
    }
  });

  function setNominal(amount) {
    inputBayar.value = amount > 0 ? formatRibuan(amount) : '';
    hitungKembalian();
  }

  function tambahNominal(amount) {
    var current = getNumeric(inputBayar.value);
    var total = current + amount;
    inputBayar.value = formatRibuan(total);
    hitungKembalian();
  }

  function hitungKembalian() {
    var bayar = getNumeric(inputBayar.value);
    var diskon = getNumeric(inputDiskon.value);
    hiddenBayar.value = bayar;
    hiddenDiskon.value = diskon;
    var totalSetelahDiskon = Math.max(0, totalBelanja - diskon);
    if (totalBelanja === 0) {
      inputKembalian.value = '';
      hiddenKembalian.value = 0;
      btnCetak.disabled = true;
      return;
    }
    if (bayar >= totalSetelahDiskon) {
      var kembalian = bayar - totalSetelahDiskon;
      inputKembalian.value  = 'Rp ' + kembalian.toLocaleString('id-ID');
      hiddenKembalian.value = kembalian;
      btnCetak.disabled = false;
    } else {
      inputKembalian.value  = 'Kurang bayar';
      hiddenKembalian.value = 0;
      btnCetak.disabled = true;
    }
  }
</script>

<?php include 'comp/footer.php'; ?>

