@extends('layouts.base')

{{-- @section('content-header')
    <div class="content-header">
        <div class="container" style="display: contents">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0"> Kasir <small>kasir 3.0</small></h1>
                </div><!-- /.col -->
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="#">Home</a></li>
                        <li class="breadcrumb-item"><a href="#">Kasir</a></li>
                        <li class="breadcrumb-item active">Transaksi</li>
                    </ol>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div><!-- /.container-fluid -->
    </div>
@endsection --}}

@section('content')
    <div class="container" style="display: contents;">
        <div class="row" style="padding: 5px">
            <div class="col-lg-8">
                <div class="card card-warning card-outline card-outline-tabs">
                    <div class="card-header p-0 border-bottom-0">
                        <ul class="nav nav-tabs" id="custom-tabs-four-tab" role="tablist">
                            @foreach ($KelompokKategori as $key => $item)
                                <li class="nav-item">
                                    <a class="nav-link @if ($key == 0) active @endif"
                                        id="custom-tabs-four-{{ $item->kode_kelompok_kategori }}-tab" data-toggle="pill"
                                        href="#custom-tabs-four-{{ $item->kode_kelompok_kategori }}" role="tab"
                                        aria-controls="custom-tabs-four-{{ $item->kode_kelompok_kategori }}"
                                        aria-selected="true">{{ $item->nama_kelompok_kategori }}</a>
                                </li>
                            @endforeach
                        </ul>
                    </div>
                    <div class="card-body" id="batasitinggi"
                        style="height:720px;overflow-y:scroll;margin-bottom: 5px;padding-top: 2px;padding-bottom: 2px">
                        <div class="tab-content" id="custom-tabs-four-tabContent">
                            @foreach ($KelompokKategori as $key => $item)
                                <div class="tab-pane fade show @if ($key == 0) active @endif"
                                    id="custom-tabs-four-{{ $item->kode_kelompok_kategori }}" role="tabpanel"
                                    aria-labelledby="custom-tabs-four-{{ $item->kode_kelompok_kategori }}-tab">
                                    <div class="row">
                                        @if ($item->kode_kelompok_kategori == 'PAK-SKOM')
                                            <div class="col" style="padding: 0px">
                                                <div class="row" style="padding: 0px">
                                                    <div class="col-4 col-sm-3" style="margin-left: 0px;padding-left: 0px;">
                                                        <div class="nav flex-column nav-tabs h-100" id="vert-tabs-tab"
                                                            role="tablist" aria-orientation="vertical">

                                                            <a class="nav-link vert-nav-content active"
                                                                id="vert-tabs-nasi-tab" data-toggle="pill"
                                                                href="#vert-tabs-nasi" role="tab"
                                                                aria-controls="vert-tabs-nasi" aria-selected="true">Nasi</a>
                                                            <a class="nav-link vert-nav-content" id="vert-tabs-telur-tab"
                                                                data-toggle="pill" href="#vert-tabs-telur" role="tab"
                                                                aria-controls="vert-tabs-telur"
                                                                aria-selected="false">Telur</a>
                                                            <a class="nav-link vert-nav-content" id="vert-tabs-sambel-tab"
                                                                data-toggle="pill" href="#vert-tabs-sambel" role="tab"
                                                                aria-controls="vert-tabs-sambel"
                                                                aria-selected="false">Sambel</a>
                                                            <a class="nav-link vert-nav-content" id="vert-tabs-topping-tab"
                                                                data-toggle="pill" href="#vert-tabs-topping" role="tab"
                                                                aria-controls="vert-tabs-topping"
                                                                aria-selected="false">Topping</a>
                                                            <a class="nav-link vert-nav-content" id="vert-tabs-free-tab"
                                                                data-toggle="pill" href="#vert-tabs-free" role="tab"
                                                                aria-controls="vert-tabs-free"
                                                                aria-selected="false">Free</a>

                                                            <div class="card card-warning card-outline"
                                                                style="margin-top: auto;margin-right: 5px;height: auto;">
                                                                <div class="card-header">
                                                                    <h5 class="card-title m-0" id="nama-paket">
                                                                        Paket Menu Terpilih
                                                                    </h5>
                                                                </div>
                                                                <div class="card-body" style="padding: 2px 20px 2px">
                                                                    <ul style="padding: 0px 5px 0px;" id="menu-terpilih">
                                                                        <li>
                                                                            Pilih Paket Menu Terlebih Dahulu
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                                <a class="btn btn-warning disabled"
                                                                    id="select-ordered-menus" onclick="cariPaket()">Pilih
                                                                    Paket Menu
                                                                </a>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="col-8 col-sm-9" style="padding: 0px;">
                                                        <div class="card-body" style="height:700px;overflow-y:scroll;">
                                                            <div class="tab-content" id="vert-tabs-tabContent">
                                                                <div class="tab-pane vert-tab-content fade text-left show active"
                                                                    id="vert-tabs-nasi" role="tabpanel"
                                                                    aria-labelledby="vert-tabs-nasi-tab">
                                                                    <div class="row">
                                                                        @foreach ($item->kelompokKategoriPivot as $key2 => $kelompokKategoriPivot)
                                                                            @if ($kelompokKategoriPivot->produk->urutan == 1)
                                                                                <div class="col-lg-4">
                                                                                    <div onclick="selectPaket( {{ $kelompokKategoriPivot->produk }} );changeTab('vert-tabs-telur')"
                                                                                        class="card card-warning card-outline btn">
                                                                                        <div class="card-header">
                                                                                            <h5 class="card-title m-0">
                                                                                                {{ $kelompokKategoriPivot->produk->nama_produk ?? '' }}
                                                                                            </h5>
                                                                                        </div>
                                                                                        <div class="card-body">
                                                                                            <img style="width: 100%;height: 100%;object-fit: cover;"
                                                                                                src="
                                                                                                @if ($kelompokKategoriPivot->produk->gambar_produk != null) {{ asset('storage/' . $kelompokKategoriPivot->produk->gambar_produk) }}
                                                                                                @else
                                                                                                    {{ asset('assets/images/menu_image.jpeg') }} @endif
                                                                                                "
                                                                                                alt="{{ $kelompokKategoriPivot->produk->nama_produk ?? '' }}">
                                                                                        </div>
                                                                                        <a class="btn btn-warning"
                                                                                            id="ordered-menus-{{ $kelompokKategoriPivot->produk->id }}">
                                                                                            Pilih Paket
                                                                                        </a>
                                                                                    </div>
                                                                                </div>
                                                                            @endif
                                                                        @endforeach
                                                                    </div>
                                                                </div>
                                                                <div class="tab-pane vert-tab-content"
                                                                    id="vert-tabs-telur" role="tabpanel"
                                                                    aria-labelledby="vert-tabs-telur-tab">
                                                                    <div class="row">
                                                                        @foreach ($item->kelompokKategoriPivot as $key2 => $kelompokKategoriPivot)
                                                                            @if ($kelompokKategoriPivot->produk->urutan == 2)
                                                                                <div class="col-lg-4">
                                                                                    <div onclick="selectPaket( {{ $kelompokKategoriPivot->produk }} );changeTab('vert-tabs-sambel')"
                                                                                        class="card card-warning card-outline btn">
                                                                                        <div class="card-header">
                                                                                            <h5 class="card-title m-0">
                                                                                                {{ $kelompokKategoriPivot->produk->nama_produk ?? '' }}
                                                                                            </h5>
                                                                                        </div>
                                                                                        <div class="card-body">
                                                                                            <img style="width: 100%;height: 100%;object-fit: cover;"
                                                                                                src="
                                                                                                @if ($kelompokKategoriPivot->produk->gambar_produk != null) {{ asset('storage/' . $kelompokKategoriPivot->produk->gambar_produk) }}
                                                                                                @else
                                                                                                    {{ asset('assets/images/menu_image.jpeg') }} @endif
                                                                                                "
                                                                                                alt="{{ $kelompokKategoriPivot->produk->nama_produk ?? '' }}">
                                                                                        </div>
                                                                                        <a class="btn btn-warning"
                                                                                            id="ordered-menus-{{ $kelompokKategoriPivot->produk->id }}">
                                                                                            Pilih Paket
                                                                                        </a>
                                                                                    </div>
                                                                                </div>
                                                                            @endif
                                                                        @endforeach
                                                                    </div>
                                                                </div>
                                                                <div class="tab-pane vert-tab-content"
                                                                    id="vert-tabs-sambel" role="tabpanel"
                                                                    aria-labelledby="vert-tabs-sambel-tab">
                                                                    <div class="row">
                                                                        @foreach ($item->kelompokKategoriPivot as $key2 => $kelompokKategoriPivot)
                                                                            @if ($kelompokKategoriPivot->produk->urutan == 3)
                                                                                <div class="col-lg-4">
                                                                                    <div onclick="selectPaket( {{ $kelompokKategoriPivot->produk }} );changeTab('vert-tabs-topping')"
                                                                                        class="card card-warning card-outline btn">
                                                                                        <div class="card-header">
                                                                                            <h5 class="card-title m-0">
                                                                                                {{ $kelompokKategoriPivot->produk->nama_produk ?? '' }}
                                                                                            </h5>
                                                                                        </div>
                                                                                        <div class="card-body">
                                                                                            <img style="width: 100%;height: 100%;object-fit: cover;"
                                                                                                src="
                                                                                                @if ($kelompokKategoriPivot->produk->gambar_produk != null) {{ asset('storage/' . $kelompokKategoriPivot->produk->gambar_produk) }}
                                                                                                @else
                                                                                                    {{ asset('assets/images/menu_image.jpeg') }} @endif
                                                                                                "
                                                                                                alt="{{ $kelompokKategoriPivot->produk->nama_produk ?? '' }}">
                                                                                        </div>
                                                                                        <a class="btn btn-warning"
                                                                                            id="ordered-menus-{{ $kelompokKategoriPivot->produk->id }}">Pilih
                                                                                            Paket
                                                                                        </a>
                                                                                    </div>
                                                                                </div>
                                                                            @endif
                                                                        @endforeach
                                                                    </div>
                                                                </div>
                                                                <div class="tab-pane vert-tab-content"
                                                                    id="vert-tabs-topping" role="tabpanel"
                                                                    aria-labelledby="vert-tabs-topping-tab">
                                                                    <div class="row">
                                                                        @foreach ($item->kelompokKategoriPivot as $key2 => $kelompokKategoriPivot)
                                                                            @if ($kelompokKategoriPivot->produk->urutan == 4)
                                                                                <div class="col-lg-4">
                                                                                    <div onclick="selectPaket( {{ $kelompokKategoriPivot->produk }} );changeTab('vert-tabs-free')"
                                                                                        class="card card-warning card-outline btn">
                                                                                        <div class="card-header">
                                                                                            <h5 class="card-title m-0">
                                                                                                {{ $kelompokKategoriPivot->produk->nama_produk ?? '' }}
                                                                                            </h5>
                                                                                        </div>
                                                                                        <div class="card-body">
                                                                                            <img style="width: 100%;height: 100%;object-fit: cover;"
                                                                                                src="
                                                                                                @if ($kelompokKategoriPivot->produk->gambar_produk != null) {{ asset('storage/' . $kelompokKategoriPivot->produk->gambar_produk) }}
                                                                                                @else
                                                                                                    {{ asset('assets/images/menu_image.jpeg') }} @endif
                                                                                                "
                                                                                                alt="{{ $kelompokKategoriPivot->produk->nama_produk ?? '' }}">
                                                                                        </div>
                                                                                        <a class="btn btn-warning"
                                                                                            id="ordered-menus-{{ $kelompokKategoriPivot->produk->id }}">Pilih
                                                                                            Paket
                                                                                        </a>
                                                                                    </div>
                                                                                </div>
                                                                            @endif
                                                                        @endforeach
                                                                    </div>
                                                                </div>
                                                                <div class="tab-pane vert-tab-content" id="vert-tabs-free"
                                                                    role="tabpanel" aria-labelledby="vert-tabs-free-tab">
                                                                    <div class="row">
                                                                        @foreach ($item->kelompokKategoriPivot as $key2 => $kelompokKategoriPivot)
                                                                            @if ($kelompokKategoriPivot->produk->urutan == 5)
                                                                                <div class="col-lg-4">
                                                                                    <div onclick="selectPaket( {{ $kelompokKategoriPivot->produk }} )"
                                                                                        class="card card-warning card-outline btn">
                                                                                        <div class="card-header">
                                                                                            <h5 class="card-title m-0">
                                                                                                {{ $kelompokKategoriPivot->produk->nama_produk ?? '' }}
                                                                                            </h5>
                                                                                        </div>
                                                                                        <div class="card-body">
                                                                                            <img style="width: 100%;height: 100%;object-fit: cover;"
                                                                                                src="
                                                                                                @if ($kelompokKategoriPivot->produk->gambar_produk != null) {{ asset('storage/' . $kelompokKategoriPivot->produk->gambar_produk) }}
                                                                                                @else
                                                                                                    {{ asset('assets/images/menu_image.jpeg') }} @endif
                                                                                                "
                                                                                                alt="{{ $kelompokKategoriPivot->produk->nama_produk ?? '' }}">
                                                                                        </div>
                                                                                        <a class="btn btn-warning"
                                                                                            id="ordered-menus-{{ $kelompokKategoriPivot->produk->id }}">
                                                                                            Pilih Paket
                                                                                        </a>
                                                                                    </div>
                                                                                </div>
                                                                            @endif
                                                                        @endforeach
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        @else
                                            @foreach ($item->kelompokKategoriPivot as $key2 => $kelompokKategoriPivot)
                                                {{-- Jika paket irit  --}}
                                                @if ($kelompokKategoriPivot->kelompok_kategori_id == 2)
                                                    <div class="col-lg-4">
                                                        <div class="card card-warning card-outline btn"
                                                            onclick="aadMenu( {{ $kelompokKategoriPivot->produk }} )">
                                                            <div class="card-header">
                                                                <h5 class="card-title m-0">
                                                                    {{ $kelompokKategoriPivot->produk->nama_produk ?? '' }}
                                                                </h5>
                                                            </div>
                                                            <div class="card-body">
                                                                <div class="col-md-12">
                                                                    <img style="width: 100%;height: 100%;object-fit: cover;"
                                                                        src="
                                                                    @if ($kelompokKategoriPivot->produk->gambar_produk != null) {{ asset('storage/' . $kelompokKategoriPivot->produk->gambar_produk) }}
                                                                    @else
                                                                        {{ asset('assets/images/menu_image.jpeg') }} @endif
                                                                    "
                                                                        alt="{{ $kelompokKategoriPivot->produk->nama_produk ?? '' }}">
                                                                    <div class="col-md-12 mt-1"
                                                                        style="align-items: center;align-content: center;">
                                                                        <h5>
                                                                            {{ convert_to_rupiah($kelompokKategoriPivot->produk->harga_produk) }}
                                                                        </h5>
                                                                    </div>
                                                                    <div class="col-md-12">
                                                                        <a class="col-6 col-md-12 col-lg-6 btn btn-warning"
                                                                            id="ordered-menus">Pesan</a>
                                                                    </div>
                                                                </div>
                                                                <div class="col-md-12 mt-3">
                                                                    <h6 style="color: red">Jumlah terjual :
                                                                        {{ $totalPembelianByProduk[$kelompokKategoriPivot->produk->id]->total_beli ?? 0 }}
                                                                    </h6>

                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                @else
                                                    <div class="col-lg-4">
                                                        <div class="card card-warning card-outline btn"
                                                            onclick="aadMenu( {{ $kelompokKategoriPivot->produk }} )">
                                                            <div class="card-header">
                                                                <h5 class="card-title m-0">
                                                                    {{ $kelompokKategoriPivot->produk->nama_produk ?? '' }}
                                                                </h5>
                                                            </div>
                                                            <div class="card-body">
                                                                <div class="col-md-12">
                                                                    <img style="width: 100%;height: 100%;object-fit: cover;"
                                                                        src="
                                                                    @if ($kelompokKategoriPivot->produk->gambar_produk != null) {{ asset('storage/' . $kelompokKategoriPivot->produk->gambar_produk) }}
                                                                    @else
                                                                        {{ asset('assets/images/menu_image.jpeg') }} @endif
                                                                    "
                                                                        alt="{{ $kelompokKategoriPivot->produk->nama_produk ?? '' }}">
                                                                    <div class="col-md-12 mt-1"
                                                                        style="align-items: center;align-content: center;">
                                                                        <h5>
                                                                            {{ convert_to_rupiah($kelompokKategoriPivot->produk->harga_produk) }}
                                                                        </h5>
                                                                    </div>
                                                                    <div class="col-md-12">
                                                                        <a class="col-6 col-md-12 col-lg-6 btn btn-warning"
                                                                            id="ordered-menus">Pesan</a>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                @endif
                                            @endforeach
                                        @endif
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    </div>
                    <!-- /.card -->
                </div>
            </div>
            <!-- /.col-md-6 -->
            <div class="col-lg-4">
                <div class="card card-warning card-outline">
                    <div class="card-header">
                        <h5 class="col-lg-6 card-title m-0">Kode Pesanan
                            <small>{{ $orderCode }}</small>
                        </h5>
                        <h5 class="col-lg-6 card-title m-0" style="text-align: right">
                            <small id="datetime-order"></small>
                        </h5>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered table-striped" id="order-menus" width="100%">
                            <thead style="background-color: lightgray">
                                <tr>
                                    <th width="60%" class="text-center">Menu</th>
                                    <th>Qty</th>
                                    <th width="10%" style="text-align: center">
                                        <i class="fas fa-cog"></i>
                                    </th>
                                </tr>
                            </thead>
                            <tbody id="tbody-order-menus">
                            </tbody>
                            <tfoot style="background-color: lightgray">
                                <tr>
                                    <th class="text-center">Total</th>
                                    <th colspan="2">
                                        <span class="row">
                                            <span class="col-6">Rp.</span>
                                            <span class="col-6" style="text-align: right" id="total">0</span>
                                            <span class="col-6" id="total-hidden" style="display: none">0</span>
                                        </span>
                                    </th>
                                </tr>
                                <tr>
                                    <th class="text-center">Diskon (%)</th>
                                    <th colspan="2">
                                        <div class="input-group input-group-sm">
                                            <input type="number" name="diskon" class="form-control rounded-0">
                                        </div>
                                    </th>
                                </tr>
                                <tr>
                                    <th class="text-center">Grand Total</th>
                                    <th colspan="2">
                                        <span class="row">
                                            <span class="col-6">Rp.</span>
                                            <span class="col-6" style="text-align: right" id="total-diskon">0</span>
                                            <span class="col-6" id="total-diskon-hidden" style="display: none">0</span>
                                        </span>
                                    </th>
                                </tr>
                                <tr>
                                    <th class="text-center">Bayar</th>
                                    <th colspan="2">
                                        <div class="input-group input-group-sm">
                                            <input type="text" name="nominal-bayar" class="form-control rounded-0"
                                                required id="nominal-bayar">
                                        </div>
                                    </th>
                                </tr>
                                <tr>
                                    <th class="text-center">Kembali</th>
                                    <th colspan="2">
                                        <span class="row">
                                            <span class="col-6">Rp.</span>
                                            <span class="col-6" style="text-align: right" id="kembali">0</span>
                                            <span class="col-6" id="kembali-hidden" style="display: none">0</span>
                                        </span>
                                    </th>
                                </tr>
                                <tr>
                                    <th colspan="3">
                                        <span class="row">
                                            <input type="text" name="nama-pemesan" class="form-control rounded-0"
                                                placeholder="Nama Pemesan" id="nama-pemesan" required>
                                            <input type="number" min="1" name="nomor-meja"
                                                class="form-control rounded-0" placeholder="Nomor Meja" id="nomor-meja"
                                                required>
                                            <input type="text" name="keterangan-pesanan"
                                                placeholder="Keterangan Pesanan" class="form-control rounded-0"
                                                id="keterangan-pesanan">
                                        </span>
                                    </th>
                                </tr>
                                <tr style="background-color: white">
                                    <th colspan="3">
                                        <button class="btn btn-warning btn-block" id="pesan-bayar">Bayar</button>
                                    </th>
                                </tr>
                            </tfoot>
                        </table>

                    </div>
                </div>
            </div>
            <!-- /.col-md-6 -->
        </div>
        <!-- /.row -->
    </div><!-- /.container-fluid -->


    <div class="modal fade" id="modal-default">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Spesial Paket Komplit</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="show-modal-paket">
                </div>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
    </div>
@endsection

@push('styles')
    <!-- Toastr -->
    <style>
    </style>
    <link rel="stylesheet" href="{{ asset('assets/plugins/toastr/toastr.min.css') }}">
@endpush

@push('scripts')
    <!-- Toastr -->
    <script src="{{ asset('assets/plugins/toastr/toastr.min.js') }}"></script>
    <script>
        //  set interval waktu pesanan
        function showTime() {
            var date = new Date(),
                utc = new Date(Date.UTC(
                    date.getFullYear(),
                    date.getMonth(),
                    date.getDate(),
                    date.getHours() - 7,
                    date.getMinutes(),
                    date.getSeconds()
                ));

            // format datetime indonesia
            var options = {
                weekday: 'long',
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: 'numeric',
                hour12: true,
                minute: 'numeric',
                second: 'numeric'
            };

            // tampilkan pada id datetime-order
            document.getElementById('datetime-order').innerHTML = utc.toLocaleDateString("id-ID", options);
        }

        setInterval(showTime, 1000);

        //  make function add menu to table and calculate qty and total price menu ordered and check menu ordered is exist or not in tbody table order-menus insert this in
        function aadMenu(params) {
            var table = document.getElementById("order-menus");
            var menu = params;
            var menuId = menu.id;
            var menuName = menu.nama_produk;
            var menuPrice = menu.harga_produk;
            var menuQty = 1;
            var menuTotal = menuPrice * menuQty;

            var isExist = false;
            var index = 0;

            for (var i = 1, row; row = table.rows[i]; i++) {
                var id = row.getAttribute('data-id');

                if (id == menuId) {
                    isExist = true;
                    index = i;
                }
            }

            if (isExist) {
                var qty = table.rows[index].getAttribute('data-qty');
                var total = table.rows[index].getAttribute('data-total');

                qty = parseInt(qty) + 1;
                total = parseInt(total) + parseInt(menuPrice);

                table.rows[index].setAttribute('data-qty', qty);
                table.rows[index].setAttribute('data-total', total);

                table.rows[index].cells[1].innerHTML = `
                <td class="text-center">
                    <div class="input-group input-group-sm">
                        <span class="input-group-append">
                            <button type="button" class="btn btn-default btn-xs btn-flat" onclick="decrementMenu(${params.id})"><b>-</b></button>
                        </span>
                        <input type="number" name="bayar" class="form-control rounded-0" value="${qty}">
                        <span class="input-group-append">
                            <button type="button" class="btn btn-default btn-xs btn-flat" onclick="incrementMenu(${params.id})">+</button>
                        </span>
                    </div>
                </td>
            `;
                table.rows[index].cells[2].innerHTML = `
                <td class="text-center">
                    <button class="btn btn-danger btn-sm" onclick="deleteMenu(${params.id})">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            `;
                calculateTotal();
                $('#modal-default').modal('hide');
            } else {
                $('#tbody-order-menus').append(`
                <tr id="row-${params.id}" data-id="${params.id}" data-nama="${params.nama_produk}" data-harga="${params.harga_produk}" data-qty="1" data-total="${params.harga_produk}">
                    <td>
                        ${params.nama_produk}
                        <br>
                        <small class="text-danger">Rp. ${params.harga_produk}</small>
                    </td>
                    <td class="text-center">
                        <div class="input-group input-group-sm">
                            <span class="input-group-append">
                                <button type="button" class="btn btn-default btn-xs btn-flat" onclick="decrementMenu(${params.id})"><b>-</b></button>
                            </span>
                            <input type="number" name="bayar" class="form-control rounded-0" value="${menuQty}">
                            <span class="input-group-append">
                                <button type="button" class="btn btn-default btn-xs btn-flat" onclick="incrementMenu(${params.id})">+</button>
                            </span>
                        </div>
                    </td>
                    <td class="text-center">
                        <button class="btn btn-danger btn-sm" onclick="deleteMenu(${params.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `);
                calculateTotal();
                $('#modal-default').modal('hide');
            }
        }

        //  delete menu from table and calculate qty and total price menu ordered
        function deleteMenu(params) {
            var table = document.getElementById("order-menus");
            var index = 0;

            for (var i = 1, row; row = table.rows[i]; i++) {
                var id = row.getAttribute('data-id');

                if (id == params) {
                    index = i;
                }
            }

            table.deleteRow(index);
            calculateTotal();
        }

        //  calculate qty and total price menu ordered
        function calculateTotal() {
            var table = document.getElementById("order-menus");
            var total = 0;
            var diskon = document.getElementsByName('diskon')?.[0]?.value ?? 0;
            var bayar = document.getElementsByName('bayar')?.[0]?.value ?? 0;

            for (var i = 1, row; row = table.rows[i]; i++) {
                var harga = row.getAttribute('data-harga');
                var qty = row.getAttribute('data-qty');
                var total = total + (harga * qty);
            }

            var ribuantotal = toRupiah(total);

            document.getElementById('total').innerHTML = ribuantotal;
            document.getElementById('total-hidden').innerHTML = total;

            var totalDiskon = total - (total * (diskon / 100));
            var ribuantotalDiskon = toRupiah(totalDiskon);
            document.getElementById('total-diskon').innerHTML = ribuantotalDiskon;
            document.getElementById('total-diskon-hidden').innerHTML = totalDiskon;

            calculatekembali();
        }

        //  increment qty menu ordered
        function incrementMenu(params) {
            var table = document.getElementById("order-menus");
            var index = 0;

            for (var i = 1, row; row = table.rows[i]; i++) {
                var id = row.getAttribute('data-id');

                if (id == params) {
                    index = i;
                }
            }

            var qty = table.rows[index].getAttribute('data-qty');
            var total = table.rows[index].getAttribute('data-total');
            var harga = table.rows[index].getAttribute('data-harga');

            qty = parseInt(qty) + 1;
            total = parseInt(total) + parseInt(harga);

            table.rows[index].setAttribute('data-qty', qty);
            table.rows[index].setAttribute('data-total', total);

            table.rows[index].cells[1].innerHTML = `
                <td class="text-center">
                    <div class="input-group input-group-sm">
                        <span class="input-group-append">
                            <button type="button" class="btn btn-default btn-xs btn-flat" onclick="decrementMenu(${params})"><b>-</b></button>
                        </span>
                        <input type="number" name="bayar" class="form-control rounded-0" value="${qty}">
                        <span class="input-group-append">
                            <button type="button" class="btn btn-default btn-xs btn-flat" onclick="incrementMenu(${params})">+</button>
                        </span>
                    </div>
                </td>
            `;

            calculateTotal();
        }

        //  decrement qty menu ordered
        function decrementMenu(params) {
            var table = document.getElementById("order-menus");
            var index = 0;

            for (var i = 1, row; row = table.rows[i]; i++) {
                var id = row.getAttribute('data-id');

                if (id == params) {
                    index = i;
                }
            }

            var qty = table.rows[index].getAttribute('data-qty');
            var total = table.rows[index].getAttribute('data-total');
            var harga = table.rows[index].getAttribute('data-harga');

            if (qty > 1) {
                qty = parseInt(qty) - 1;
                total = parseInt(total) - parseInt(harga);

                table.rows[index].setAttribute('data-qty', qty);
                table.rows[index].setAttribute('data-total', total);

                table.rows[index].cells[1].innerHTML = `
                    <td class="text-center">
                        <div class="input-group input-group-sm">
                            <span class="input-group-append">
                                <button type="button" class="btn btn-default btn-xs btn-flat" onclick="decrementMenu(${params})"><b>-</b></button>
                            </span>
                            <input type="number" name="bayar" class="form-control rounded-0" value="${qty}">
                            <span class="input-group-append">
                                <button type="button" class="btn btn-default btn-xs btn-flat" onclick="incrementMenu(${params})">+</button>
                            </span>
                        </div>
                    </td>
                `;

                calculateTotal();
            }
        }

        // diskon use keyup
        document.getElementsByName('diskon')[0].addEventListener('keyup', function() {
            var diskon = document.getElementsByName('diskon')[0].value;
            var total = document.getElementById('total-hidden').innerHTML;
            var totalDiskon = total - (total * (diskon / 100));

            var ribuan = toRupiah(totalDiskon);
            document.getElementById('total-diskon-hidden').innerHTML = totalDiskon;
            document.getElementById('total-diskon').innerHTML = ribuan;

            calculatekembali();
        });

        /* Dengan Rupiah */
        var dengan_rupiah = document.getElementById('nominal-bayar');
        dengan_rupiah.addEventListener('keyup', function(e) {
            dengan_rupiah.value = formatRupiah(this.value, 'Rp. ');
        });

        /* Fungsi */
        function formatRupiah(angka, prefix) {
            var number_string = angka.replace(/[^,\d]/g, '').toString(),
                split = number_string.split(','),
                sisa = split[0].length % 3,
                rupiah = split[0].substr(0, sisa),
                ribuan = split[0].substr(sisa).match(/\d{3}/gi);

            if (ribuan) {
                separator = sisa ? '.' : '';
                rupiah += separator + ribuan.join('.');
            }

            rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
            return prefix == undefined ? rupiah : (rupiah ? 'Rp. ' + rupiah : '');
        }

        // bayar use keyup
        document.getElementsByName('nominal-bayar')[0].addEventListener('keyup', function() {
            calculatekembali();
        });

        function calculatekembali() {
            var bayar = document.getElementsByName('nominal-bayar')[0].value;
            var nonimalBayar = bayar.replace(/[^,\d]/g, '').toString();
            var totalDiskon = document.getElementById('total-diskon-hidden').innerHTML;
            var kembali = nonimalBayar - totalDiskon;

            document.getElementById('kembali-hidden').innerHTML = kembali;

            var ribuan = toRupiah(kembali);
            if (totalDiskon == 0 || bayar == 0) {
                ribuan = 0;
                var bayar = document.getElementsByName('nominal-bayar')[0].value = '';

            }
            document.getElementById('kembali').innerHTML = ribuan;
        }

        // format rupiah with minus
        function toRupiah(angka) {
            var rupiah = '';
            var angkarev = angka.toString().split('').reverse().join('');
            for (var i = 0; i < angkarev.length; i++)
                if (i % 3 == 0) rupiah += angkarev.substr(i, 3) + '.';
            return rupiah.split('', rupiah.length - 1).reverse().join('');
        }

        //  pesan bayar
        document.getElementById('pesan-bayar').addEventListener('click', function() {
            var table = document.getElementById("order-menus");
            var orderMenus = [];

            for (var i = 1, row; row = table.rows[i]; i++) {
                var id = row.getAttribute('data-id');
                var nama = row.getAttribute('data-nama');
                var qty = row.getAttribute('data-qty');
                var harga = row.getAttribute('data-harga');
                var total = row.getAttribute('data-total');

                if (id != null || qty != null || total != null) {
                    orderMenus.push({
                        id: id,
                        nama: nama,
                        qty: qty,
                        harga: harga,
                        total: total
                    });
                }
            }

            var diskon = document.getElementsByName('diskon')[0].value;
            var totalDiskon = document.getElementById('total-diskon-hidden').innerHTML;
            var bayar = document.getElementsByName('nominal-bayar')[0].value;
            var nominalBayar = bayar.replace(/[^,\d]/g, '').toString();
            var kembaliHidden = document.getElementById('kembali-hidden').innerHTML;
            var namaPemesan = document.getElementsByName('nama-pemesan')[0].value;
            var nomorMeja = document.getElementsByName('nomor-meja')[0].value;

            if (orderMenus.length == 0) {
                alert('Menu tidak boleh kosong');
                return false;
            }
            if (nominalBayar == '' || nominalBayar == 0) {
                alert('Pembayaran tidak boleh kosong');
                return false;
            } else if (kembaliHidden < 0) {
                alert('Pembayaran kurang');
                return false;
            } else if (nomorMeja == '') {
                alert('Nomor meja tidak boleh kosong');
                return false;
            } else if (namaPemesan == '') {
                alert('Nama pemesan tidak boleh kosong');
                return false;
            }


            var data = {
                _token: "{{ csrf_token() }}",
                orderCode: "{{ $orderCode }}",
                orderMenus: orderMenus,
                namaPemesan: namaPemesan,
                nomorMeja: nomorMeja,
                keteranganPesanan: document.getElementsByName('keterangan-pesanan')[0].value,
                diskon: diskon,
                totalDiskon: totalDiskon,
                nominalBayar: nominalBayar,
                kembali: kembaliHidden
            };
            console.log(data);
            $.ajax({
                url: "{{ route('transaksi.store') }}",
                method: "POST",
                data: data,
                success: function(result) {
                    console.log(result);
                    // show toastr success
                    toastr.success(result.message, 'Success', {
                        timeOut: 2000
                    });
                    // opem mew page print
                    window.open(result.url, '_blank');

                    // // refresh page
                    setTimeout(function() {
                        window.location.reload(1);
                    }, 2000);
                },
                error: function(xhr, status, error) {
                    toastr.error(xhr.responseJSON.message, 'Error', {
                        timeOut: 3000
                    });
                    console.log(xhr.responseJSON);
                    console.log(status);
                    console.log(error);
                }
            });
        });

        // select paket
        var selectedMenus = [];
        var menu_terpilih = document.getElementById('menu-terpilih');
        // pilih paket menu terlebih dahulu kemudian cocokkan dengan menu yang ada di menu terpilih jika ada maka tidak bisa memilih paket menu yang sama
        function selectPaket(params) {
            var isExist = false;
            var index = 0;

            for (var i = 0; i < selectedMenus.length; i++) {
                // lakukan periksa kembali apabila menu dengan urutan yang sama sudah ada maka hapus menu tersebut dari array selectedMenus kecuali menu dengan urutan 5 boleh lebih dari 1
                if (params.urutan == 5) {
                    if (selectedMenus[i].id == params.id) {
                        changeOrderedMenus(selectedMenus[i].id, 'pilih');
                        isExist = true;
                        index = i;
                    }
                } else if (selectedMenus[i].urutan == params.urutan) {
                    changeOrderedMenus(selectedMenus[i].id, 'batal');
                    selectedMenus.splice(i, 1);
                } else if (selectedMenus[i].id == params.id) {
                    changeOrderedMenus(selectedMenus[i].id, 'pilih');
                    isExist = true;
                    index = i;
                }
            }

            if (isExist) {
                selectedMenus.splice(index, 1);
                document.getElementById('select-ordered-menus').classList.remove('disabled');
                // document.getElementById('ordered-menus').setAttribute('onclick', 'orderedMenus()');
            } else {
                selectedMenus.push(params);
                document.getElementById('select-ordered-menus').classList.remove('disabled');
                // document.getElementById('ordered-menus').classList.add('disabled');
                // document.getElementById('ordered-menus').setAttribute('onclick', '');
            }

            menu_terpilih.innerHTML = '';
            for (var i = 0; i < selectedMenus.length; i++) {
                changeOrderedMenus(selectedMenus[i].id, 'pilih');
                menu_terpilih.innerHTML += `
                <li>
                    ${selectedMenus[i].nama_produk}
                </li>
            `;
            }

            if (selectedMenus.length == 0) {
                menu_terpilih.innerHTML = `
                <li>
                    Pilih Paket Menu Terlebih Dahulu
                </li>
            `;
            }
        }

        // ordered menus change button text and onclick
        function changeOrderedMenus(id, status) {
            if (status == 'batal') {
                var orderedMenus = document.getElementById('ordered-menus-' + id);
                orderedMenus.innerHTML = 'Pilih Paket';
                orderedMenus.classList.remove('btn-secondary');
                orderedMenus.classList.add('btn-warning');
                return false;

            } else if (status == 'pilih') {
                var orderedMenus = document.getElementById('ordered-menus-' + id);
                orderedMenus.innerHTML = 'Batal Pilih';
                orderedMenus.classList.remove('btn-warning');
                orderedMenus.classList.add('btn-secondary');
                return false;
            }
        }

        // cari paket
        function cariPaket(params) {
            var show_modal_paket = document.getElementById('show-modal-paket');
            show_modal_paket.innerHTML = ``;
            // loop selectedMenus ambil kode produk
            var kodeProduk = [];
            if (selectedMenus.length == 0) {
                alert('Pilih Paket Menu Terlebih Dahulu');
                return false;
            }
            for (var i = 0; i < selectedMenus.length; i++) {
                if (selectedMenus[i].urutan != 5) {
                    kodeProduk.push({
                        urutan: selectedMenus[i].urutan,
                        kode_produk: selectedMenus[i].kode_produk
                    });
                }
            }
            var data = {
                _token: "{{ csrf_token() }}",
                kodeProduk: kodeProduk
            };
            $.ajax({
                url: "{{ route('transaksi.cari-paket') }}",
                method: "POST",
                data: data,
                success: function(result) {
                    var dataParse = JSON.stringify(result);

                    // Replace karakter kutipan ganda dengan HTML entities
                    var htmlEntitiesData = dataParse.replace(/\"/g, '&quot;');
                    // Tampilkan hasil
                    var show_modal_paket = document.getElementById('show-modal-paket');
                    if (result.gambar_produk != null) {
                        var gambar_produk = result.full_path;
                    } else {
                        var gambar_produk = "{{ asset('assets/images/menu_image.jpeg') }}";
                    }
                    show_modal_paket.innerHTML += `
                    <div class="card card-warning card-outline btn"
                        onclick="aadMenu(${htmlEntitiesData});clearSelected()">
                        <div class="card-header">
                            <h5 class="card-title m-0" id="nama-produk-modal">
                                ${result.nama_produk ?? ''}
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="col-md-12">
                                <img style="width: 80%;height: 80%;object-fit: cover;"
                                    src="${gambar_produk}"
                                    alt="${result.nama_produk ?? ''}">
                                <div class="col-md-12 mt-1"
                                    style="align-items: center;align-content: center;">
                                    <h5>
                                        Rp ${result.harga_produk ?? ''}
                                    </h5>
                                </div>
                                <div class="col-md-12">
                                    <a class="col-6 btn btn-warning" id="ordered-menus">Pesan</a>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                    $('#modal-default').modal('show');
                },
                error: function(xhr, status, error) {
                    toastr.error(xhr.responseJSON.message, 'Error', {
                        timeOut: 3000
                    });
                    console.log(xhr.responseJSON);
                    console.log(status);
                    console.log(error);
                }
            })
        }

        // clear selected menus
        function clearSelected() {
            console.log(selectedMenus);
            for (var i = 0; i < selectedMenus.length; i++) {
                changeOrderedMenus(selectedMenus[i].id, 'batal');
                menu_terpilih.innerHTML = ` `;
            }
            selectedMenus = [];
        }

        function changeTab(tabId) {
            // Hide all tabs
            var tabContents = document.getElementsByClassName('vert-tab-content');
            for (var i = 0; i < tabContents.length; i++) {
                tabContents[i].classList.remove('text-left', 'show', 'active');
            }

            var navLinks = document.getElementsByClassName('vert-nav-content');
            for (var i = 0; i < navLinks.length; i++) {
                navLinks[i].classList.remove('active');
                // aria-selected
                navLinks[i].setAttribute('aria-selected', false);
            }

            document.getElementById(tabId).classList.add('text-left', 'show', 'active');
            document.getElementById(tabId + '-tab').classList.add('active');
            // aria-selected
            document.getElementById(tabId + '-tab').setAttribute('aria-selected', true);
        }
    </script>
@endpush
