
<?php include 'template/header.php';?>
<?php $barang=mysqli_query($conn, "SELECT * FROM barang");
$jsArray = "var harga_barang = new Array();"; 
$jsArray1 = "var kode_barang = new Array();"; 
 ?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
 <link rel="icon" type="image/png" href="assets/img/kasir.ico">
<style>
  body {
    background: linear-gradient(to left, #b3d9ff, #e6f2ff);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    background-attachment: fixed;
  }

  /* Agar card dan konten tetap terbaca */
  .card {
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 10px;
  }

  .card-header {
    background-color: rgba(111, 66, 193, 0.9); /* Tetap pakai bg-purple tapi transparan */
  }
  /* Hilangkan spinner (panah atas bawah) pada input number di Chrome, Safari, Edge */
    input[type=number]::-webkit-outer-spin-button,
    input[type=number]::-webkit-inner-spin-button {
        -webkit-appearance: none;
        margin: 0;
    }

    /* Hilangkan spinner di Firefox */
    input[type=number] {
        -moz-appearance: textfield;
    }
</style>

  <div class="col-md-9 mb-2">
    <div class="row">

    <!-- kasir -->
    <div class="col-md-6 mb-3">
        <div class="card">
            <div class="card-body py-4">
            <form method="POST">
            <div class="form-group row mb-0">
                        <label class="col-sm-4 col-form-label col-form-label-sm"><b>Tgl. Transaksi</b></label>
                        <div class="col-sm-8 mb-2">
                            <input type="date" class="form-control form-control-sm" name="tgl_input" value="<?php echo date('Y-m-d'); ?>" readonly>
                        </div>
                        <label class="col-sm-4 col-form-label col-form-label-sm"><b>Kode Barang</b></label>
                        <div class="col-sm-8 mb-2">
                            <input type="text" class="form-control form-control-sm" name="id_barang" id="id_barang" readonly>
                        </div>
                      <label class="col-sm-4 col-form-label col-form-label-sm"><b>Nama Barang</b></label>
                        <div class="col-sm-8 mb-2">
                            <div class="input-group">
                                <select name="nama_barang" class="form-control form-control-sm border-right-0" onchange="changeValue(this.value)" required>
                                    <option value="" selected disabled hidden>-- Pilih Barang --</option>
                                    <?php if(mysqli_num_rows($barang) > 0) { ?>
                                        <?php while($row_brg = mysqli_fetch_array($barang)) { ?>
                                            <option value="<?php echo $row_brg["nama_barang"]; ?>">
                                                <?php echo $row_brg["nama_barang"]; ?>
                                            </option>
                                        <?php 
                                            $jsArray .= "harga_barang['" . $row_brg['nama_barang'] . "'] = {harga_barang:'" . addslashes($row_brg['harga_barang']) . "'};";
                                            $jsArray1 .= "kode_barang['" . $row_brg['nama_barang'] . "'] = {id_barang:'" . addslashes($row_brg['id_barang']) . "'};";
                                        } ?>
                                    <?php } ?>
                                </select>
                                <div class="input-group-append">
                                    <span class="input-group-text bg-white border-left-0" id="basic-addon2" style="border-radius:0px 15px 15px 0px;">
                                        <img src="https://www.bumiqu.org/wp-content/uploads/2020/03/icon-penjualan-png-2-300x244.png" width="15" height="15" alt="Icon Penjualan">
                                    </span>
                                </div>
                            </div>
                        </div>
                        <label class="col-sm-4 col-form-label col-form-label-sm"><b>Harga</b></label>
                        <div class="col-sm-8 mb-2">
                            <input type="number" class="form-control form-control-sm" id="harga_barang" onchange="total()"
                             value="<?php echo $row['harga_barang'];?>" name="harga_barang" readonly>
                        </div>
                       <label class="col-sm-4 col-form-label col-form-label-sm"><b>Quantity</b></label>
                        <div class="col-sm-8 mb-2">
                            <div class="input-group input-group-sm">
                                <div class="input-group-prepend">
                                    <button class="btn btn-purple text-white" type="button" onclick="changeQty(-1)">
                                        <i class="fas fa-minus"></i>
                                    </button>
                                </div>
                                <input type="number" class="form-control" id="quantity" name="quantity" placeholder="0" required onchange="total()" min="0">
                                <div class="input-group-append">
                                    <button class="btn btn-purple text-white" type="button" onclick="changeQty(1)">
                                        <i class="fas fa-plus"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <label class="col-sm-4 col-form-label col-form-label-sm"><b>Diskon</b></label>
                        <div class="col-sm-8 mb-2">
                          <input type="number" class="form-control form-control-sm" id="diskon" name="diskon" onchange="total()" placeholder="0">
                        </div>
                        <label class="col-sm-4 col-form-label col-form-label-sm"><b>Sub-Total</b></label>
                        <div class="col-sm-8">
                            <div class="input-group">
                            <input type="text" class="form-control form-control-sm"  id="subtotal" name="subtotal" onchange="total()"
                             name="sub_total" readonly>
                            <div class="input-group-append">
                                <button class="btn btn-purple btn-sm" name="save" value="simpan" type="submit">
                                    <i class="fa fa-plus mr-2"></i>Tambah</button>
                            </div>
                            </div>
                        </div>
                    </div> 
            </form>
            <?php
                if (isset($_POST['save'])) {
                $idb = $_POST['id_barang'];
                $nama = $_POST['nama_barang'];
                $harga = $_POST['harga_barang'];
                $qty = $_POST['quantity'];
                $diskon = $_POST['diskon'];
                $total = $_POST['subtotal'];
                $tgl = $_POST['tgl_input'];
                    // MODIFIKASI: Cek ketersediaan stok sebelum menambahkan ke keranjang
                $cek_stok = mysqli_query($conn, "SELECT stok_barang FROM barang WHERE id_barang = '$idb'");
                $data_stok = mysqli_fetch_assoc($cek_stok);

                    if ($qty > $data_stok['stok_barang']) {
                    echo '<script>alert("Stok barang tidak cukup!");window.location=""</script>';
                    } else {
                    $sql = "INSERT INTO keranjang (kode_barang, nama_barang, harga_barang, quantity, diskon, subtotal, tgl_input)
                    VALUES('$idb','$nama','$harga','$qty','$diskon','$total','$tgl')";
                    $query = mysqli_query($conn, $sql) or die (mysqli_error($conn));
                    
                    if($query){
                    echo '<script>window.location=""</script>';
                    } else {
                    echo "Error :".$sql."<br>".mysqli_error($conn);
                    }
                }
                    // mysqli_close($conn); // MODIFIKASI: Jangan tutup koneksi di tengah skrip
                    }?>
            <hr>
            <?php 

function format_ribuan ($nilai){
    return number_format ($nilai, 0, ',', '.');
}
                $tgl = date("jmYGi");
                $huruf = "AD";
                $kodeCart = $huruf . $tgl;
                ?>
                <?php
                $query = mysqli_query($conn, "SELECT * FROM keranjang");
                $total = 0;
                $tot_bayar = 0;
                $total_diskon = 0;
                $no = 1;
                while ($r = $query->fetch_assoc()) {
                    $harga = $r['harga_barang'];
                    $qty = $r['quantity'];
                    $diskon = isset($r['diskon']) && is_numeric($r['diskon']) ? floatval($r['diskon']) : 0;
                    $subtotal = ($harga * $qty) - $diskon;
                    if ($subtotal < 0) $subtotal = 0;
                    $total_diskon += $diskon;
                    $tot_bayar += $subtotal;
                    $bayar = $r['bayar'];
                    $kembalian = $r['kembalian'];
                }
             error_reporting(0);
                ?>
            <form method="POST">
                <div class="form-group row mb-0">
                <input type="hidden" class="form-control" name="no_transaksi" value="<?php echo $kodeCart; ?>" readonly>
                <input type="hidden" class="form-control" value="<?php echo $tot_bayar; ?>" id="hargatotal" readonly>
                    <label class="col-sm-4 col-form-label col-form-label-sm"><b>Bayar</b></label>
                        <div class="col-sm-8 mb-2">
                            <input type="number" class="form-control form-control-sm"
                            name="bayar" id="bayarnya" onchange="totalnya()">
                    </div>
                    <label class="col-sm-4 col-form-label col-form-label-sm"><b>Kembali</b></label>
                        <div class="col-sm-8 mb-2">
                            <input type="number" class="form-control form-control-sm"
                            name="kembalian" id="total1" readonly>
                    </div>
                </div>
                <div class="text-right">
                <button class="btn btn-purple btn-sm" name="save1" value="simpan" type="submit">
                    <i class="fa fa-shopping-cart mr-2"></i>Bayar</button> 
                </div>
            </form>
            <?php
            if(isset($_POST['save1'])){
                $notrans = $_POST['no_transaksi'];
                $bayar = $_POST['bayar'];
                $kembalian = $_POST['kembalian'];

                $sql = "UPDATE keranjang SET no_transaksi='$notrans',bayar='$bayar',kembalian='$kembalian' ";
                $query = mysqli_query($conn, $sql) or die (mysqli_error());
                echo '<script>window.location="index.php"</script>';

            }?>  
            </div>
        </div>
    </div>
    <!-- end kasir -->

  <!-- tes -->
  <div class="col-md-6 mb-3">
      <div class="card" id="print">
          <div class="card-header bg-white border-0 pb-0 pt-4">
              <?php 
      $toko = mysqli_query($conn,"SELECT * FROM login ORDER BY nama_toko ASC");
      while($dat = mysqli_fetch_array($toko)){
        $user = $dat['user'];
        $nama_toko = $dat['nama_toko'];
        $alamat = $dat['alamat'];
        $telp = $dat['telp'];
        echo "<h5 class='card-tittle mb-0 text-center'><b>$nama_toko</b></h5>
        <p class='m-0 small text-center'>$alamat</p>
          <p class='small text-center'>Telp. $telp</p>";
      }
          ?>
          <div class="row">
              <div class="col-8 col-sm-9 pr-0">
                <ul class="pl-0 small" style="list-style: none;text-transform: uppercase;">
                    <li>NOTA : <?php 
      $notrans = mysqli_query($conn,"SELECT * FROM keranjang ORDER BY no_transaksi ASC LIMIT 1");
      while($dat2 = mysqli_fetch_array($notrans)){
        $notransaksi = $dat2['no_transaksi'];
        echo "$notransaksi";
      }
          ?></li>
                    <li>KASIR : <?php echo $user ?></li>
                </ul>
              </div>
              <div class="col-4 col-sm-3 pl-0">
              <ul class="pl-0 small" style="list-style: none;">
                    <li>TGL : <?php echo  date("d-m-y");?></li>
                    <li>JAM : <?php echo  date("G:i:s");?></li>
                </ul>
              </div>
          </div>
          </div>
          <div class="card-body small pt-0">
          <hr class="mt-0">
              <div class="row">
              <div class="col-5 pr-0">
                    <span><b>Nama Barang</b></span>
              </div>
              <div class="col-1 px-0 text-center">
                  <span><b>Qty</b></span>
              </div>
              <div class="col-3 px-0 text-right">
                  <span><b>Harga</b></span>
              </div>
              <div class="col-3 pl-0 text-right">
                  <span><b>Subtotal</b></span>
              </div>
              <div class="col-12">
                  <hr class="mt-2">
              </div>
              <?php 
                $data_barang = mysqli_query($conn,"SELECT * FROM keranjang");
                while($d = mysqli_fetch_array($data_barang)){
                    ?>
             <div class="col-5 pr-0">
                <a href="?id=<?php echo $d['id_cart']; ?>" 
                onclick="javascript:return confirm('Hapus Data Barang ?');" 
                style="text-decoration:none;">
                    <i class="fa fa-times fa-xs text-danger mr-1"></i>
                    <span class="text-dark"><?php echo $d['nama_barang']; ?></span>
                </a>
            </div>

            <div class="col-1 px-0 text-center">
                <span><?php echo $d['quantity']; ?></span>
            </div>

            <div class="col-3 px-0 text-right">
                <span><?php echo format_ribuan($d['harga_barang']); ?></span>
                    <div style="font-size: 12px; color: #555;">Disc:</div>
            </div>

            <div class="col-3 pl-0 text-right">
                <span><?php echo format_ribuan($d['subtotal']); ?></span>
                   <div style="font-size: 12px; color: #555;">
                        <?php echo ($d['diskon'] > 0) ? format_ribuan($d['diskon']) : 0; ?>
                   </div>
            </div>
              <?php }?>
              <div class="col-12">
                  <hr class="mt-2">
                    <ul class="list-group border-0">
                    <li class="list-group-item p-0 border-0 d-flex justify-content-between align-items-center">
                        <b>Diskon</b>
                        <span><b><?php echo format_ribuan($total_diskon); ?></b></span>
                    </li>
                    <li class="list-group-item p-0 border-0 d-flex justify-content-between align-items-center">
                        <b>Total</b>
                        <span><b><?php echo format_ribuan($tot_bayar); ?></b></span>
                    </li>
                    <li class="list-group-item p-0 border-0 d-flex justify-content-between align-items-center">
                        <b>Bayar (cash)</b>
                        <span><b><?php echo format_ribuan($bayar); ?></b></span>
                    </li>
                    <li class="list-group-item p-0 border-0 d-flex justify-content-between align-items-center">
                        <b>Kembalian</b>
                        <span><b><?php echo format_ribuan($kembalian); ?></b></span>
                    </li>
                    </ul>
              </div>
              <div class="col-sm-12 mt-3 text-center">
                  <p>* TERIMA KASIH TELAH BERBELANJA DITOKO KAMI*</p>
              </div>
              </div>
          </div>
      </div>
      <div class="text-right mt-3">
          <form method="POST">
            <a href="javascript:void(0);" id="whatsapp-link" class="btn btn-purple-light btn-sm mr-2" onclick="sendWhatsApp();"><i class="fa fa-whatsapp  mr-1"></i> WhatsApp</a>
            <a href="print.php" target="_blank" class="btn btn-purple-light btn-sm mr-2"><i class="fa fa-print mr-1"></i> Print</a>
            <button class="btn btn-purple btn-sm" name="selesai" type="submit"><i class="fa fa-check mr-1"></i> Selesai</button>
          </form>
      </div>
    <?php
    if (isset($_POST['selesai'])) {
        // Kurangi stok barang berdasarkan data dari keranjang
        $items_di_keranjang = mysqli_query($conn, "SELECT kode_barang, quantity FROM keranjang");
        while ($item = mysqli_fetch_assoc($items_di_keranjang)) {
            $kode_barang_update = $item['kode_barang'];
            $qty_terjual = $item['quantity'];

            // Update stok
            $update_stok = "UPDATE barang SET stok_barang = stok_barang - '$qty_terjual' WHERE id_barang = '$kode_barang_update'";
            mysqli_query($conn, $update_stok) or die(mysqli_error($conn));
        }

        // Simpan semua data dari keranjang ke laporanku (termasuk diskon)
        $simpan_ke_laporan = mysqli_query($conn, "
            INSERT INTO laporanku (
                no_transaksi, bayar, kembalian, id_cart, kode_barang, 
                nama_barang, harga_barang, quantity, diskon, subtotal, tgl_input
            )
            SELECT 
                no_transaksi, bayar, kembalian, id_cart, kode_barang, 
                nama_barang, harga_barang, quantity, diskon, subtotal, tgl_input
            FROM keranjang
        ") or die(mysqli_error($conn));

        // Kosongkan isi keranjang
        $hapus_keranjang = mysqli_query($conn, "DELETE FROM keranjang") or die(mysqli_error($conn));

        // Redirect ke halaman utama
        echo '<script>window.location="index.php"</script>';
    }
?>
  </div>
  <!-- end tes -->

    <?php 
	include 'config.php';
	if(!empty($_GET['id'])){
		$id= $_GET['id'];
		$hapus_data = mysqli_query($conn, "DELETE FROM keranjang WHERE id_cart ='$id'");
		echo '<script>window.location="index.php"</script>';
	}

?>
    </div><!-- end row col-md-9 -->
  </div>
  <script type="text/javascript">
      <?php echo $jsArray; ?>
      <?php echo $jsArray1; ?>
    function changeValue(nama_barang) {
        document.getElementById("harga_barang").value = harga_barang[nama_barang].harga_barang;
        // MODIFIKASI: Ubah id_barang menjadi kode_barang agar sesuai dengan JS Array
        document.getElementById("id_barang").value = kode_barang[nama_barang].id_barang;
  };

function changeQty(delta) {
    const qtyInput = document.getElementById("quantity");
    let current = parseInt(qtyInput.value) || 0;
    let newValue = current + delta;
    if (newValue < 0) newValue = 0;
    qtyInput.value = newValue;
    total();
}

function total() {
  var harga = parseInt(document.getElementById('harga_barang').value) || 0;
  var jumlah = parseInt(document.getElementById('quantity').value) || 0;
  var diskon = parseInt(document.getElementById('diskon').value) || 0;
  var subtotal = harga * jumlah; // Subtotal tidak dikurangi diskon
  document.getElementById('subtotal').value = subtotal;
}
    
  function totalnya() {
   var harga =  parseInt(document.getElementById('hargatotal').value);
   var pembayaran =  parseInt(document.getElementById('bayarnya').value);
   var kembali = pembayaran - harga;
    document.getElementById('total1').value = kembali;
  }

  function printContent(print){
			var restorepage = document.body.innerHTML;
			var printcontent = document.getElementById(print).innerHTML;
			document.body.innerHTML = printcontent;
			window.print();
			document.body.innerHTML = restorepage;
		}
        // Tambahkan ini sebelum fungsi sendWhatsApp()
    function str_pad(input, pad_length, pad_string = ' ', pad_type = 'STR_PAD_RIGHT') {
    input = input.toString();
    if (pad_type === 'STR_PAD_LEFT') {
        return input.padStart(pad_length, pad_string);
    } else {
        return input.padEnd(pad_length, pad_string);
    }
    }

        function sendWhatsApp() {
        let toko = "<?php echo $nama_toko; ?>";
        let alamatToko = "<?php echo $alamat; ?>";
        let telpToko = "<?php echo $telp; ?>";
        let nota = "<?php echo $notransaksi; ?>";
        let kasir = "<?php echo $user; ?>";
        let tanggal = "<?php echo date('d-m-Y'); ?>";
        let jam = "<?php echo date('H:i:s'); ?>";

        // Fungsi center teks di WhatsApp
        function centerText(text, width = 45) {
            let pad = Math.floor((width - text.length) / 2);
            return ' '.repeat(pad > 0 ? pad : 0) + text;
        }
        function padRight(text, length) {
            return text + ' '.repeat(Math.max(length - text.length, 0));
        }

        function padLeft(text, length) {
            return ' '.repeat(Math.max(length - text.length, 0)) + text;
        }

        // Header (rata kiri)
        let header = '';
        header += `*${toko}*\n`;
        header += `${alamatToko}\n`;
        header += `Telp: ${telpToko}\n`;
        header += `${'-'.repeat(45)}\n`;
        header += `NOTA  : ${nota}\n`;
        header += `KASIR : ${kasir}\n`;
        header += `TGL   : ${tanggal} ${jam}\n`;
        header += `${'-'.repeat(45)}\n`;

        // Judul kolom
        let items = "Nama Barang        Qty   Harga     Subtotal\n";

        // Isi item dari PHP
        <?php
        $data_barang_wa = mysqli_query($conn, "SELECT * FROM keranjang");
        while ($d = mysqli_fetch_array($data_barang_wa)) {
            $nama     = substr($d['nama_barang'], 0, 18);
            $qty      = $d['quantity'];
            $harga    = number_format($d['harga_barang'], 0, '', '.');
            $subtotal = number_format($d['subtotal'], 0, '', '.');

            $nama_pad  = str_pad($nama, 18);                         // kiri
            $qty_pad   = str_pad($qty, 3, ' ', STR_PAD_LEFT);        // kanan
            $harga_pad = str_pad($harga, 9, ' ', STR_PAD_LEFT);     // kanan
            $sub_pad   = str_pad($subtotal, 11, ' ', STR_PAD_LEFT);  // kanan

            echo "items += \"{$nama_pad}{$qty_pad}{$harga_pad}{$sub_pad}\\n\";\n";
        }
        ?>

        // Footer total
        let total_diskon = "<?php echo format_ribuan($total_diskon); ?>";
        let total        = "<?php echo format_ribuan($tot_bayar); ?>";
        let bayar        = "<?php echo format_ribuan($bayar); ?>";
        let kembalian    = "<?php echo format_ribuan($kembalian); ?>";

        let footer = "";
        footer += `${'-'.repeat(45)}\n`;
        footer += `${str_pad("Total Diskon", 18)}: Rp. ${str_pad(total_diskon, 18, ' ', 'STR_PAD_LEFT')}\n`;
        footer += `${str_pad("Total", 18)}: Rp. ${str_pad(total, 18, ' ', 'STR_PAD_LEFT')}\n`;
        footer += `${str_pad("Bayar", 18)}: Rp. ${str_pad(bayar, 18, ' ', 'STR_PAD_LEFT')}\n`;
        footer += `${str_pad("Kembalian", 18)}: Rp. ${str_pad(kembalian, 18, ' ', 'STR_PAD_LEFT')}\n`;
        footer += `${'-'.repeat(45)}\n`;
        footer += `${centerText('*TERIMA KASIH*')}\n`;
        footer += `${centerText('TELAH BERBELANJA')}\n`;

        // Gabungkan dan bungkus monospace
        let pesan = `${header}\`\`\`\n${items}\n${footer}\`\`\``;

        let encodedPesan = encodeURIComponent(pesan);
        let whatsappUrl = `https://wa.me/?text=${encodedPesan}`;
        window.open(whatsappUrl, '_blank');
        }
</script>
  
<?php include 'template/footer.php';?>
