<?php
// Deteksi role user
$user = auth()->user();
$isKasir = false;
$isCustomer = false;

if ($user) {
    $role = $user->role ?? '';
    $isKasir = in_array($role, ['kasir', 'admin']);
    $isCustomer = ($role == 'customer');
}

// Hitung informasi pembayaran
$nominalPelunasan = $data->nominal_pelunasan;
$dpPembayaran = $data->dp_pembayaran ?? 0;
$sisaPembayaran = $data->sisa_pembayaran ?? $nominalPelunasan;
$statusPelunasan = $data->status_pelunasan ?? 0;
$sudahBayarDP = $statusPelunasan == 1;
$sudahLunas = $statusPelunasan == 2;

// Tentukan jumlah yang harus dibayar
if ($sudahBayarDP) {
    $jumlahHarusBayar = $sisaPembayaran;
    $keterangan = "Sisa pembayaran (Pelunasan)";
} else {
    $jumlahHarusBayar = $nominalPelunasan;
    $keterangan = "Total pembayaran";
}
?>

<div class="modal-header bg-light">
    <h4 class="modal-title">
        <i class="fas fa-cash-register"></i>
        <?= $sudahBayarDP ? 'Pelunasan Pembayaran' : 'Pembayaran Pesanan' ?>
    </h4>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">×</span>
    </button>
</div>
<div class="modal-body">
    <!-- Alert Info untuk Item Custom (Bawa Model/Kain Sendiri) -->
    <?php
    $hasCustomItems = false;
    $customItemsInfo = [];
    foreach ($detail_model as $detail) {
        if ($detail->upload_model_sendiri == 1 || $detail->bawa_kain_sendiri == 1) {
            $hasCustomItems = true;
            $customItemsInfo[] = [
                'model_sendiri' => $detail->upload_model_sendiri == 1,
                'kain_sendiri' => $detail->bawa_kain_sendiri == 1
            ];
        }
    }
    ?>

    <!-- Info Pembayaran -->
    <div class="card card-outline card-info mb-3">
        <div class="card-header">
            <h3 class="card-title"><i class="fas fa-info-circle"></i> Informasi Pembayaran</h3>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <table class="table table-sm table-borderless">
                        <tr>
                            <th width="50%">Total Pesanan:</th>
                            <td><strong>Rp <?= number_format($nominalPelunasan, 0, ",", ".") ?></strong></td>
                        </tr>
                        <?php if ($sudahBayarDP): ?>
                            <tr>
                                <th>DP Dibayar:</th>
                                <td><span class="text-success">Rp <?= number_format($dpPembayaran, 0, ",", ".") ?></span></td>
                            </tr>
                            <tr class="bg-light">
                                <th>Sisa Pembayaran:</th>
                                <td><strong class="text-danger">Rp <?= number_format($sisaPembayaran, 0, ",", ".") ?></strong></td>
                            </tr>
                        <?php endif; ?>
                        <tr>
                            <th>Status:</th>
                            <td>
                                <?php if ($sudahLunas): ?>
                                    <span class="badge badge-success">Lunas</span>
                                <?php elseif ($sudahBayarDP): ?>
                                    <span class="badge badge-warning">DP (Menunggu Pelunasan)</span>
                                <?php else: ?>
                                    <span class="badge badge-danger">Belum Dibayar</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <?php if ($sudahBayarDP): ?>
                        <div class="alert alert-info mb-0">
                            <i class="fas fa-exclamation-circle"></i> <strong>Informasi:</strong><br>
                            • Ini adalah pembayaran <strong>PELUNASAN</strong><br>
                            • DP Sebelumnya: <strong>Rp <?= number_format($dpPembayaran, 0, ",", ".") ?></strong><br>
                            • Jumlah yang harus dibayar: <strong>Rp <?= number_format($sisaPembayaran, 0, ",", ".") ?></strong><br>
                            • Harus bayar PENUH nominal sisa pembayaran!
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <form method="POST" action="<?= base_url('transactions/pay_proccess/' . $data->kode_permintaan_custom) ?>" enctype="multipart/form-data" id="formPembayaran">
        <?= csrf_field() ?>

        <!-- Debug Info (hanya untuk development) -->
        <?php if (ENVIRONMENT !== 'production'): ?>
            <div class="alert alert-secondary alert-dismissible">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                <small>
                    <strong>Debug Info:</strong><br>
                    Order: <?= $data->no_order_custom ?? 'N/A' ?><br>
                    Total Items: <?= isset($detail_model) ? count($detail_model) : 0 ?><br>
                    <?php if (isset($detail_model) && count($detail_model) > 0): ?>
                        Items Detail:<br>
                        <?php foreach ($detail_model as $idx => $detail): ?>
                            - Item #<?= ($idx + 1) ?>:
                            Model: <?= $detail->upload_model_sendiri == 1 ? 'Sendiri' : ($detail->nama_model ?? 'N/A') ?>,
                            Kain: <?= $detail->bawa_kain_sendiri == 1 ? 'Sendiri' : ($detail->nama_jenis_kain ?? 'N/A') ?>
                            <br>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </small>
            </div>
        <?php endif; ?>

        <!-- Warning Meter Pemakaian Belum Diisi -->
        <?php
        $hasMissingMeter = false;
        foreach ($detail_model as $detail) {
            // Skip validation for items with bawa_kain_sendiri (customer brings own fabric)
            if ($detail->bawa_kain_sendiri == 1) {
                continue;
            }
            // Check if meter is empty or zero for regular items
            if (empty($detail->meter_pemakaian) || $detail->meter_pemakaian == 0) {
                $hasMissingMeter = true;
                break;
            }
        }
        ?>
        <?php if ($hasMissingMeter): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> <strong>PERHATIAN!</strong><br>
                • Meter pemakaian kain belum diinputkan<br>
                • Pembayaran <strong>TIDAK DAPAT DIPROSES</strong> sampai meter pemakaian diisi<br>
                • Silakan hubungi <strong>Kasir</strong> untuk menginputkan meter pemakaian terlebih dahulu<br>
                • Tombol pembayaran akan dinonaktifkan hingga semua meter pemakaian terisi
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-12">
                <!-- Informasi Transfer -->
                <div class="card card-outline card-primary mb-3">
                    <div class="card-header">
                        <h3 class="card-title"><i class="fas fa-university"></i> Rekening Tujuan Transfer</h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="alert alert-light border">
                                    <i class="fas fa-landmark"></i> <strong>BCA</strong> - 8945242589<br>
                                    a.n <strong>Annisa Syar'i (Naning Indras)</strong>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Form Pembayaran -->
                <div class="card card-outline card-success">
                    <div class="card-header">
                        <h3 class="card-title"><i class="fas fa-money-bill-wave"></i> Detail Pembayaran</h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <!-- Jumlah Pembayaran -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="jumlah_bayar">
                                        <i class="fas fa-money-check-alt"></i> Jumlah Pembayaran <span class="text-danger">*</span>
                                    </label>
                                    <input type="number"
                                        class="form-control form-control-lg"
                                        id="jumlah_bayar"
                                        name="jumlah_bayar"
                                        placeholder="Masukkan jumlah pembayaran"
                                        required
                                        min="<?= $sudahBayarDP ? $sisaPembayaran : 0 ?>"
                                        max="<?= $jumlahHarusBayar ?>"
                                        value="<?= $jumlahHarusBayar ?>">
                                    <small class="form-text text-muted">
                                        <?= $keterangan ?>: <strong>Rp <?= number_format($jumlahHarusBayar, 0, ",", ".") ?></strong>
                                        <?php if ($sudahBayarDP): ?>
                                            <br><span class="text-danger">Harus bayar PENUH untuk pelunasan!</span>
                                        <?php else: ?>
                                            <br>Bisa bayar sebagian (DP) atau lunas
                                        <?php endif; ?>
                                    </small>
                                    <div id="statusBayarPreview" class="mt-2"></div>
                                </div>
                            </div>

                            <!-- Metode Pembayaran -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="metode_pembayaran">
                                        <i class="fas fa-credit-card"></i> Metode Pembayaran <span class="text-danger">*</span>
                                    </label>
                                    <select class="custom-select custom-select-lg" id="metode_pembayaran" name="metode_pembayaran" required>
                                        <option value="">-- Pilih Metode --</option>
                                        <!-- <option value="cash">Tunai / Cash</option> -->
                                        <option value="transfer" selected>Transfer Bank</option>
                                    </select>
                                </div>
                            </div>

                            <!-- Upload Bukti Transfer (Customer Only) -->
                            <?php if ($isCustomer): ?>
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="bukti_transfer">
                                            <i class="fas fa-receipt"></i> Upload Bukti Transfer <span class="text-danger">*</span>
                                        </label>
                                        <div class="custom-file">
                                            <input type="file"
                                                class="custom-file-input"
                                                id="bukti_transfer"
                                                name="bukti_transfer"
                                                accept="image/*">
                                            <label class="custom-file-label" for="bukti_transfer">Pilih file...</label>
                                        </div>
                                        <small class="form-text text-muted">
                                            Format: JPG, PNG, JPEG (Max 2MB)
                                        </small>
                                        <div id="imagePreview" class="mt-2"></div>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <!-- Alamat Pengiriman - DISABLED: Input alamat sudah dipindahkan ke menu Tambah dan Revisi Pesanan -->
                            <?php /* COMMENTED OUT - Alamat input moved to create/edit form
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="alamat_pengiriman">
                                        <i class="fas fa-map-marker-alt"></i> Alamat Pengiriman <span class="text-danger">*</span>
                                        <?php if ($data->alamat_locked == 1): ?>
                                            <span class="badge badge-warning ml-2">
                                                <i class="fas fa-lock"></i> Terkunci
                                            </span>
                                        <?php endif; ?>
                                    </label>
                                    <textarea class="form-control"
                                        id="alamat_pengiriman"
                                        name="alamat_pengiriman"
                                        rows="3"
                                        placeholder="Masukkan alamat lengkap pengiriman"
                                        <?= $data->alamat_locked == 1 ? 'readonly' : '' ?>
                                        required><?= $data->alamat_pengiriman ?? '' ?></textarea>

                                    <?php if ($data->alamat_locked == 1): ?>
                                        <small class="form-text text-warning">
                                            <i class="fas fa-exclamation-triangle"></i>
                                            Alamat sudah terkunci setelah pembayaran.
                                            <?php if ($role == 'customer'): ?>
                                                <a href="javascript:void(0)" onclick="showRequestChangeAlamat()">Ajukan perubahan alamat</a>
                                            <?php endif; ?>
                                        </small>
                                    <?php else: ?>
                                        <small class="form-text text-muted">Alamat untuk pengiriman pesanan</small>
                                    <?php endif; ?>
                                </div>
                            </div>
                            */ ?>

                            <!-- Tanggal Pelunasan -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="tanggal_pelunasan">
                                        <i class="fas fa-calendar-check"></i> Tanggal Pembayaran <span class="text-danger">*</span>
                                    </label>
                                    <input type="text"
                                        class="form-control"
                                        value="<?= date('d/m/Y H:i') ?>"
                                        readonly>
                                    <input type="hidden" name="tanggal_pelunasan" value="<?= date('Y-m-d H:i:s') ?>">
                                    <small class="form-text text-muted d-none">Tanggal pembayaran otomatis mengikuti waktu saat ini</small>
                                </div>
                            </div>

                            <!-- Estimasi Pengerjaan -->
                            <?php if (auth()->user()->role == 'customer'): ?>
                                <div class="col-md-12">
                                    <div class="alert alert-warning">
                                        <i class="fas fa-clock"></i> <strong>Estimasi Pengerjaan:</strong> <?= $data->estimasi_pengerjaan ?? 'Estimasi pengerjaan 7-14 hari tergantung desain & proses' ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Detail Pesanan -->
        <div class="card card-outline card-secondary">
            <div class="card-header">
                <h3 class="card-title"><i class="fas fa-file-invoice"></i> Detail Pesanan</h3>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <table class="table table-sm table-borderless">
                            <tr>
                                <th width="45%"><i class="fas fa-barcode"></i> No Order:</th>
                                <td><code><?= $data->no_order_custom ?></code></td>
                            </tr>
                            <tr>
                                <th><i class="fas fa-user"></i> Customer:</th>
                                <td><?= $data->nama ?></td>
                            </tr>
                            <tr>
                                <th><i class="fas fa-calendar"></i> Tanggal Order:</th>
                                <td><?= $data->tanggal_order ?></td>
                            </tr>
                            <tr class="d-none">
                                <th><i class="fas fa-calendar-check"></i> Tanggal Pengambilan:</th>
                                <td><?= $data->tanggal_pengambilan ?? '-' ?></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <table class="table table-sm table-borderless">
                            <tr>
                                <th width="45%"><i class="fas fa-shopping-cart"></i> Total Order:</th>
                                <td><?= $data->total_order  ?> pcs</td>
                            </tr>
                            <tr>
                                <th><i class="fas fa-money-bill-wave"></i> Nominal Pelunasan:</th>
                                <td><strong>Rp <?= number_format($data->nominal_pelunasan, 0, ",", ".") ?></strong></td>
                            </tr>
                            <tr>
                                <th><i class="fas fa-info-circle"></i> Status Pelunasan:</th>
                                <td>
                                    <?php if ($data->status_pelunasan == 2): ?>
                                        <span class="badge badge-success">Lunas</span>
                                    <?php elseif ($data->status_pelunasan == 1): ?>
                                        <span class="badge badge-warning">DP</span>
                                    <?php else: ?>
                                        <span class="badge badge-danger">Belum Dibayar</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>

                <!-- Item Pesanan -->
                <h6 class="mt-3 mb-2">
                    <i class="fas fa-boxes"></i> Item Pesanan
                    <?php if (!empty($detail_model)): ?>
                        <span class="badge badge-secondary ml-2"><?= count($detail_model) ?> Item</span>
                    <?php endif; ?>
                </h6>

                <?php if (!empty($detail_model)): ?>
                    <?php
                    $itemNumber = 1;
                    foreach ($detail_model as $detail):
                        $riwayat = $riwayatPerubahanModel
                            ->where('id_detail_order', $detail->id_detail_order)
                            ->where('status', 1)
                            ->orderBy('created_at', 'DESC')
                            ->first();
                        $message = $riwayat ? $riwayat->keterangan_permintaan_revisi : 'Tidak ada revisi';

                        // Check if this is custom item (upload model sendiri + bawa kain sendiri)
                        $isCustomItem = ($detail->upload_model_sendiri == 1 && $detail->bawa_kain_sendiri == 1);
                    ?>

                        <!-- Item Card -->
                        <?php if ($isCustomer): ?>
                            <div class="card mb-3" style="border: 2px solid #d1d5db; border-radius: 8px;">
                                <div class="card-header" style="background: #e5e7eb; color: #111827; border-bottom: 2px solid #d1d5db;">
                                    <h6 class="mb-0">
                                        <i class="fas fa-shopping-bag"></i> Item #<?= $itemNumber++ ?>
                                        <span class="float-right">
                                            <?php if ($detail->upload_model_sendiri == 1): ?>
                                                <span class="badge badge-info mr-1">
                                                    <i class="fas fa-upload"></i> Model Sendiri
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($detail->bawa_kain_sendiri == 1): ?>
                                                <span class="badge badge-info">
                                                    <i class="fas fa-hand-holding"></i> Kain Sendiri
                                                </span>
                                            <?php endif; ?>
                                        </span>
                                    </h6>
                                </div>
                            <?php else: ?>
                                <div class="card mb-3 border-info">
                                    <div class="card-header bg-info text-white">
                                        <h6 class="mb-0">
                                            <i class="fas fa-shopping-bag"></i> Item #<?= $itemNumber++ ?>
                                            <span class="float-right">
                                                <?php if ($detail->upload_model_sendiri == 1): ?>
                                                    <span class="badge badge-light text-dark mr-1">
                                                        <i class="fas fa-upload"></i> Model Sendiri
                                                    </span>
                                                <?php endif; ?>
                                                <?php if ($detail->bawa_kain_sendiri == 1): ?>
                                                    <span class="badge badge-light text-dark">
                                                        <i class="fas fa-hand-holding"></i> Kain Sendiri
                                                    </span>
                                                <?php endif; ?>
                                            </span>
                                        </h6>
                                    </div>
                                <?php endif; ?>
                                <div class="card-body">
                                    <div class="row">
                                        <!-- Model Column -->
                                        <div class="col-md-6 mb-3 mb-md-0">
                                            <div class="card h-100">
                                                <?php if ($isCustomer): ?>
                                                    <div class="card-header" style="background: #e5e7eb; color: #111827; border-bottom: 2px solid #d1d5db;">
                                                        <strong><i class="fas fa-shirt"></i> Model Gamis</strong>
                                                    </div>
                                                <?php else: ?>
                                                    <div class="card-header bg-success text-white">
                                                        <strong><i class="fas fa-shirt"></i> Model Gamis</strong>
                                                    </div>
                                                <?php endif; ?>
                                                <div class="card-body">
                                                    <?php if (!empty($detail->foto_model)): ?>
                                                        <div class="text-center mb-3">
                                                            <img src="<?= base_url($detail->foto_model) ?>" alt="Model" class="img-fluid rounded" style="max-height: 150px; object-fit: cover;" />
                                                        </div>
                                                    <?php else: ?>
                                                        <div class="text-center mb-3">
                                                            <div class="bg-light rounded d-flex align-items-center justify-content-center" style="height: 150px;">
                                                                <div class="text-center">
                                                                    <i class="fas fa-upload fa-3x text-info mb-2"></i>
                                                                    <p class="mb-0 text-muted"><strong>Model Upload Sendiri</strong></p>
                                                                    <small class="text-muted">Customer membawa desain sendiri</small>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    <?php endif; ?>

                                                    <?php if ($detail->upload_model_sendiri == 1): ?>
                                                        <div class="alert alert-info mb-3">
                                                            <i class="fas fa-info-circle"></i> <strong>Informasi:</strong> Customer mengupload model/desain sendiri untuk item ini.
                                                        </div>
                                                    <?php endif; ?>

                                                    <table class="table table-sm table-borderless">
                                                        <tr>
                                                            <th width="50%">Nama Model:</th>
                                                            <td>
                                                                <?php if (!empty($detail->nama_model)): ?>
                                                                    <?= $detail->nama_model ?>
                                                                <?php elseif ($detail->upload_model_sendiri == 1): ?>
                                                                    <span class="badge badge-info"><i class="fas fa-upload"></i> Model Upload Sendiri</span>
                                                                <?php else: ?>
                                                                    <span class="text-muted">-</span>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <th>Ukuran:</th>
                                                            <td><?= $detail->ukuran_gamis ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>Jumlah (Pcs):</th>
                                                            <td><?= $detail->jumlah_pcs ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>Ongkos Pengerjaan:</th>
                                                            <td><strong>Rp. <?= number_format($detail->subtotal_detail_order, 0, ",", ".") ?></strong></td>
                                                        </tr>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Kain Column -->
                                        <div class="col-md-6">
                                            <div class="card h-100">
                                                <?php if ($isCustomer): ?>
                                                    <div class="card-header" style="background: #e5e7eb; color: #111827; border-bottom: 2px solid #d1d5db;">
                                                        <strong><i class="fas fa-fabric"></i> Jenis Kain</strong>
                                                    </div>
                                                <?php else: ?>
                                                    <div class="card-header bg-warning text-dark">
                                                        <strong><i class="fas fa-fabric"></i> Jenis Kain</strong>
                                                    </div>
                                                <?php endif; ?>
                                                <div class="card-body">
                                                    <?php if ($detail->bawa_kain_sendiri == 1): ?>
                                                        <div class="text-center mb-3">
                                                            <div class="bg-light rounded d-flex align-items-center justify-content-center" style="height: 150px;">
                                                                <div class="text-center">
                                                                    <i class="fas fa-hand-holding fa-3x text-info mb-2"></i>
                                                                    <p class="mb-0 text-muted"><strong>Bawa Kain Sendiri</strong></p>
                                                                    <small class="text-muted">Customer menyediakan kain sendiri</small>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="alert alert-info">
                                                            <i class="fas fa-info-circle"></i> <strong>Informasi:</strong> Customer membawa kain sendiri untuk item ini. Tidak ada pembelian kain dari toko.
                                                        </div>
                                                        <table class="table table-sm table-borderless">
                                                            <tr>
                                                                <th width="50%">Total Harga Kain:</th>
                                                                <td><strong>Rp. 0</strong></td>
                                                            </tr>
                                                        </table>
                                                    <?php else: ?>
                                                        <?php if (!empty($detail->foto_jenis_kain)): ?>
                                                            <div class="text-center mb-3">
                                                                <img src="<?= base_url($detail->foto_jenis_kain) ?>" alt="Kain" class="img-fluid rounded" style="max-height: 150px; object-fit: cover;" />
                                                            </div>
                                                        <?php endif; ?>
                                                        <table class="table table-sm table-borderless">
                                                            <tr>
                                                                <th width="50%">Jenis Kain:</th>
                                                                <td><?= !empty($detail->nama_jenis_kain) ? $detail->nama_jenis_kain : '-' ?></td>
                                                            </tr>
                                                            <tr>
                                                                <th>Warna:</th>
                                                                <td><?= !empty($detail->warna) ? $detail->warna : '-' ?></td>
                                                            </tr>
                                                            <tr>
                                                                <th>Meter Pemakaian:</th>
                                                                <td><?= isset($detail->meter_pemakaian) ? $detail->meter_pemakaian . ' m' : '-' ?></td>
                                                            </tr>
                                                            <tr>
                                                                <th>Harga:</th>
                                                                <td><strong>Rp. <?= number_format($detail->subtotal_detail_kain ?? 0, 0, ",", ".") ?></strong></td>
                                                            </tr>
                                                        </table>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                </div>
                            <?php endforeach; ?>

                        <?php else: ?>
                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle fa-2x mb-2 d-block"></i>
                                <h5>Tidak ada item pesanan ditemukan</h5>
                                <p class="mb-2">Kemungkinan penyebab:</p>
                                <ul class="text-left mb-0">
                                    <li>Item belum ditambahkan ke pesanan ini</li>
                                    <li>Terjadi kesalahan saat memuat data dari database</li>
                                    <li>Item mungkin terhapus atau tidak valid</li>
                                </ul>
                                <hr>
                                <small class="text-muted">
                                    <i class="fas fa-info-circle"></i> Jika pesanan seharusnya memiliki item, silakan hubungi admin atau refresh halaman.
                                </small>
                            </div>
                        <?php endif; ?>
                            </div>
            </div>

            <!-- Alert Validation -->
            <div id="alertValidation" class="alert alert-danger mt-3" style="display:none;">
                <i class="fas fa-exclamation-triangle"></i> <span id="alertMessage"></span>
            </div>

            <!-- Submit Button -->
            <div class="row mt-3">
                <div class="col-12">
                    <button type="submit" class="btn btn-success btn-lg btn-block" id="btnSubmit" <?= $hasMissingMeter ? 'disabled' : '' ?>>
                        <i class="fas fa-check-circle"></i> <?= $hasMissingMeter ? 'Meter Pemakaian Belum Diisi' : 'Proses Pembayaran' ?>
                    </button>
                    <button type="button" class="btn btn-secondary btn-lg btn-block" data-dismiss="modal">
                        <i class="fas fa-times-circle"></i> Batal
                    </button>
                </div>
            </div>
    </form>
</div>

<script>
    $(document).ready(function() {
        // Data pembayaran
        const nominalPelunasan = <?= $nominalPelunasan ?>;
        const dpPembayaran = <?= $dpPembayaran ?>;
        const sisaPembayaran = <?= $sisaPembayaran ?>;
        const statusPelunasan = <?= $statusPelunasan ?>;
        const sudahBayarDP = statusPelunasan == 1;
        const isCustomer = <?= $isCustomer ? 'true' : 'false' ?>;
        const isKasir = <?= $isKasir ? 'true' : 'false' ?>;

        // Preview status pembayaran
        function previewStatusPembayaran() {
            const jumlahBayar = parseFloat($('#jumlah_bayar').val()) || 0;
            const previewDiv = $('#statusBayarPreview');

            if (jumlahBayar > 0) {
                if (sudahBayarDP) {
                    // Pembayaran pelunasan - harus TEPAT sama
                    if (jumlahBayar < sisaPembayaran) {
                        previewDiv.html('<div class="alert alert-danger"><i class="fas fa-times-circle"></i> <strong>DITOLAK!</strong> Jumlah kurang dari sisa pembayaran.<br>Harus bayar TEPAT: <strong>Rp ' + sisaPembayaran.toLocaleString('id-ID') + '</strong></div>');
                    } else if (jumlahBayar == sisaPembayaran) {
                        previewDiv.html('<div class="alert alert-success"><i class="fas fa-check-circle"></i> <strong>BENAR!</strong> Status akan menjadi: <strong>LUNAS</strong></div>');
                    } else {
                        previewDiv.html('<div class="alert alert-danger"><i class="fas fa-times-circle"></i> <strong>DITOLAK!</strong> Jumlah lebih dari sisa pembayaran.<br>Harus bayar TEPAT: <strong>Rp ' + sisaPembayaran.toLocaleString('id-ID') + '</strong></div>');
                    }
                } else {
                    // Pembayaran pertama
                    if (jumlahBayar < nominalPelunasan) {
                        const sisa = nominalPelunasan - jumlahBayar;
                        previewDiv.html('<div class="alert alert-warning"><i class="fas fa-info-circle"></i> Status akan menjadi: <strong>DP</strong><br>Sisa: Rp ' + sisa.toLocaleString('id-ID') + '</div>');
                    } else if (jumlahBayar == nominalPelunasan) {
                        previewDiv.html('<div class="alert alert-success"><i class="fas fa-check-circle"></i> Status akan menjadi: <strong>LUNAS</strong></div>');
                    } else {
                        previewDiv.html('<div class="alert alert-warning"><i class="fas fa-exclamation-circle"></i> Jumlah melebihi total pesanan</div>');
                    }
                }
            } else {
                previewDiv.html('');
            }
        }

        $('#jumlah_bayar').on('input', previewStatusPembayaran);

        // Preview bukti transfer (customer)
        <?php if ($isCustomer): ?>
            $('#bukti_transfer').on('change', function() {
                const file = this.files[0];
                if (file) {
                    // Validasi ukuran file (max 2MB)
                    if (file.size > 2 * 1024 * 1024) {
                        alert('Ukuran file terlalu besar! Maximum 2MB');
                        $(this).val('');
                        $('#imagePreview').html('');
                        $(this).next('.custom-file-label').html('Pilih file...');
                        return;
                    }

                    // Validasi tipe file
                    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png'];
                    if (!allowedTypes.includes(file.type)) {
                        alert('Format file tidak valid! Gunakan JPG, JPEG, atau PNG');
                        $(this).val('');
                        $('#imagePreview').html('');
                        $(this).next('.custom-file-label').html('Pilih file...');
                        return;
                    }

                    // Preview image
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        $('#imagePreview').html('<img src="' + e.target.result + '" class="img-thumbnail" style="max-height: 200px;">');
                    }
                    reader.readAsDataURL(file);

                    // Update label
                    const fileName = file.name;
                    $(this).next('.custom-file-label').html(fileName);
                } else {
                    $('#imagePreview').html('');
                }
            });
        <?php endif; ?>

        // Validasi form sebelum submit
        $('#formPembayaran').on('submit', function(e) {
            const jumlahBayar = parseFloat($('#jumlah_bayar').val()) || 0;
            let error = '';

            // Validasi jumlah minimum dan maksimum
            if (sudahBayarDP) {
                // Untuk pelunasan, harus TEPAT sama dengan sisa pembayaran
                if (jumlahBayar != sisaPembayaran) {
                    error = 'Pembayaran pelunasan harus TEPAT sebesar sisa pembayaran: Rp ' + sisaPembayaran.toLocaleString('id-ID');
                }
            } else {
                // Untuk pembayaran pertama (DP)
                if (jumlahBayar <= 0) {
                    error = 'Jumlah pembayaran harus lebih dari 0';
                } else if (jumlahBayar > nominalPelunasan) {
                    error = 'Jumlah pembayaran tidak boleh melebihi total pesanan';
                }
            }

            <?php if ($isCustomer): ?>
                // Validasi bukti transfer (customer)
                if ($('#bukti_transfer')[0].files.length == 0) {
                    error = 'Bukti transfer harus diupload';
                }
            <?php endif; ?>

            // Validasi metode pembayaran
            if ($('#metode_pembayaran').val() == '') {
                error = 'Metode pembayaran harus dipilih';
            }

            // Validasi alamat pengiriman
            if ($('#alamat_pengiriman').val().trim() == '') {
                error = 'Alamat pengiriman harus diisi';
            }

            if (error != '') {
                e.preventDefault();
                $('#alertMessage').text(error);
                $('#alertValidation').slideDown();
                $('html, body').animate({
                    scrollTop: $('#alertValidation').offset().top - 100
                }, 500);
                return false;
            } else {
                $('#alertValidation').slideUp();
            }

            // Konfirmasi sebelum submit
            const confirmText = sudahBayarDP ?
                'Proses pelunasan pembayaran sebesar Rp ' + jumlahBayar.toLocaleString('id-ID') + '?' :
                'Proses pembayaran sebesar Rp ' + jumlahBayar.toLocaleString('id-ID') + '?';

            if (!confirm(confirmText)) {
                e.preventDefault();
                return false;
            }

            // Disable button untuk prevent double submit
            $('#btnSubmit').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Memproses...');
        });

        // Trigger preview pertama kali
        previewStatusPembayaran();
    });

    // Function untuk show modal request change alamat
    function showRequestChangeAlamat() {
        $('#modalRequestChangeAlamat').modal('show');
    }

    // Submit request change alamat
    $('#formRequestChangeAlamat').on('submit', function(e) {
        e.preventDefault();

        const alamatBaru = $('#alamat_baru_request').val().trim();
        if (alamatBaru == '') {
            alert('Alamat baru harus diisi');
            return false;
        }

        if (!confirm('Ajukan perubahan alamat? Perubahan akan diproses oleh admin/kasir.')) {
            return false;
        }

        $.ajax({
            url: '<?= base_url('permintaan_custom/request_change_alamat/' . $data->kode_permintaan_custom) ?>',
            method: 'POST',
            data: {
                alamat_baru: alamatBaru,
                <?= csrf_token() ?>: '<?= csrf_hash() ?>'
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    alert(response.message);
                    $('#modalRequestChangeAlamat').modal('hide');
                    location.reload();
                } else {
                    alert(response.message || 'Terjadi kesalahan');
                }
            },
            error: function() {
                alert('Terjadi kesalahan saat mengajukan perubahan alamat');
            }
        });
    });
</script>

<!-- Modal Request Change Alamat -->
<div class="modal fade" id="modalRequestChangeAlamat" 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-edit"></i> Ajukan 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="formRequestChangeAlamat">
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        Alamat saat ini sudah terkunci. Perubahan alamat memerlukan approval dari admin/kasir.
                    </div>

                    <div class="form-group">
                        <label>Alamat Saat Ini:</label>
                        <textarea class="form-control" rows="3" readonly><?= $data->alamat_pengiriman ?? '' ?></textarea>
                    </div>

                    <div class="form-group">
                        <label for="alamat_baru_request">
                            Alamat Baru <span class="text-danger">*</span>
                        </label>
                        <textarea class="form-control"
                            id="alamat_baru_request"
                            name="alamat_baru"
                            rows="3"
                            placeholder="Masukkan alamat baru yang diinginkan"
                            required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-warning">
                        <i class="fas fa-paper-plane"></i> Ajukan Perubahan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>