<?php if (auth()->user()->role == 'customer'): ?>
    <?= $this->extend('layouts/topbar') ?>
<?php else: ?>
    <?= $this->extend('layouts/sidebar') ?>
<?php endif; ?>

<?= $this->section('content') ?>

<?php
// Define role and permissions
$role = auth()->user()->role;
$isAdmin = $role === 'admin';
$isKasir = $role === 'kasir';
$isCustomer = $role === 'customer';
?>

<?php if ($isCustomer): ?>
    <!-- CUSTOMER VIEW: Card-based Layout -->
    <section class="content">
        <div class="container-fluid">
            <!-- Add New Order Button -->
            <div class="mb-4 text-center">
                <button class="btn btn-lg shadow-sm mb-5 <?= $type == 'history' ? 'd-none' : '' ?>"
                    onclick="show_lg('<?= base_url('permintaan_custom/create') ?>')"
                    style="background: #e5e7eb; border: none; color: #111827 !important; border-radius: 25px; padding: 15px 50px;">
                    <i class="fas fa-plus-circle" style="color: #111827;"></i> Buat Pesanan Baru</button>

                <div class="row d-none">
                    <div class="col-md-6">
                        <button class="btn btn-lg shadow-sm  mb-5" onclick="showPemesanan('baru')"
                            style="background: #e5e7eb; border: none; color: #111827 !important; border-radius: 25px; padding: 15px 50px;">Pesanan
                            Baru</button>
                    </div>
                    <div class="col-md-6">
                        <button class="btn btn-lg shadow-sm  mb-5" onclick="showPemesanan('lama')"
                            style="background: #e5e7eb; border: none; color: #111827 !important; border-radius: 25px; padding: 15px 50px;">Pesanan
                            Lama</button>
                    </div>
                </div>

                <!-- Orders Grid -->
                <div class="row" id="row-pemesanan_custom">
                    <?php if (empty($data)): ?>

                        <?php if ($type == 'order'): ?>
                            <div class="col-12">
                                <div class="alert shadow-sm text-center py-5"
                                    style="background: #e5e7eb; color: #111827; border: none; border-radius: 15px;">
                                    <i class="fas fa-shopping-bag fa-3x mb-3"></i>
                                    <h4>Belum Ada Pesanan</h4>
                                    <p>Mulai buat pesanan custom gamis Anda sekarang!</p>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="col-12">
                                <div class="alert shadow-sm text-center py-5"
                                    style="background: #e5e7eb; color: #111827; border: none; border-radius: 15px;">
                                    <i class="fas fa-shopping-bag fa-3x mb-3"></i>
                                    <h4>Belum Ada Riwayat Pesanan</h4>
                                </div>
                            </div>
                        <?php endif; ?>

                    <?php else: ?>
                        <?php foreach ($data as $row): ?>
                            <div class="col-md-6 col-lg-4 mb-4">
                                <div class="card shadow-sm h-100"
                                    style="border-radius: 15px; border: 2px solid #e0e0e0; transition: transform 0.2s;">
                                    <div class="card-header"
                                        style="background: #e5e7eb; color: #111827; border-radius: 13px 13px 0 0;">
                                        <h5 class="mb-0" style="color: #111827 !important;">
                                            <i class="fas fa-receipt"></i> <?= $row->no_order_custom ?>
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <!-- Order Date -->
                                        <div class="mb-2">
                                            <small class="text-muted"><i class="fas fa-calendar"></i> Tanggal Order</small>
                                            <p class="mb-0 font-weight-bold">
                                                <?= $row->tanggal_order ? date('d/m/Y H:i', strtotime($row->tanggal_order)) : '-' ?>
                                            </p>
                                        </div>

                                        <!-- Pickup Date -->
                                        <div class="mb-2 d-none">
                                            <small class="text-muted"><i class="fas fa-calendar-check"></i> Tanggal
                                                Pengambilan</small>
                                            <p class="mb-0 font-weight-bold">
                                                <?= date('d-m-Y', strtotime($row->tanggal_pengambilan)) ?></p>
                                        </div>

                                        <!-- Total -->
                                        <div class="mb-3">
                                            <small class="text-muted"><i class="fas fa-money-bill-wave"></i> Total
                                                Pembayaran</small>
                                            <h4 class="mb-0 text-primary">Rp.
                                                <?= number_format($row->nominal_pelunasan, 0, ',', '.') ?></h4>
                                        </div>

                                        <!-- Payment Status -->
                                        <div class="mb-2">
                                            <small class="text-muted">Status Pembayaran:</small><br>
                                            <?php if ($row->sisa_pembayaran === null || $row->dp_pembayaran === null || ($row->dp_pembayaran == 0 && $row->sisa_pembayaran == $row->nominal_pelunasan)): ?>
                                                <span class="badge badge-danger badge-lg">Belum Bayar</span>
                                            <?php elseif ($row->sisa_pembayaran == 0): ?>
                                                <span class="badge badge-success badge-lg">Lunas</span>
                                            <?php elseif ($row->dp_pembayaran > 0): ?>
                                                <span class="badge badge-warning badge-lg">DP Dibayar</span>
                                            <?php endif; ?>
                                        </div>

                                        <!-- Unified Order Status -->
                                        <div class="mb-3">
                                            <small class="text-muted">Status Pesanan:</small><br>
                                            <?php
                                            $status_pesanan = $row->status_pesanan ?? 'menunggu_konfirmasi';
                                            $badge_class = 'secondary';
                                            $icon = 'clock';
                                            $status_text = '';

                                            switch ($status_pesanan) {
                                                case 'menunggu_konfirmasi':
                                                    $badge_class = 'warning';
                                                    $icon = 'hourglass-half';
                                                    $status_text = 'Menunggu Konfirmasi Admin';
                                                    break;
                                                case 'menunggu_input_meter':
                                                    $badge_class = 'danger';
                                                    $icon = 'ruler';
                                                    $status_text = 'Menunggu Input Meter';
                                                    break;
                                                case 'menunggu_pembayaran':
                                                    $badge_class = 'info';
                                                    $icon = 'credit-card';
                                                    $status_text = 'Menunggu Pembayaran';
                                                    break;
                                                case 'diproses':
                                                    $badge_class = 'primary';
                                                    $icon = 'cog';
                                                    $status_text = 'Sedang Diproses';
                                                    break;
                                                case 'selesai':
                                                    $badge_class = 'success';
                                                    $icon = 'check-circle';
                                                    $status_text = 'Selesai';
                                                    break;
                                                case 'ditolak':
                                                    $badge_class = 'danger';
                                                    $icon = 'times-circle';
                                                    $status_text = 'Ditolak';
                                                    break;
                                                default:
                                                    $badge_class = 'secondary';
                                                    $icon = 'fas fa-truck-pickup';
                                                    $status_text = ucfirst(str_replace('_', ' ', $status_pesanan));
                                            }
                                            ?>
                                            <span class="badge badge-<?= $badge_class ?> badge-lg">
                                                <i class="fas fa-<?= $icon ?>"></i> <?= $status_text ?>
                                            </span>
                                        </div>
                                    </div>

                                    <!-- Action Buttons -->
                                    <div class="card-footer bg-white" style="border-radius: 0 0 13px 13px;">
                                        <?php
                                        $hasNoPayment = $row->dp_pembayaran == 0;
                                        $hasOutstandingPayment = $row->sisa_pembayaran > 0 || $row->sisa_pembayaran === null;
                                        $hasMissingMeter = isset($row->has_missing_meter) && $row->has_missing_meter;
                                        $isConfirmed = $row->status_admin_konfirmasi == 1;

                                        // Check if current user is customer and order was created by customer
                                        // Only show payment button to customer if the order was created by customer, not by kasir
                                        $currentUserRole = auth()->user()->role;
                                        $createdByRole = $row->created_by_role ?? 'customer'; // Default to customer if not set

                                        // Payment button logic:
                                        // - If current user is customer: only show if created_by_role is 'customer' (not 'kasir')
                                        // - If current user is admin/kasir: always show (they can accept payment)
                                        if ($currentUserRole == 'customer') {
                                            $canPayByRole = $createdByRole == 'customer';
                                        } else {
                                            $canPayByRole = true; // Admin/kasir can always process payment
                                        }

                                        $canEdit = $hasNoPayment && $hasNoPayment;
                                        $canDelete = $hasNoPayment && !$isConfirmed;
                                        // Payment button only shows after admin confirmation
                                        $canPay = $hasOutstandingPayment && $canPayByRole && $isConfirmed && ($row->status_pesanan != 'menunggu_input_meter' && $row->status_pesanan != 'menunggu_konfirmasi');
                                        ?>

                                        <div class="btn-group-vertical w-100">
                                            <!-- Detail Button -->
                                            <button class="btn btn-primary btn-sm mb-1"
                                                onclick="show_lg('<?= base_url('permintaan_custom/detail/' . $row->kode_permintaan_custom) ?>')">
                                                <i class="fas fa-eye"></i> Lihat Detail
                                            </button>

                                            <!-- Edit Button -->
                                            <?php if ($canEdit): ?>
                                                <button class="btn btn-warning btn-sm mb-1 d-none"
                                                    onclick="show_lg('<?= base_url('permintaan_custom/edit/' . $row->kode_permintaan_custom) ?>')">
                                                    <i class="fas fa-edit"></i> Revisi Pesanan
                                                </button>
                                            <?php endif; ?>

                                            <!-- Delete Button -->
                                            <?php if ($canDelete): ?>
                                                <a class="btn btn-danger btn-sm mb-1" onclick="notificationforDelete(event, this)"
                                                    href="<?= base_url('permintaan_custom/delete/' . $row->kode_permintaan_custom) ?>">
                                                    <i class="fas fa-trash"></i> Hapus Pesanan
                                                </a>
                                            <?php endif; ?>

                                            <!-- Payment Button -->
                                            <?php if ($canPay): ?>
                                                <button class="btn btn-success btn-sm"
                                                    onclick="show_lg('<?= base_url('transactions/pay_dp/' . $row->kode_permintaan_custom) ?>')">
                                                    <i class="fas fa-money-check"></i> Bayar Sekarang
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
    </section>

    <style>
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3) !important;
        }

        .badge-lg {
            font-size: 0.85rem;
            padding: 5px 10px;
        }
    </style>

<?php else: ?>
    <!-- ADMIN/KASIR VIEW: Table Layout (Original) -->
    <section class="content">
        <div class="container-fluid">
            <div class="card mb-3">
                <div class="card-body">
                    <?php if (auth()->user()->role != 'pemilik_toko' && auth()->user()->role != 'admin'): ?>
                        <a class="btn btn-success mb-3" onclick="show_lg('<?= base_url('permintaan_custom/create') ?>')"><i
                                class="fas fa-plus"></i>&nbsp; Tambah Data</a>
                    <?php endif; ?>
                    <table id="example1" class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>No Order</th>
                                <?php if (!$isCustomer): ?>
                                    <th>Customer</th>
                                <?php endif; ?>
                                <th>Tanggal Order</th>
                                <th class="d-none">Tanggal Pengambilan</th>
                                <th>Nominal Pelunasan</th>
                                <th>Status Pembayaran</th>
                                <th>Status Pesanan</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $i = 1; ?>
                            <?php foreach ($data as $row) : ?>
                                <tr>
                                    <td style="width: 30px;"><?= $i++ ?></td>
                                    <td><?= $row->no_order_custom ?></td>
                                    <?php if (!$isCustomer): ?>
                                        <td><?= $row->nama ?></td>
                                    <?php endif; ?>
                                    <td><?= $row->tanggal_order ? date('d/m/Y H:i', strtotime($row->tanggal_order)) : '-' ?>
                                    </td>
                                    <td class="d-none"><?= $row->tanggal_pengambilan ?></td>
                                    <td>Rp. <?= number_format($row->nominal_pelunasan, 0, ',', '.') ?></td>
                                    <td>
                                        <?php if ($row->sisa_pembayaran === null || $row->dp_pembayaran === null || ($row->dp_pembayaran == 0 && $row->sisa_pembayaran == $row->nominal_pelunasan)): ?>
                                            <span class="badge badge-danger">Belum Bayar</span>
                                        <?php elseif ($row->sisa_pembayaran == 0): ?>
                                            <span class="badge badge-success">Lunas</span>
                                        <?php elseif ($row->dp_pembayaran > 0): ?>
                                            <span class="badge badge-warning">DP</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php
                                        // Unified Status System
                                        $status_pesanan = $row->status_pesanan ?? 'menunggu_konfirmasi';
                                        $badge_class = 'secondary';
                                        $icon = 'clock';
                                        $status_text = '';

                                        switch ($status_pesanan) {
                                            case 'menunggu_konfirmasi':
                                                $badge_class = 'warning';
                                                $icon = 'hourglass-half';
                                                $status_text = 'Menunggu Konfirmasi Admin';
                                                break;
                                            case 'menunggu_pembayaran':
                                                $badge_class = 'info';
                                                $icon = 'credit-card';
                                                $status_text = 'Menunggu Pembayaran';
                                                break;
                                            case 'menunggu_input_meter':
                                                $badge_class = 'danger';
                                                $icon = 'ruler';
                                                $status_text = 'Menunggu Input Meter';
                                                break;
                                            case 'diproses':
                                                $badge_class = 'primary';
                                                $icon = 'cog';
                                                $status_text = 'Sedang Diproses';
                                                break;
                                            case 'selesai':
                                                $badge_class = 'success';
                                                $icon = 'check-circle';
                                                $status_text = 'Selesai';
                                                break;
                                            case 'ditolak':
                                                $badge_class = 'danger';
                                                $icon = 'times-circle';
                                                $status_text = 'Ditolak';
                                                break;
                                            default:
                                                $badge_class = 'secondary';
                                                $icon = 'fas fa-truck-pickup';
                                                $status_text = ucfirst(str_replace('_', ' ', $status_pesanan));
                                        }
                                        ?>
                                        <span class="badge badge-<?= $badge_class ?>">
                                            <i class="fas fa-<?= $icon ?>"></i> <?= $status_text ?>
                                        </span>

                                        <!-- Badge untuk request perubahan alamat (Admin/Kasir only) -->
                                        <?php if (!$isCustomer && isset($row->alamat_change_request) && $row->alamat_change_request && $row->alamat_change_approved === null): ?>
                                            <br>
                                            <span class="badge badge-warning mt-1" title="Ada permintaan perubahan alamat">
                                                <i class="fas fa-map-marker-alt"></i> Req. Alamat
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td style="width: 220px;">
                                        <?php

                                        // Define order status
                                        $isPending = $row->status_admin_konfirmasi == 0;
                                        $isConfirmed = $row->status_admin_konfirmasi == 1;
                                        $hasNoPayment = $row->dp_pembayaran == 0;
                                        $hasOutstandingPayment = $row->sisa_pembayaran > 0 || $row->sisa_pembayaran === null;
                                        $hasMissingMeter = isset($row->has_missing_meter) && $row->has_missing_meter;
                                        $isConfirmed = $row->status_admin_konfirmasi == 1;

                                        // Can edit/delete before payment and confirmation
                                        $canEdit = ($isKasir || $isCustomer) && $hasNoPayment;
                                        $canDelete = $isCustomer && $hasNoPayment && !$isConfirmed;
                                        $canPay = ($isKasir || $isCustomer) && $hasOutstandingPayment && $row->created_by_role != 'customer' && $isConfirmed;
                                        $canConfirm = !$isAdmin && $isPending;
                                        $canEditMeter = $isKasir && $hasNoPayment && ($row->status_pesanan != 'menunggu_pembayaran' && $row->status_pesanan != 'menunggu_konfirmasi');
                                        $hasAlamatChangeRequest = isset($row->alamat_change_request) && $row->alamat_change_request && $row->alamat_change_approved === null;
                                        ?>

                                        <!-- Detail Button -->
                                        <?php if (!$isAdmin): ?>
                                            <a class="btn btn-primary btn-sm mt-1"
                                                onclick="show_lg('<?= base_url('permintaan_custom/detail/' . $row->kode_permintaan_custom) ?>')">
                                                <i class="fas fa-eye"></i> Detail
                                            </a>
                                        <?php endif; ?>

                                        <!-- Edit Button -->
                                        <?php if ($canEdit): ?>
                                            <a class="btn btn-warning btn-sm mt-1 d-none"
                                                onclick="show_lg('<?= base_url('permintaan_custom/edit/' . $row->kode_permintaan_custom) ?>')">
                                                <i class="fas fa-edit"></i> Revisi
                                            </a>
                                        <?php endif; ?>

                                        <!-- Edit Meter Button (Kasir Only) -->
                                        <?php if ($canEditMeter): ?>
                                            <a class="btn btn-info btn-sm mt-1"
                                                onclick="show_lg('<?= base_url('permintaan_custom/kasir_edit_meter/' . $row->kode_permintaan_custom) ?>')">
                                                <i class="fas fa-ruler"></i> Edit Meter & Ongkos Jahit
                                            </a>
                                        <?php endif; ?>

                                        <!-- Delete Button (Customer Only) -->
                                        <?php if ($canDelete): ?>
                                            <a class="btn btn-danger btn-sm mt-1" onclick="notificationforDelete(event, this)"
                                                href="<?= base_url('permintaan_custom/delete/' . $row->kode_permintaan_custom) ?>">
                                                <i class="fas fa-trash"></i> Hapus
                                            </a>
                                        <?php endif; ?>

                                        <!-- Payment Button -->
                                        <?php if ($canPay): ?>
                                            <a class="btn btn-success btn-sm mt-1"
                                                onclick="show_lg('<?= base_url('transactions/pay_dp/' . $row->kode_permintaan_custom) ?>')">
                                                <i class="fas fa-money-check"></i> Bayar
                                            </a>
                                        <?php endif; ?>

                                        <!-- Confirm Button (Admin/Kasir) -->
                                        <?php if ($canConfirm): ?>
                                            <a class="btn btn-info btn-sm mt-1"
                                                onclick="show_lg('<?= base_url('permintaan_custom/Conrfirmrder/' . $row->kode_permintaan_custom) ?>')">
                                                <i class="fas fa-check-circle"></i> Konfirmasi
                                            </a>
                                        <?php endif; ?>

                                        <!-- Update Production Status (Admin/Kasir) -->
                                        <?php if (($isKasir) && in_array($row->status_pesanan ?? '', ['diproses', 'selesai'])): ?>
                                            <?php if ($row->status_pesanan === 'diproses'): ?>
                                                <button class="btn btn-success btn-sm mt-1"
                                                    onclick="updateProductionStatus(<?= $row->kode_permintaan_custom ?>, 'selesai')">
                                                    <i class="fas fa-check-double"></i> Tandai Selesai
                                                </button>
                                            <?php endif; ?>
                                        <?php endif; ?>

                                        <!-- Approve Alamat Change Request (Admin/Kasir) -->
                                        <?php if (($isKasir) && $hasAlamatChangeRequest): ?>
                                            <button class="btn btn-warning btn-sm mt-1"
                                                onclick="showApproveAlamatModal(<?= $row->kode_permintaan_custom ?>, '<?= htmlspecialchars($row->alamat_pengiriman ?? '', ENT_QUOTES) ?>', '<?= htmlspecialchars($row->alamat_change_request ?? '', ENT_QUOTES) ?>')">
                                                <i class="fas fa-map-marked-alt"></i> Approve Alamat
                                            </button>
                                        <?php endif; ?>

                                        <!-- Admin Actions After Confirmation -->
                                        <?php if ($isAdmin && $isConfirmed): ?>
                                            <a class="btn btn-primary btn-sm mt-1"
                                                onclick="show_lg('<?= base_url('permintaan_custom/detail/' . $row->kode_permintaan_custom) ?>')">
                                                <i class="fas fa-eye"></i> Detail
                                            </a>
                                            <a class="btn btn-danger btn-sm mt-1" onclick="notificationforDelete(event, this)"
                                                href="<?= base_url('permintaan_custom/delete/' . $row->kode_permintaan_custom) ?>">
                                                <i class="fas fa-trash"></i> Hapus
                                            </a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </section>
<?php endif; ?>

<!-- Modal Approve Alamat Change -->
<div class="modal fade" id="modalApproveAlamat" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-warning text-white">
                <h5 class="modal-title">
                    <i class="fas fa-map-marked-alt"></i> Approve Perubahan Alamat
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="formApproveAlamat">
                <input type="hidden" id="approve_kode_permintaan" name="kode_permintaan">
                <div class="modal-body">
                    <div class="form-group">
                        <label class="font-weight-bold">Alamat Saat Ini:</label>
                        <textarea class="form-control" id="approve_alamat_lama" rows="3" readonly></textarea>
                    </div>

                    <div class="form-group">
                        <label class="font-weight-bold text-primary">Alamat Baru yang Diminta:</label>
                        <textarea class="form-control bg-light" id="approve_alamat_baru" rows="3" readonly></textarea>
                    </div>

                    <div class="form-group">
                        <label for="approve_note">Catatan (Opsional):</label>
                        <textarea class="form-control" id="approve_note" name="note" rows="2"
                            placeholder="Tambahkan catatan jika diperlukan"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" onclick="processApproveAlamat(0)">
                        <i class="fas fa-times"></i> Tolak
                    </button>
                    <button type="button" class="btn btn-success" onclick="processApproveAlamat(1)">
                        <i class="fas fa-check"></i> Setujui
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    function showApproveAlamatModal(kode_permintaan, alamat_lama, alamat_baru) {
        $('#approve_kode_permintaan').val(kode_permintaan);
        $('#approve_alamat_lama').val(alamat_lama);
        $('#approve_alamat_baru').val(alamat_baru);
        $('#approve_note').val('');
        $('#modalApproveAlamat').modal('show');
    }

    function processApproveAlamat(approved) {
        const kode_permintaan = $('#approve_kode_permintaan').val();
        const note = $('#approve_note').val();
        const action = approved == 1 ? 'menyetujui' : 'menolak';

        if (!confirm(`Apakah Anda yakin akan ${action} perubahan alamat ini?`)) {
            return false;
        }

        $.ajax({
            url: '<?= base_url('permintaan_custom/approve_change_alamat/') ?>' + kode_permintaan,
            method: 'POST',
            data: {
                approved: approved,
                note: note,
                <?= csrf_token() ?>: '<?= csrf_hash() ?>'
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    alert(response.message);
                    $('#modalApproveAlamat').modal('hide');
                    location.reload();
                } else {
                    alert(response.message || 'Terjadi kesalahan');
                }
            },
            error: function() {
                alert('Terjadi kesalahan saat memproses approval');
            }
        });
    }

    function updateProductionStatus(kode_permintaan, newStatus) {
        const statusText = newStatus === 'selesai' ? 'Selesai' : 'Diproses';

        if (!confirm(`Apakah Anda yakin akan mengubah status pesanan menjadi ${statusText}?`)) {
            return false;
        }

        $.ajax({
            url: '<?= base_url('permintaan_custom/updateOrderStatus/') ?>' + kode_permintaan,
            method: 'POST',
            data: {
                status_pesanan: newStatus,
                <?= csrf_token() ?>: '<?= csrf_hash() ?>'
            },
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    alert(response.message);
                    location.reload();
                } else {
                    alert(response.message || 'Terjadi kesalahan');
                }
            },
            // error: function(e) {
            //     console.log(e)
            //     alert('Terjadi kesalahan saat mengupdate status pesanan');
            // }
        });
    }

    function showPemesanan(param) {

        var user_id = "<?= $user_id ?>"

        $.ajax({
            url: "<?= base_url() ?>permintaan_custom/showPemesanan",
            type: "POST",
            data: {
                user_id: user_id,
                status: param,
            },
            success: (response) => {

                $('#row-pemesanan_custom').html('')

                if (response.success == true) {

                    var html = ``
                    $.each(response.data, function(i, v) {

                        var status_pembayaran = '';

                        if (v.sisa_pembayaran === null || v.dp_pembayaran === null || (v
                                .dp_pembayaran == 0 && v.sisa_pembayaran == v.nominal_pelunasan)) {
                            status_pembayaran +=
                                `<span class="badge badge-danger badge-lg">Belum Bayar</span>`
                        } else if (v.sisa_pembayaran == 0) {
                            status_pembayaran += `
                                 <span class="badge badge-success badge-lg">Lunas</span>
                            `
                        } else if (v.dp_pembayaran > 0) {
                            status_pembayaran += `
                                <span class="badge badge-warning badge-lg">DP Dibayar</span>
                            `
                        }

                        var status_pesanan = v.status_pesanan ?? 'meunggu_konfirmasi'
                        var badge_class = 'secondary';
                        var icon = 'clock';
                        var status_text = '';

                        var badge_pemesanan = '';
                        switch (status_pesanan) {
                            case 'menunggu_konfirmasi':
                                badge_class = 'warning';
                                icon = 'hourglass-half';
                                status_text = 'Menunggu Konfrimasi Admin'
                                break;
                            case 'menunggu_pembayaran':
                                badge_class = 'info';
                                icon = 'credit-card';
                                status_text = 'Menunggu Pembayaran'
                                break;
                            case 'menunggu_input_meter':
                                badge_class = 'danger';
                                icon = 'ruler';
                                status_text = 'Menunggu Input Meter'
                                break;
                            case 'diproses':
                                badge_class = 'primary';
                                icon = 'cog';
                                status_text = 'Sedang Diproses';
                                break;
                            case 'selesai':
                                badge_class = 'success';
                                icon = 'check-circle';
                                status_text = 'Selesai';
                                break;
                            case 'ditolak':
                                badge_class = 'danger';
                                icon = 'times-circle';
                                status_text = 'Ditolak';
                                break;
                            default:
                                badge_class = 'secondary';
                                icon = 'fas fa fa-truck-pickup';
                                status_text = v.status_pesanan
                                break;
                        }

                        badge_pemesanan += `
                            <span class="badge badge-${badge_class} badge-lg">
                                <i class="fas fa-${icon}"></i> ${status_text}
                            </span>
                        `

                        var hasNoPayment = (v.dp_pembayaran == 0);
                        var hasOutstandingPayment = (v.sisa_pembayaran > 0 || v.sisa_pembayaran ===
                            null);
                        var hasMissingMeter = (v.has_missing_meter) && v.has_missing_meter
                        var isConfirmed = (v.status_admin_konfirmasi == 1);

                        var currentUserRole = "<?= auth()->user()->role ?>"
                        var createdByRole = v.created_by_role ?? 'customer'

                        var canPayByRole = true;

                        if (currentUserRole == 'customer') {
                            canPayByRole = (createdByRole == 'customer')
                        }

                        var canEdit = (hasNoPayment && hasNoPayment)
                        var canDelete = (hasNoPayment && !isConfirmed)
                        var canPay = (hasOutstandingPayment && canPayByRole && isConfirmed)

                        html += `
                        <div class="col-md-6 col-lg-4 mb-4">
                                <div class="card shadow-sm h-100" style="border-radius: 15px; border: 2px solid #e0e0e0; transition: transform 0.2s;">
                                    <div class="card-header" style="background: #e5e7eb; color: #111827; border-radius: 13px 13px 0 0;">
                                        <h5 class="mb-0" style="color: #111827 !important;">
                                            <i class="fas fa-receipt"></i> ${v.no_order_custom}
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <!-- Order Date -->
                                        <div class="mb-2">
                                            <small class="text-muted"><i class="fas fa-calendar"></i> Tanggal Order</small>
                                            <p class="mb-0 font-weight-bold"> ${v.tanggal_order ? moment(v.tanggal_order).format('DD/MM/YYYY HH:mm') : '-'} </p>
                                        </div>

                                        <!-- Pickup Date -->
                                        <div class="mb-2 d-none">
                                            <small class="text-muted"><i class="fas fa-calendar-check"></i> Tanggal Pengambilan</small>
                                            <p class="mb-0 font-weight-bold">${v.tanggal_pengambilan ? moment(v.tanggal_pengambilan).format('DD-MM-YYYY') : '-'}</p>
                                        </div>

                                        <!-- Total -->
                                        <div class="mb-3">
                                            <small class="text-muted"><i class="fas fa-money-bill-wave"></i> Total Pembayaran</small>
                                            <h4 class="mb-0 text-primary">Rp. ${parseFloat(v.nominal_pelunasan).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".")}</h4>
                                        </div>

                                        <!-- Payment Status -->
                                        <div class="mb-2">
                                            <small class="text-muted">Status Pembayaran:</small><br>
                                            ${status_pembayaran}
                                        </div>

                                        <!-- Unified Order Status -->
                                        <div class="mb-3">
                                            <small class="text-muted">Status Pesanan:</small><br>
                                            ${badge_pemesanan}
                                        </div>
                                    </div>

                                    <!-- Action Buttons -->
                                    <div class="card-footer bg-white" style="border-radius: 0 0 13px 13px;">

                                        <div class="btn-group-vertical w-100">
                                            <!-- Detail Button -->
                                            <button class="btn btn-primary btn-sm mb-1" onclick="show_lg('<?= base_url('permintaan_custom/detail/') ?>${v.kode_permintaan_custom}')">
                                                <i class="fas fa-eye"></i> Lihat Detail
                                            </button>

                                            <!-- Edit Button -->
                                            <button class="btn btn-warning btn-sm mb-1 d-none ${canEdit ? '' : 'd-none'}" onclick="show_lg('${v.kode_permintaan_custom}')">
                                                <i class="fas fa-edit"></i> Revisi Pesanan
                                            </button>

                                            <!-- Delete Button -->
                                            <a class="btn btn-danger btn-sm mb-1 ${canDelete ? '' : 'd-none'}" onclick="notificationforDelete(event, this)" href="<?= base_url('permintaan_custom/delete/') ?>${v.kode_permintaan_custom}">
                                                <i class="fas fa-trash"></i> Hapus Pesanan
                                            </a>

                                            <!-- Payment Button -->
                                            <button class="btn btn-success btn-sm ${canPay ? '' : 'd-none'}" onclick="show_lg('<?= base_url('transactions/pay_dp/') ?>${v.kode_permintaan_custom}')">
                                                <i class="fas fa-money-check"></i> Bayar Sekarang
                                            </button>

                                        </div>
                                    </div>
                                </div>
                            </div>
                        `
                    })

                    $('#row-pemesanan_custom').html(html)
                } else {

                    if (param == 'lama') {
                        $('#row-pemesanan_custom').html(`
                            <div class="col-12">
                                <div class="alert shadow-sm text-center py-5" style="background: #e5e7eb; color: #111827; border: none; border-radius: 15px;">
                                    <i class="fas fa-shopping-bag fa-3x mb-3"></i>
                                    <h4>Belum Ada History Pesanan Yang Telah Selesai</h4>
                                </div>
                            </div>
                        `)
                    } else {

                        $('#row-pemesanan_custom').html(`
                            <div class="col-12">
                                <div class="alert shadow-sm text-center py-5" style="background: #e5e7eb; color: #111827; border: none; border-radius: 15px;">
                                    <i class="fas fa-shopping-bag fa-3x mb-3"></i>
                                    <h4>Belum Ada Pesanan</h4>
                                    <p>Mulai buat pesanan custom gamis Anda sekarang!</p>
                                </div>
                            </div>
                        `)
                    }

                }
            },
            error: (error) => {

            },
            complete: (complete) => {

            }
        })

    }
</script>

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