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

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

<?= $this->section('content') ?>
<div class="row mb-3">
    <div class="col-lg-12">
        <div class="card card-soft mb-3">
            <div class="card-header">
                <h5>View Order</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-lg-12">
                        <span class="text-muted small">Note : Untuk kode otomatis silahkan biarkan kosong input kode order.</span>
                    </div>
                </div>
                <div class="row mb-3 g-3 align-items-end">
                    <div class="col-12 col-md-3">
                        <label class="form-label">Kode Order</label>
                        <input type="text" name="kode_order" id="kode_order" class="form-control border-primary" value="<?=(isset($order) ? $order->kode_order : "")?>" >
                        <span id="ekode_order" class="text-danger invalid-feedback"></span>
                    </div>
                    <div class="col-6 col-md-2">
                        <label class="form-label">Status</label>
                        <span class="form-control bg-success text-white"><?=$order->status_order?></span>
                    </div>
                    <div class="col-6 col-md-2">
                        <label class="form-label">Checkout At</label>
                        <span class="form-control"><?=(empty($order->checkout_at))? "-" :$order->checkout_at?></span>
                    </div>
                    <div class="col-6 col-md-3">
                        <label class="form-label">Tanggal Order</label>
                        <input type="text" id="tanggal_order" class="form-control" value="<?=($order->tanggal_order) ? $order->tanggal_order : "-"?>">
                        <span id="etanggal_order" class="text-danger invalid-feedback"></span>
                    </div>
                    <div class="col-12 col-md-4">
                        <label class="form-label">Operator</label>
                        <span class="form-control"><?=$user->nama?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-lg-12">
        <div class="card card-soft">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Item Dipesan</h5>
                <button class="btn btn-primary touch" id="btnAddProduct">
                    + Tambah Produk
                </button>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table mb-0" id="orderTable">
                        <thead class="table-light">
                            <tr>
                            <th style="width:48px;"></th>
                            <th>Produk</th>
                            <th class="text-end">Harga</th>
                            <th class="text-center" style="width:170px;">Qty</th>
                            <th class="text-end">Subtotal</th>
                            <th class="text-center" style="width:48px;"></th>
                            </tr>
                        </thead>
                        <tbody id="orderBody">
                            <!-- rows injected by JS -->
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="sticky-actions p-3">
                <div class="row g-2 align-items-center">
                    <div class="col-12 col-md">
                        <div class="d-flex gap-2 align-items-center">
                            <span class="fw-semibold">Total Item:</span> <span id="totalItem" class="badge text-bg-secondary">0</span>
                            <span class="fw-semibold ms-3">Total:</span> <span id="grandTotal" class="fs-5 fw-bold">Rp0</span>
                            <span class="ms-3" id="statusBadge" class="badge badge-status terisi">Terisi</span>
                        </div>
                    </div>
                    <div class="col-12 col-md-auto d-flex gap-2">
                        <button class="btn btn-outline-danger touch" id="btnCancel">Batalkan Pesanan</button>
                        <button class="btn btn-outline-primary touch" id="btnSave">Simpan Order</button>
                        <button class="btn btn-success touch" id="btnCheckout">Checkout</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal Pilih Produk -->
<div class="modal fade" id="productModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Pilih Produk</h5>
                <button type="button" class="btn-close touch" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="input-group mb-3">
                    <span class="input-group-text">🔍</span>
                    <input type="text" id="searchProduct" class="form-control search-input touch" placeholder="Cari produk (kode/nama)">
                </div>

                <div id="productList" class="row g-3">
                    <!-- cards injected by JS -->
                </div>

                <div id="productEmpty" class="text-center text-muted py-4 d-none">
                    Tidak ada produk yang cocok.
                </div>
                <div class="modal-pager-wrapper">
                    
                </div>
            </div>
            <div id="productPager" class="pager-float bg-white border-top d-flex justify-content-center align-items-center gap-3 p-2">
                <div class="btn-group shadow">
                    <button id="btnPrevPage" type="button" class="btn btn-outline-secondary">‹ Prev</button>
                    <span id="pageInfo" class="btn btn-outline-secondary disabled" style="min-width:86px">1 / ?</span>
                    <button id="btnNextPage" type="button" class="btn btn-outline-secondary">Next ›</button>
                </div>
            </div>
        </div>
    </div>
</div>
<?= $this->endSection() ?>

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

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
flatpickr("#tanggal_order", {
  enableTime: true,
  dateFormat: "Y-m-d H:i:S", // langsung cocok dengan MySQL DATETIME
  defaultDate: new Date("<?=(isset($order) ? $order->tanggal_order : date("Y-m-d H:i:s"))?>"),
});
</script>

<script>
// ===== Helpers =====
const API_BASE = '<?=base_url()?>order'; // sesuaikan folder backend Anda
const fmtIDR = n => new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumFractionDigits: 0 }).format(n||0);

const CART = {}; // { [id_produk]: { id, kode, nama, harga, qty } }
var id_order = 0;

function setNowToInputDatetimeLocal(el){
const now = new Date();
const pad = (s)=> String(s).padStart(2,'0');
const val = `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}`;
el.value = val;
}

const PROD_STATE = {
  q: '',
  page: 1,
  limit: 12,   // atur sesuai kebutuhan UI
  hasNext: false,
  total: 0
};

// ===== Init =====
$(function(){
// setNowToInputDatetimeLocal(document.getElementById('tanggal_order'));
updateStatusBadge();

$('#btnAddProduct').on('click', () => {
    $('#productModal').modal('show');
    $('#searchProduct').val('');
    PROD_STATE.q = '';
    PROD_STATE.page = 1;
    loadProducts('');
    $('#productPager').removeClass('d-none'); // tampilkan pager saat modal aktif
});

$('#productModal').on('hidden.bs.modal', ()=> {
    $('#productPager').addClass('d-none');
});

$('#searchProduct').on('input', debounce(function(){
    const q = this.value.trim();
    PROD_STATE.q = q;
    PROD_STATE.page = 1; // reset ke halaman pertama saat ganti pencarian
    loadProducts(q);
}, 300));

$('#btnPrevPage').on('click', function(){
    if (PROD_STATE.page > 1) {
        PROD_STATE.page--;
        loadProducts(PROD_STATE.q);
    }
});
$('#btnNextPage').on('click', function(){
    if (PROD_STATE.hasNext) {
        PROD_STATE.page++;
        loadProducts(PROD_STATE.q);
    }
});

$('#btnSave').on('click', saveOrder);
$('#btnCancel').on('click', cancelOrder);
$('#btnCheckout').on('click', checkoutOrder);

<?php
echo "id_order = '".$order->id_order."';";
echo "var order_detail = new Object;";
foreach($order_detail as $item){
    ?>
    order_detail = new Object();
    order_detail.id_produk = '<?=$item->id_produk?>';
    order_detail.id_harga = '<?=$item->id_harga?>';
    order_detail.kode_produk = '<?=$item->kode_produk?>';
    order_detail.nama_produk = '<?=$item->nama_produk?>';
    order_detail.harga_jual = '<?=$item->harga_jual?>';
    order_detail.gambar = '<?=$item->gambar?>';
    addToCart(order_detail);
    <?php
}
?>
// contoh: preload 1 item (bisa dihapus)
// addToCart({id_produk:1,kode_produk:'KOPI1',nama_produk:'Kopi Hitam',harga_jual:12000});
});

function updateStatusBadge(){
const v = $('#status_meja').val();
const $b = $('#statusBadge').removeClass('kosong terisi');
if (v === 'kosong') { $b.text('Kosong').addClass('kosong'); }
else { $b.text('Terisi').addClass('terisi'); }
}

// ===== Product Modal =====
function loadProducts(q){
    $('#productList').empty();
    $('#productEmpty').addClass('d-none');

    const params = { q: q || '', page: PROD_STATE.page, limit: PROD_STATE.limit };

    $.getJSON(`${API_BASE}/list_products`, { ...params }, function(res){
        const items = res?.data || [];
        const total   = Number(res?.total ?? 0);
        const page    = Number(res?.page ?? PROD_STATE.page);
        const perPage = Number(res?.per_page ?? res?.limit ?? PROD_STATE.limit);
        const hasMore = (res?.has_more !== undefined)
                        ? !!res.has_more
                        : (total ? (page * perPage) < total : (items.length === perPage));

        // simpan state
        PROD_STATE.total  = total;
        PROD_STATE.page   = page;
        PROD_STATE.limit  = perPage;
        PROD_STATE.hasNext= hasMore;

        if (!items.length) {
            if (PROD_STATE.page > 1) {
                PROD_STATE.page--;
                return loadProducts(PROD_STATE.q);
            }
            $('#productEmpty').removeClass('d-none');
            updatePagerUI();
            return;
        }
        const $row = $('#productList');
        items.forEach(p => {
            const inCart   = !!CART[p.id_produk];
            const CartClass  = inCart ? 'text-dark bg-warning' : "";
            const card = $(`
                <div class="col-6 col-md-4 col-lg-3">
                    <div class="card ${CartClass} card-soft product-card h-100" data-id="${p.id_produk}">
                        <div class="card-body d-flex gap-3 align-items-center">
                            <div><img class="product-thumb" src="<?=base_url()?>gambar/${p.gambar}" alt=""></div>
                            <div class="flex-grow-1">
                                <div class="small">${p.kode_produk}</div>
                                <div class="fw-semibold">${p.nama_produk}</div>
                                <div class="fw-bold">${fmtIDR(p.harga_jual)}</div>
                            </div>
                        </div>
                    </div>
                </div>
            `);
            card.on('click', ()=> { addToCart(p); });
            $row.append(card);
        });

        updatePagerUI();
    }).fail(()=>{
        $('#productEmpty').removeClass('d-none').text('Gagal memuat produk.');
        PROD_STATE.hasNext = false;
        updatePagerUI();
    });
}

function updatePagerUI(){
  // Info halaman: jika total diketahui → “page / totalPage”, else “page / ?”
  let totalPage = '?';
  if (PROD_STATE.total && PROD_STATE.limit) {
    totalPage = Math.max(1, Math.ceil(PROD_STATE.total / PROD_STATE.limit));
  }
  $('#pageInfo').text(`${PROD_STATE.page} / ${totalPage}`);

  // Disable/enable tombol
  $('#btnPrevPage').prop('disabled', PROD_STATE.page <= 1);
  $('#btnNextPage').prop('disabled', !PROD_STATE.hasNext);
}

// ===== Cart =====
function addToCart(p){
    const id = p.id_produk;
    if (!CART[id]) {
        CART[id] = {
            id_produk: id,
            id_harga: p.id_harga,
            kode_produk: p.kode_produk,
            nama_produk: p.nama_produk,
            harga_jual: Number(p.harga_jual)||0,
            qty: 1,
            gambar : p.gambar
        };

        $(`div[data-id="${id}"]`).addClass("text-dark bg-warning");
    } else {
        CART[id].qty++;
    }
    renderCart();
}

function removeFromCart(id){
    delete CART[id];
    renderCart();
}

function changeQty(id, delta){
    if (!CART[id]) return;
    CART[id].qty = Math.max(1, CART[id].qty + delta);
    renderCart();
}

function renderCart(){
    const $tb = $('#orderBody').empty();
    let totalQty = 0, grand = 0;

    Object.values(CART).forEach(item => {
        const sub = item.qty * item.harga_jual;
        totalQty += item.qty;
        grand += sub;

        const tr = $(`
        <tr>
            <td class="text-center">
            <img class="product-thumb" style="width:44px;height:44px" src="<?=base_url()?>gambar/${item.gambar}" alt="">
            </td>
            <td>
            <div class="fw-semibold">${item.nama_produk}</div>
            <div class="text-muted small">${item.kode_produk}</div>
            </td>
            <td class="text-end">${fmtIDR(item.harga_jual)}</td>
            <td class="text-center">
            <div class="btn-group qty-group" role="group" aria-label="qty">
                <button class="btn btn-outline-secondary touch" data-act="dec">−</button>
                <button class="btn btn-outline-secondary" style="min-width:60px">${item.qty}</button>
                <button class="btn btn-outline-secondary touch" data-act="inc">+</button>
            </div>
            </td>
            <td class="text-end fw-bold">${fmtIDR(sub)}</td>
            <td class="text-center">
            <button class="btn btn-outline-danger touch" title="Hapus" data-act="del">✕</button>
            </td>
        </tr>
        `);

        tr.find('[data-act="inc"]').on('click', ()=> changeQty(item.id_produk, +1));
        tr.find('[data-act="dec"]').on('click', ()=> changeQty(item.id_produk, -1));
        tr.find('[data-act="del"]').on('click', ()=> removeFromCart(item.id_produk));
        $tb.append(tr);
    });

    $('#totalItem').text(totalQty);
    $('#grandTotal').text(fmtIDR(grand));
}

// ===== Actions =====
function collectOrderPayload(){
    const items = Object.values(CART).map(x => ({
        id_produk: x.id_produk,
        id_harga: x.id_harga,
        qty: x.qty
    }));
    // const total = items.reduce((a,b)=>a+b.subtotal,0);
    return {
        emode:'1',
        kode_order : $("#kode_order").val(),
        id_order : id_order,
        id_meja: '<?=$order->id_meja?>',
        tanggal_order: $('#tanggal_order').val(),
        items
    };
}

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

    const payload = collectOrderPayload();
    $.ajax({
        url: `${API_BASE}/save_order`,
        method: 'POST',
        data: JSON.stringify(payload),
        contentType: 'application/json',
        success: res => {
            Swal.fire({
                text:'Proses berhasil!',
                icon : 'success'
            }).then(function () {
                window.location.href = '<?=base_url()?>order/view_riwayat/<?=$order->id_order?>';
            });
        },
        error: (data) => {
            if(data.statusText == 'input'){
                Object.keys(data.responseJSON.messages).forEach(function(key){
                    $("#e"+key).html(data.responseJSON.messages[key]);
                    $("#e"+key).show();
                });
                Swal.close();
            }else{
                var pesan_error = "Terjadi kesalahan sistem!";
                if(data.responseJSON.messages.error){
                    pesan_error = data.responseJSON.messages.error;
                }
                Swal.fire({
                    text:pesan_error,
                    icon : 'error'
                });
            }
        }
    });
}

function cancelOrder(){
    const payload = collectOrderPayload();
    Swal.fire({
        title:'Cancel Data..',
        html: '<p>Yakin ingin membatalkan data ini?</p>',
        showDenyButton: true,
        showCancelButton: true,
        confirmButtonText: 'Yes',
        denyButtonText: 'No',
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                text: 'Processing.. Silahkan tunggu..',
                allowOutsideClick: false
            });
            Swal.showLoading();
            $.ajax({
                url: `${API_BASE}/cancel_order`,
                method: 'POST',
                data: JSON.stringify(payload),
                contentType: 'application/json',
                success: () => {
                Object.keys(CART).forEach(k=>delete CART[k]);
                renderCart();
                    Swal.fire({
                        text:'Proses berhasil!',
                        icon : 'success'
                    }).then(function () {
                        window.location.href = '<?=base_url()?>order/view_riwayat/<?=$order->id_order?>';
                    });
                },
                error: (data) => {
                    // console.log(data.responseJSON.messages.error);
                    let pesan = "";
                    if(data.responseJSON.messages.error){
                        pesan = data.responseJSON.messages.error;
                    }
                    Swal.fire({
                        text:'Terjadi kesalahan sistem!' + ' ' + pesan,
                        icon : 'error'
                    });
                }
            });
        }
    });
}

function checkoutOrder(){
    const payload = collectOrderPayload();
    if(!payload.items.length){ 
        Swal.fire({
            text:'Item order masih kosong!',
            icon : 'error'
        });
        return; 
    }
    
    if(id_order == 0){
        Swal.fire({
            text:'Silahkan lakukan penyimpanan order terlebih dahulu!',
            icon : 'error'
        });
        return; 
    }

    window.location.href = '<?=base_url()?>order/checkout/' + id_order;
}

// ===== Debounce helper =====
function debounce(fn, delay){ let t; return (...a)=>{ clearTimeout(t); t=setTimeout(()=>fn(...a),delay); }; }
</script>
<?= $this->endSection() ?>