<div class="modal-header">
    <h4 class="modal-title">Revisi Pesanan Custom</h4>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">×</span>
    </button>
</div>
<div class="modal-body" style="max-height: 85vh; overflow-y: auto;">
    <form method="POST" action="<?= base_url('permintaan_perubahan/create') ?>" enctype="multipart/form-data" id="formRevisiOrder">
        <?= csrf_field() ?>

        <!-- Order Summary -->
        <div class="card mb-3">
            <div class="card-header bg-info text-white">
                <h5 class="mb-0"><i class="fas fa-info-circle"></i> Informasi Pesanan</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <table class="table table-sm table-borderless">
                            <tr>
                                <th>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><?= $data->tanggal_order ?></td>
                            </tr>
                            <tr>
                                <th>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>Total Order Awal:</th>
                                <td id="totalOrderAwal">Rp. <?= number_format($data->total_order, 0, ",", ".") ?></td>
                            </tr>
                            <tr>
                                <th>DP Pembayaran:</th>
                                <td>Rp. <?= number_format($data->dp_pembayaran, 0, ",", ".") ?></td>
                            </tr>
                            <tr>
                                <th>Sisa Pembayaran Awal:</th>
                                <td>Rp. <?= number_format($data->sisa_pembayaran, 0, ",", ".") ?></td>
                            </tr>
                            <tr>
                                <th>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 Bayar</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>

                <div class="alert alert-warning mt-3">
                    <strong><i class="fas fa-exclamation-triangle"></i> Total Baru (Setelah Revisi):</strong>
                    <h4 class="mb-0 mt-2" id="totalOrderBaru">Rp. <?= number_format($data->total_order, 0, ",", ".") ?></h4>
                    <small id="selisihInfo" class="text-muted"></small>
                </div>
            </div>
        </div>

        <!-- Detail Items for Revision -->
        <?php foreach ($detail_model as $index => $detail):
            $riwayat = $riwayatPerubahanModel
                ->where('id_detail_order', $detail->id_detail_order)
                ->where('status', 1)
                ->orderBy('created_at', 'DESC')
                ->first();
        ?>
            <div class="card mb-3 detail-item-card" data-index="<?= $index ?>">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fas fa-edit"></i> Detail Item #<?= $index + 1 ?></h5>
                </div>
                <div class="card-body">
                    <input type="hidden" name="id_detail_order[]" value="<?= $detail->id_detail_order ?>">
                    <input type="hidden" class="kode_model_old" value="<?= $detail->kode_model ?>">
                    <input type="hidden" class="kode_kain_old" value="<?= $detail->kode_jenis_kain ?>">
                    <input type="hidden" name="kode_model_selected[]" class="kode_model_selected" value="<?= $detail->kode_model ?>">
                    <input type="hidden" name="kode_jenis_kain_selected[]" class="kode_jenis_kain_selected" value="<?= $detail->kode_jenis_kain ?>">
                    <input type="hidden" class="subtotal_model_old" value="<?= $detail->subtotal_detail_order ?>">
                    <input type="hidden" class="subtotal_kain_old" value="<?= $detail->subtotal_detail_kain ?>">

                    <div class="row">
                        <!-- Model Section -->
                        <div class="col-md-6">
                            <div class="card h-100">
                                <div class="card-header bg-success text-white">
                                    <strong>Model Gamis</strong>
                                </div>
                                <div class="card-body">
                                    <div class="model-preview-<?= $index ?>">
                                        <img src="<?= base_url($detail->foto_model) ?>" alt="Model" class="img-fluid mb-2" style="max-height: 150px; object-fit: cover;">
                                        <p><strong>Nama:</strong> <span class="nama-model"><?= $detail->nama_model ?></span></p>
                                        <p><strong>Size:</strong> <?= $detail->ukuran_gamis ?></p>
                                        <p><strong>Jumlah (Pcs):</strong> <?= $detail->jumlah_pcs ?></p>
                                        <p><strong>Ongkos Lama:</strong> <span class="subtotal-model-display">Rp. <?= number_format($detail->subtotal_detail_order, 0, ",", ".") ?></span></p>
                                    </div>
                                    <button type="button" class="btn btn-sm btn-outline-success btn-block mt-2 btn-change-model" data-index="<?= $index ?>">
                                        <i class="fas fa-sync-alt"></i> Ganti Model
                                    </button>
                                    <div class="mt-2 model-new-price-<?= $index ?>" style="display: none;">
                                        <label>Ongkos Baru (Rp)</label>
                                        <input type="number" class="form-control form-control-sm subtotal_model_new" name="subtotal_model_new[]" placeholder="Masukkan harga baru">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Kain Section -->
                        <div class="col-md-6">
                            <div class="card h-100">
                                <div class="card-header bg-warning text-dark">
                                    <strong><i class="fas fa-fabric"></i> Jenis Kain
                                        <?php
                                        $additionalFabrics = [];
                                        if (!empty($detail->additional_fabrics)) {
                                            $decoded = json_decode($detail->additional_fabrics, true);
                                            if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                                                $additionalFabrics = $decoded;
                                            }
                                        }
                                        $totalFabrics = 1 + count($additionalFabrics);
                                        if ($totalFabrics > 1): ?>
                                            (<?= $totalFabrics ?> Kombinasi)
                                        <?php endif; ?>
                                    </strong>
                                </div>
                                <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                                    <!-- PRIMARY FABRIC -->
                                    <div class="fabric-preview-<?= $index ?> border-bottom pb-3 mb-3">
                                        <div class="badge badge-primary mb-2">Kain Utama</div>
                                        <?php if (!empty($detail->foto_jenis_kain)): ?>
                                            <img src="<?= base_url($detail->foto_jenis_kain) ?>" alt="Kain" class="img-fluid mb-2 rounded" style="max-height: 120px; object-fit: cover; width: 100%;">
                                        <?php endif; ?>
                                        <p class="mb-1"><strong>Nama:</strong> <span class="nama-kain"><?= $detail->nama_jenis_kain ?></span></p>
                                        <p class="mb-1"><strong>Warna:</strong> <span class="warna-kain"><?= $detail->warna ?></span></p>
                                        <p class="mb-1"><strong>Jumlah (Meter):</strong> <?= $detail->meter_pemakaian ?? '0' ?> m</p>
                                        <p class="mb-1"><strong>Harga Lama:</strong> <span class="subtotal-kain-display">Rp. <?= number_format($detail->subtotal_detail_kain, 0, ",", ".") ?></span></p>
                                    </div>

                                    <!-- ADDITIONAL FABRICS -->
                                    <?php if (!empty($additionalFabrics)): ?>
                                        <?php foreach ($additionalFabrics as $idx => $addFabric): ?>
                                            <?php
                                            $kodeKain = $addFabric['kode_jenis_kain'] ?? $addFabric['kode'] ?? '';
                                            $fabricInfo = null;
                                            if (!empty($kodeKain)) {
                                                $db = \Config\Database::connect();
                                                $fabricInfo = $db->table('tabel_jenis_kain')
                                                    ->where('kode_jenis_kain', $kodeKain)
                                                    ->get()->getRow();
                                            }
                                            $addMeter = $addFabric['meter_pemakaian'] ?? $addFabric['meter'] ?? 0;
                                            $addHarga = $addFabric['harga_per_meter'] ?? ($fabricInfo->harga_per_meter ?? 0);
                                            $addSubtotal = $addMeter * $addHarga * $detail->jumlah_pcs;
                                            ?>
                                            <div class="border-bottom pb-3 mb-3">
                                                <div class="badge badge-success mb-2">
                                                    <i class="fas fa-plus-circle"></i> Kain Tambahan #<?= ($idx + 1) ?>
                                                </div>
                                                <?php if ($fabricInfo && !empty($fabricInfo->foto_jenis_kain)): ?>
                                                    <img src="<?= base_url($fabricInfo->foto_jenis_kain) ?>" alt="Kain" class="img-fluid mb-2 rounded" style="max-height: 100px; object-fit: cover; width: 100%;">
                                                <?php endif; ?>
                                                <p class="mb-1"><strong>Nama:</strong> <?= $fabricInfo->nama_jenis_kain ?? 'Kain Tambahan' ?></p>
                                                <p class="mb-1"><strong>Warna:</strong> <?= $fabricInfo->warna ?? '-' ?></p>
                                                <p class="mb-1"><strong>Jumlah (Meter):</strong> <?= $addMeter ?> m</p>
                                                <p class="mb-1"><strong>Harga:</strong> Rp. <?= number_format($addSubtotal, 0, ",", ".") ?></p>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>

                                    <button type="button" class="btn btn-sm btn-outline-warning btn-block mt-2 btn-change-fabric" data-index="<?= $index ?>">
                                        <i class="fas fa-sync-alt"></i> Ganti Kain Utama
                                    </button>
                                    <small class="text-muted d-block mt-2">
                                        <i class="fas fa-info-circle"></i> Untuk mengganti kain tambahan, silakan hubungi kasir
                                    </small>
                                    <div class="mt-2 fabric-new-price-<?= $index ?>" style="display: none;">
                                        <label>Harga Baru (Rp)</label>
                                        <input type="number" class="form-control form-control-sm subtotal_kain_new" name="subtotal_kain_new[]" placeholder="Masukkan harga baru">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Total Item Breakdown -->
                    <hr class="my-3">
                    <div class="alert alert-warning mb-3">
                        <strong><i class="fas fa-calculator"></i> Total Item #<?= $index + 1 ?>:</strong>
                        <h5 class="mb-2 mt-2">
                            Rp <?= number_format($detail->subtotal_detail_order + $detail->subtotal_detail_kain, 0, ",", ".") ?>
                        </h5>
                        <small>
                            <strong>Model:</strong> Rp <?= number_format($detail->subtotal_detail_order / $detail->jumlah_pcs, 0, ",", ".") ?> x <?= $detail->jumlah_pcs ?> pcs = Rp <?= number_format($detail->subtotal_detail_order, 0, ",", ".") ?><br>
                            <strong>Kain Utama:</strong> Rp <?= number_format($detail->harga_per_meter ?? 0, 0, ",", ".") ?>/m x <?= $detail->meter_pemakaian ?? 0 ?> m x <?= $detail->jumlah_pcs ?> pcs = Rp <?= number_format($detail->subtotal_detail_kain, 0, ",", ".") ?>
                            <?php if (!empty($additionalFabrics)): ?>
                                <br><strong>Kain Tambahan:</strong>
                                <?php
                                $totalAdditionalKain = 0;
                                foreach ($additionalFabrics as $idx => $addFabric):
                                    $kodeKain = $addFabric['kode_jenis_kain'] ?? $addFabric['kode'] ?? '';
                                    $fabricInfo = null;
                                    if (!empty($kodeKain)) {
                                        $db = \Config\Database::connect();
                                        $fabricInfo = $db->table('tabel_jenis_kain')
                                            ->where('kode_jenis_kain', $kodeKain)
                                            ->get()->getRow();
                                    }
                                    $addMeter = $addFabric['meter_pemakaian'] ?? $addFabric['meter'] ?? 0;
                                    $addHarga = $addFabric['harga_per_meter'] ?? ($fabricInfo->harga_per_meter ?? 0);
                                    $addSubtotal = $addMeter * $addHarga * $detail->jumlah_pcs;
                                    $totalAdditionalKain += $addSubtotal;
                                ?>
                                    <br>&nbsp;&nbsp;• <?= $fabricInfo->nama_jenis_kain ?? 'Kain #' . ($idx + 1) ?>: Rp <?= number_format($addHarga, 0, ",", ".") ?>/m x <?= $addMeter ?> m x <?= $detail->jumlah_pcs ?> pcs = Rp <?= number_format($addSubtotal, 0, ",", ".") ?>
                                <?php endforeach; ?>
                                <br><strong>Total Kain:</strong> Rp <?= number_format($detail->subtotal_detail_kain + $totalAdditionalKain, 0, ",", ".") ?>
                            <?php endif; ?>
                        </small>
                    </div>

                    <!-- Keterangan Revisi -->
                    <div class="form-group mt-3">
                        <label><strong>Keterangan Revisi</strong></label>
                        <textarea name="keterangan_revisi[]" class="form-control" rows="3" placeholder="Jelaskan perubahan yang diminta (opsional)"><?= $riwayat->keterangan_permintaan_revisi ?? '' ?></textarea>
                        <small class="text-muted">Jelaskan detail perubahan jika ada (misal: ubah warna, ukuran, dll)</small>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>

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

<!-- Include modal files -->
<?= $this->include('permintaan_custom/modal_select_model') ?>
<?= $this->include('permintaan_custom/modal_select_fabric') ?>

<script>
    $(document).ready(function() {
        let currentIndex = null;
        const totalOrderAwal = <?= $data->total_order ?>;
        let totalOrderBaru = totalOrderAwal;

        // Button change model
        $('.btn-change-model').click(function() {
            currentIndex = $(this).data('index');
            $('#modalSelectModel').modal('show');
        });

        // Button change fabric
        $('.btn-change-fabric').click(function() {
            currentIndex = $(this).data('index');
            $('#modalSelectFabric').modal('show');
        });

        // Override selectModel function to handle revision context
        window.selectModelForRevision = function(kodeModel, namaModel, fotoModel) {
            if (currentIndex === null) return;

            const card = $(`.detail-item-card[data-index="${currentIndex}"]`);
            const oldKode = card.find('.kode_model_old').val();

            // Update hidden input
            card.find('.kode_model_selected').val(kodeModel);

            // Update preview
            card.find(`.model-preview-${currentIndex} img`).attr('src', fotoModel);
            card.find(`.model-preview-${currentIndex} .nama-model`).text(namaModel);

            // Show price input if changed
            if (kodeModel !== oldKode) {
                card.find(`.model-new-price-${currentIndex}`).show();
                card.find('.subtotal_model_new').attr('required', true);
            } else {
                card.find(`.model-new-price-${currentIndex}`).hide();
                card.find('.subtotal_model_new').removeAttr('required').val('');
            }

            $('#modalSelectModel').modal('hide');
            recalculateTotal();
        };

        // Override selectFabric function to handle revision context
        window.selectFabricForRevision = function(kodeFabric, namaFabric, warnaFabric, fotoFabric) {
            if (currentIndex === null) return;

            const card = $(`.detail-item-card[data-index="${currentIndex}"]`);
            const oldKode = card.find('.kode_kain_old').val();

            // Update hidden input
            card.find('.kode_jenis_kain_selected').val(kodeFabric);

            // Update preview
            card.find(`.fabric-preview-${currentIndex} img`).attr('src', fotoFabric);
            card.find(`.fabric-preview-${currentIndex} .nama-kain`).text(namaFabric);
            card.find(`.fabric-preview-${currentIndex} .warna-kain`).text(warnaFabric);

            // Show price input if changed
            if (kodeFabric !== oldKode) {
                card.find(`.fabric-new-price-${currentIndex}`).show();
                card.find('.subtotal_kain_new').attr('required', true);
            } else {
                card.find(`.fabric-new-price-${currentIndex}`).hide();
                card.find('.subtotal_kain_new').removeAttr('required').val('');
            }

            $('#modalSelectFabric').modal('hide');
            recalculateTotal();
        };

        // Recalculate total when prices change
        $('.subtotal_model_new, .subtotal_kain_new').on('input', recalculateTotal);

        function recalculateTotal() {
            let newTotal = 0;

            $('.detail-item-card').each(function() {
                const subtotalModelOld = parseFloat($(this).find('.subtotal_model_old').val()) || 0;
                const subtotalKainOld = parseFloat($(this).find('.subtotal_kain_old').val()) || 0;
                const subtotalModelNew = parseFloat($(this).find('.subtotal_model_new').val()) || 0;
                const subtotalKainNew = parseFloat($(this).find('.subtotal_kain_new').val()) || 0;

                const modelFinal = subtotalModelNew > 0 ? subtotalModelNew : subtotalModelOld;
                const kainFinal = subtotalKainNew > 0 ? subtotalKainNew : subtotalKainOld;

                newTotal += modelFinal + kainFinal;
            });

            totalOrderBaru = newTotal;
            $('#totalOrderBaru').text('Rp. ' + formatRupiah(newTotal));

            const selisih = newTotal - totalOrderAwal;
            if (selisih > 0) {
                $('#selisihInfo').html(`<i class="fas fa-arrow-up text-danger"></i> Tambahan biaya: Rp. ${formatRupiah(selisih)}`);
            } else if (selisih < 0) {
                $('#selisihInfo').html(`<i class="fas fa-arrow-down text-success"></i> Pengurangan biaya: Rp. ${formatRupiah(Math.abs(selisih))}`);
            } else {
                $('#selisihInfo').html('Tidak ada perubahan harga');
            }
        }

        function formatRupiah(angka) {
            return angka.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        }

        // Modify modal select functions to use revision context
        const originalSelectModel = window.selectModel;
        window.selectModel = function(element, kodeModel, namaModel) {
            if (currentIndex !== null) {
                // We're in revision context
                $.ajax({
                    url: '<?= base_url('api/model/') ?>' + kodeModel,
                    type: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        selectModelForRevision(kodeModel, data.nama_model, data.foto_model);
                    }
                });
            } else {
                // Normal context
                if (originalSelectModel) originalSelectModel(element, kodeModel, namaModel);
            }
        };

        const originalSelectFabric = window.selectFabric;
        window.selectFabric = function(element, kodeFabric, namaFabric, warnaFabric) {
            if (currentIndex !== null) {
                // We're in revision context
                $.ajax({
                    url: '<?= base_url('api/fabric/') ?>' + kodeFabric,
                    type: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        selectFabricForRevision(kodeFabric, data.nama_jenis_kain, data.warna, data.foto_jenis_kain);
                    }
                });
            } else {
                // Normal context
                if (originalSelectFabric) originalSelectFabric(element, kodeFabric, namaFabric, warnaFabric);
            }
        };
    });
</script>