<div class="modal-header bg-warning">
    <h4 class="modal-title">
        <i class="fas fa-edit"></i> Edit Meter Pemakaian & Ongkos Jahit
    </h4>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">×</span>
    </button>
</div>

<div class="modal-body">

    <!-- Order Info -->
    <div class="card card-outline card-primary mb-3">
        <div class="card-header">
            <h3 class="card-title"><i class="fas fa-shopping-cart"></i> Informasi Pesanan</h3>
        </div>
        <div class="card-body">
            <table class="table table-sm table-borderless">
                <tr>
                    <th width="30%">No Order:</th>
                    <td><?= $data->no_order_custom ?></td>
                </tr>
                <tr>
                    <th>Customer:</th>
                    <td><?= $data->nama ?></td>
                </tr>
                <tr>
                    <th>Tanggal Order:</th>
                    <td><?= date('d/m/Y H:i', strtotime($data->tanggal_order)) ?></td>
                </tr>
                <tr class="d-none">
                    <th>Estimasi Pengambilan:</th>
                    <td>
                        <?php if (!empty($data->tanggal_pengambilan)): ?>
                            <?= date('d/m/Y', strtotime($data->tanggal_pengambilan)) ?>
                            <?php if (empty($data->tanggal_pengambilan_konfirmasi)): ?>
                                <span class="badge badge-warning">Perlu Konfirmasi</span>
                            <?php else: ?>
                                <span class="badge badge-success">Dikonfirmasi</span>
                            <?php endif; ?>
                        <?php else: ?>
                            <span class="text-muted">Belum diset</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th>Total Saat Ini:</th>
                    <td><strong>Rp <?= number_format($data->nominal_pelunasan, 0, ",", ".") ?></strong></td>
                </tr>
            </table>
        </div>
    </div>

    <form method="POST" action="<?= base_url('permintaan_custom/kasir_edit_meter/' . $data->kode_permintaan_custom) ?>" id="formEditMeter">
        <?= csrf_field() ?>

        <!-- Tanggal Pengambilan Confirmation -->
        <?php if (!empty($data->tanggal_pengambilan)): ?>
            <div class="card card-outline card-info mb-3">
                <div class="card-header">
                    <h3 class="card-title"><i class="fas fa-calendar-check"></i> Konfirmasi Tanggal Pengambilan</h3>
                </div>
                <div class="card-body">
                    <div class="form-group">
                        <label>Tanggal Pengambilan <small class="text-muted">(Estimasi dari customer: <?= date('d/m/Y', strtotime($data->tanggal_pengambilan)) ?>)</small></label>
                        <input type="date" class="form-control" name="tanggal_pengambilan_konfirmasi"
                            value="<?= !empty($data->tanggal_pengambilan_konfirmasi) ? date('Y-m-d', strtotime($data->tanggal_pengambilan_konfirmasi)) : date('Y-m-d', strtotime($data->tanggal_pengambilan)) ?>">
                        <small class="text-info">
                            <i class="fas fa-info-circle"></i> Konfirmasi atau ubah tanggal pengambilan sesuai ketersediaan
                        </small>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="card card-outline card-success">
            <div class="card-header">
                <h3 class="card-title"><i class="fas fa-ruler"></i> Daftar Item - Meter Pemakaian & Ongkos Jahit</h3>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover table-sm">
                        <thead class="thead-light">
                            <tr>
                                <th width="5%">No</th>
                                <th width="20%">Model</th>
                                <th width="15%">Jenis Kain</th>
                                <th width="10%">Warna</th>
                                <th width="12%">Harga/Meter atau Ongkos</th>
                                <th width="15%">Meter/Ongkos per Pcs</th>
                                <th width="13%">Subtotal</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $no = 1; ?>
                            <?php foreach ($detail_model as $detail): ?>
                                <?php
                                // Check if this is custom (bawa kain sendiri + upload model sendiri)
                                $isCustom = ($detail->upload_model_sendiri == 1);

                                $ongkos_jahit = $detail->ongkos_jahit_custom;
                                $ongkos_pengerjaan = $detail->ongkos_pengerjaan;

                                // Parse additional fabrics
                                $additionalFabrics = [];
                                if (!empty($detail->additional_fabrics)) {
                                    $decoded = json_decode($detail->additional_fabrics, true);
                                    if (is_array($decoded)) {
                                        $additionalFabrics = $decoded;
                                    }
                                }
                                $totalFabrics = count($additionalFabrics) + 1;
                                ?>

                                <?php if ($isCustom): ?>
                                    <tr class="table-warning">
                                        <td class="text-center"><?= $no++ ?></td>
                                        <td>
                                            <strong><?= $detail->nama_model ?? 'Upload Model Sendiri' ?></strong><br>
                                            <small class="text-muted">
                                                Ukuran: <?= $detail->ukuran_gamis ?><br>
                                                Jumlah: <?= $detail->jumlah_pcs ?> pcs
                                            </small>
                                            <br><span class="badge badge-warning">
                                                <i class="fas fa-tools"></i> Custom (Bawa Kain & Model Sendiri)
                                            </span>
                                        </td>
                                        <?php if ($detail->nama_jenis_kain): ?>
                                            <td>
                                                <i class="fas fa-star text-warning"></i> <?= $detail->nama_jenis_kain ?? 'Bawa Sendiri' ?>
                                                <?php if ($totalFabrics > 1): ?>
                                                    <br><small class="text-muted">(Kain Utama)</small>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if (!empty($detail->warna)): ?>
                                                    <span class="badge badge-info">
                                                        <?= $detail->warna ?>
                                                    </span>
                                                <?php else: ?>
                                                    -
                                                <?php endif; ?>
                                            </td>

                                            <td class="text-right">
                                                <?php
                                                $hargaPerMeter = $detail->harga_per_meter ?? $detail->jenis_harga_per_meter ?? 0;
                                                ?>
                                                Rp <?= number_format($hargaPerMeter, 0, ",", ".") ?>/m
                                                <input type="hidden" name="harga_per_meter[]" value="<?= $hargaPerMeter ?>">
                                                <input type="hidden" name="id_detail_order[]" value="<?= $detail->kain_id_detail ?? $detail->id_detail_order ?>">
                                                <input type="hidden" name="is_custom[]" value="0">
                                                <input type="hidden" name="ongkos_jahit_custom[]" value="0">
                                                <input type="hidden" name="jumlah_pcs_custom[]" value="0">
                                            </td>

                                        <?php else: ?>

                                            <td colspan="2" class="text-center text-muted">
                                                <em>Customer bawa kain sendiri</em>
                                            </td>

                                            <td class="text-right">
                                                <span class="text-muted">Ongkos Jahit/pcs</span>
                                                <input type="hidden" name="harga_per_meter[]" value="0">
                                                <input type="hidden" name="id_detail_order[]" value="<?= $detail->id_detail_order ?>">
                                                <input type="hidden" name="is_custom[]" value="1">
                                                <input type="hidden" name="jumlah_pcs_custom[]" value="<?= $detail->jumlah_pcs ?>">
                                                <span class="text-muted">Ongkos Pengerjaan/pcs</span>
                                            </td>
                                        <?php endif ?>

                                        <td>

                                            <?php if ($detail->nama_jenis_kain): ?>

                                                <div class="input-group input-group-sm">
                                                    <input type="number"
                                                        class="form-control meter-input"
                                                        name="meter_pemakaian[]"
                                                        value="<?= $detail->meter_pemakaian ?? 0 ?>"
                                                        step="0.5"
                                                        min="0"
                                                        data-index="<?= $no - 2 ?>"
                                                        data-harga="<?= $hargaPerMeter ?>"
                                                        data-meter="<?= $hargaPerMeter ?>
                                                        onchange=" calculateSubtotal(this)"
                                                        required>
                                                    <div class="input-group-append">
                                                        <span class="input-group-text">meter</span>
                                                    </div>
                                                </div>

                                            <?php endif ?>

                                            <div class="input-group input-group-sm">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text">Rp</span>
                                                </div>
                                                <input type="number" class="form-control ongkos-input" name="ongkos_jahit_custom[]" value="<?= $detail->ongkos_jahit_custom ?? 0 ?>"
                                                    step="1000" min="0" data-index="<?= $no - 2 ?>" data-jumlah="<?= $detail->jumlah_pcs ?>" onchange="calculateOngkosSubtotal(this)" required>
                                                <div class="input-group-append">
                                                    <span class="input-group-text">/pcs</span>
                                                </div>
                                            </div>
                                            <div class="input-group input-group-sm d-none">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text">Rp</span>
                                                </div>
                                                <input type="number"
                                                    class="form-control pengerjaan-input"
                                                    name="ongkos_pengerjaan[]"
                                                    value="0"
                                                    step="1000"
                                                    min="0"
                                                    data-index="<?= $no - 2 ?>"
                                                    data-jumlah="<?= $detail->jumlah_pcs ?>"
                                                    onchange="calculateOngkosSubtotal(this)"
                                                    required>
                                                <div class="input-group-append">
                                                    <span class="input-group-text">/pcs</span>
                                                </div>
                                            </div>
                                            <small class="text-muted">x <?= $detail->jumlah_pcs ?> pcs</small>
                                        </td>
                                        <td class="text-right">
                                            <span class="subtotal-display" data-index="<?= $no - 2 ?>">
                                                Rp <?= number_format(($detail->ongkos_jahit_custom + $detail->ongkos_pengerjaan) * $detail->jumlah_pcs, 0, ",", ".") ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <!-- REGULAR ITEM (Meter Pemakaian) -->
                                    <tr class="<?= $totalFabrics > 1 ? 'table-primary' : '' ?>">
                                        <td class="text-center" <?= $totalFabrics > 1 ? 'rowspan="' . $totalFabrics . '"' : '' ?>>
                                            <?= $no++ ?>
                                        </td>
                                        <td <?= $totalFabrics > 1 ? 'rowspan="' . $totalFabrics . '"' : '' ?>>
                                            <strong><?= $detail->nama_model ?></strong><br>
                                            <small class="text-muted">
                                                Ukuran: <?= $detail->ukuran_gamis ?><br>
                                                Jumlah: <?= $detail->jumlah_pcs ?> pcs
                                            </small>
                                            <?php if ($totalFabrics > 1): ?>
                                                <br><span class="badge badge-info">
                                                    <i class="fas fa-layer-group"></i> <?= $totalFabrics ?> Kain
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <i class="fas fa-star text-warning"></i> <?= $detail->nama_jenis_kain ?? 'Bawa Sendiri' ?>
                                            <?php if ($totalFabrics > 1): ?>
                                                <br><small class="text-muted">(Kain Utama)</small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if (!empty($detail->warna)): ?>
                                                <span class="badge badge-info">
                                                    <?= $detail->warna ?>
                                                </span>
                                            <?php else: ?>
                                                -
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-right">
                                            <?php
                                            $hargaPerMeter = $detail->harga_per_meter ?? $detail->jenis_harga_per_meter ?? 0;
                                            ?>
                                            Rp <?= number_format($hargaPerMeter, 0, ",", ".") ?>/m
                                            <input type="hidden" name="harga_per_meter[]" value="<?= $hargaPerMeter ?>">
                                            <input type="hidden" name="id_detail_order[]" value="<?= $detail->kain_id_detail ?? $detail->id_detail_order ?>">
                                            <input type="hidden" name="is_custom[]" value="0">
                                            <input type="hidden" name="ongkos_jahit_custom[]" value="0">
                                            <input type="hidden" name="jumlah_pcs_custom[]" value="0">
                                        </td>
                                        <td>
                                            <div class="input-group input-group-sm">
                                                <input type="number"
                                                    class="form-control meter-input"
                                                    name="meter_pemakaian[]"
                                                    value="<?= $detail->meter_pemakaian ?? 0 ?>"
                                                    step="0.5"
                                                    min="0"
                                                    data-index="<?= $no - 2 ?>"
                                                    data-harga="<?= $hargaPerMeter ?>"
                                                    data-meter="<?= $hargaPerMeter ?>"
                                                    onchange="calculateSubtotal(this)"
                                                    required>
                                                <div class="input-group-append">
                                                    <span class="input-group-text">meter</span>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="text-right">
                                            <span class="subtotal-display" data-index="<?= $no - 2 ?>">
                                                Rp <?= number_format($detail->subtotal_detail_kain ?? 0, 0, ",", ".") ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endif; ?>

                                <!-- ADDITIONAL FABRICS ROWS -->
                                <?php if (!empty($additionalFabrics)): ?>
                                    <?php foreach ($additionalFabrics as $idx => $addFabric): ?>
                                        <?php
                                        // Get fabric info from database
                                        $fabricInfo = null;
                                        $kodeKain = $addFabric['kode_jenis_kain'] ?? $addFabric['kode'] ?? '';
                                        $addMeter = $addFabric['meter_pemakaian'] ?? $addFabric['meter'] ?? 0;
                                        $addHarga = 0;
                                        $namaKain = 'Kain Tambahan';
                                        $warnaKain = '';

                                        if (!empty($kodeKain)) {
                                            $db = \Config\Database::connect();
                                            $fabricInfo = $db->table('tabel_jenis_kain')
                                                ->where('kode_jenis_kain', $kodeKain)
                                                ->get()
                                                ->getRow();

                                            if ($fabricInfo) {
                                                $namaKain = $fabricInfo->nama_jenis_kain;
                                                $warnaKain = $fabricInfo->warna ?? '';
                                                $addHarga = $fabricInfo->harga_per_meter ?? 0;
                                            }
                                        }

                                        // Override dengan harga yang tersimpan jika ada
                                        if (isset($addFabric['harga_per_meter']) && $addFabric['harga_per_meter'] > 0) {
                                            $addHarga = $addFabric['harga_per_meter'];
                                        }
                                        ?>
                                        <tr class="table-secondary">
                                            <td>
                                                <i class="fas fa-plus-circle text-success"></i> <?= $namaKain ?>
                                                <br><small class="text-muted">(Kain Tambahan #<?= ($idx + 1) ?>)</small>
                                                <input type="hidden" name="additional_fabric_codes_<?= $detail->id_detail_order ?>[]" value="<?= $kodeKain ?>">
                                            </td>
                                            <td>
                                                <?php if (!empty($warnaKain)): ?>
                                                    <span class="badge badge-secondary">
                                                        <?= $warnaKain ?>
                                                    </span>
                                                <?php else: ?>
                                                    -
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-right">
                                                Rp <?= number_format($addHarga, 0, ",", ".") ?>
                                                <input type="hidden" name="additional_fabric_hargas_<?= $detail->id_detail_order ?>[]" value="<?= $addHarga ?>">
                                            </td>
                                            <td>
                                                <div class="input-group input-group-sm">
                                                    <input type="number"
                                                        class="form-control meter-input-additional"
                                                        name="additional_fabric_meters_<?= $detail->id_detail_order ?>[]"
                                                        value="<?= $addMeter ?>"
                                                        step="0.5"
                                                        min="0"
                                                        data-harga="<?= $addHarga ?>"
                                                        data-jumlah="<?= $detail->jumlah_pcs ?>"
                                                        onchange="calculateAdditionalSubtotal(this)"
                                                        required>
                                                    <div class="input-group-append">
                                                        <span class="input-group-text">meter</span>
                                                    </div>
                                                </div>
                                                <small class="text-muted">x <?= $detail->jumlah_pcs ?> pcs</small>
                                            </td>
                                            <td class="text-right">
                                                <span class="additional-subtotal-display">
                                                    Rp <?= number_format($addHarga * $addMeter * $detail->jumlah_pcs, 0, ",", ".") ?>
                                                </span>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>


                            <?php endforeach; ?>
                        </tbody>
                        <tfoot class="thead-light">
                            <tr>
                                <th colspan="6" class="text-right">Total Kain:</th>
                                <th class="text-right">
                                    <span id="totalKain">Rp 0</span>
                                </th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>

        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">
                <i class="fas fa-times"></i> Batal
            </button>
            <button type="submit" class="btn btn-success">
                <i class="fas fa-save"></i> Simpan Meter Pemakaian
            </button>
        </div>
    </form>
</div>

<script>
    $(() => {
        calculateTotal()
    })

    function calculateOngkosSubtotal(input) {
        const index = input.dataset.index;
        // const ongkos = parseFloat(input.value) || 0;

        var ongkos = 0;

        // Calculate from ongkos jahit custom items
        document.querySelectorAll('.ongkos-input').forEach(input => {
            ongkos += parseFloat(input.value) || 0;
        });

        document.querySelectorAll('.pengerjaan-input').forEach(input => {
            ongkos += parseFloat(input.value) || 0;
        });

        const jumlah = parseFloat(input.dataset.jumlah) || 1;
        const subtotal = ongkos * jumlah;

        // Update display
        const subtotalDisplay = document.querySelector(`span.subtotal-display[data-index="${index}"]`);
        if (subtotalDisplay) {
            subtotalDisplay.textContent = 'Rp ' + subtotal.toLocaleString('id-ID');
        }

        // Recalculate total
        calculateTotal();
    }

    function calculateSubtotal(input) {
        const index = input.dataset.index;
        const meter = parseFloat(input.value) || 0;
        const meteran = parseFloat(input.meter) || 0;
        const harga = parseFloat(input.dataset.harga) || 0;
        const subtotal = meter * harga;

        // Update display
        const subtotalDisplay = document.querySelector(`span.subtotal-display[data-index="${index}"]`);
        if (subtotalDisplay) {
            subtotalDisplay.textContent = 'Rp ' + subtotal.toLocaleString('id-ID');
        }

        // Recalculate total
        calculateTotal();
    }

    function calculateAdditionalSubtotal(input) {
        const meter = parseFloat(input.value) || 0;
        const harga = parseFloat(input.dataset.harga) || 0;
        const jumlah = parseFloat(input.dataset.jumlah) || 1;
        const subtotal = meter * harga * jumlah;

        // Find the closest subtotal display
        const row = input.closest('tr');
        const subtotalDisplay = row.querySelector('.additional-subtotal-display');
        if (subtotalDisplay) {
            subtotalDisplay.textContent = 'Rp ' + subtotal.toLocaleString('id-ID');
        }

        // Recalculate total
        calculateTotal();
    }

    function calculateTotal() {
        let total = 0;

        // Calculate from ongkos jahit custom items
        document.querySelectorAll('.ongkos-input').forEach(input => {
            const ongkos = parseFloat(input.value) || 0;
            const jumlah = parseFloat(input.dataset.jumlah) || 1;
            total += ongkos * jumlah;
        });

        // Calculate from ongkos jahit custom items
        document.querySelectorAll('.pengerjaan-input').forEach(input => {
            const ongkos = parseFloat(input.value) || 0;
            const jumlah = parseFloat(input.dataset.jumlah) || 1;
            total += ongkos * jumlah;
        });

        // Calculate from primary fabrics
        document.querySelectorAll('.meter-input').forEach(input => {
            const meter = parseFloat(input.value) || 0;
            const harga = parseFloat(input.dataset.harga) || 0;
            total += meter * harga;
        });

        // Calculate from additional fabrics (including jumlah_pcs)
        document.querySelectorAll('.meter-input-additional').forEach(input => {
            const meter = parseFloat(input.value) || 0;
            const harga = parseFloat(input.dataset.harga) || 0;
            const jumlah = parseFloat(input.dataset.jumlah) || 1;
            total += meter * harga * jumlah;
        });

        document.getElementById('totalKain').textContent = 'Rp ' + total.toLocaleString('id-ID');
    }

    // Calculate on page load
    document.addEventListener('DOMContentLoaded', function() {
        calculateTotal();
    });

    // Form validation
    document.getElementById('formEditMeter').addEventListener('submit', function(e) {
        let hasEmptyInput = false;
        let errorMessage = '';

        // Check ongkos jahit custom (for custom items only)
        const ongkosInputs = document.querySelectorAll('.ongkos-input');
        if (ongkosInputs.length > 0) {
            ongkosInputs.forEach(input => {
                const value = parseFloat(input.value) || 0;
                if (value <= 0) {
                    hasEmptyInput = true;
                    errorMessage = 'Ongkos jahit custom harus diisi dengan nilai lebih dari 0';
                }
            });
        }

        // Check primary fabrics (for regular items only)
        if (!hasEmptyInput) {
            const meterInputs = document.querySelectorAll('.meter-input');
            if (meterInputs.length > 0) {
                meterInputs.forEach(input => {
                    const value = parseFloat(input.value) || 0;
                    if (value <= 0) {
                        hasEmptyInput = true;
                        errorMessage = 'Semua meter pemakaian harus diisi dengan nilai lebih dari 0';
                    }
                });
            }
        }

        // Check additional fabrics (for regular items with multiple fabrics)
        if (!hasEmptyInput) {
            const additionalInputs = document.querySelectorAll('.meter-input-additional');
            if (additionalInputs.length > 0) {
                additionalInputs.forEach(input => {
                    const value = parseFloat(input.value) || 0;
                    if (value <= 0) {
                        hasEmptyInput = true;
                        errorMessage = 'Semua meter pemakaian kain tambahan harus diisi dengan nilai lebih dari 0';
                    }
                });
            }
        }

        // Prevent submission if validation fails
        if (hasEmptyInput) {
            e.preventDefault();
            Swal.fire({
                icon: 'warning',
                title: 'Perhatian',
                text: errorMessage || 'Semua meter pemakaian dan ongkos jahit harus diisi dengan nilai lebih dari 0',
                confirmButtonColor: '#3085d6'
            });
        }
    });
</script>