<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\CustomerModel;
use App\Models\DetailKainModel;
use App\Models\DetailPermintaanModel;
use App\Models\JenisKainModel;
use App\Models\ModelCustomModel;
use App\Models\PermintaanCustomModel;
use App\Models\RevisiModel;
use App\Models\RiwayatPerubahanModel;
use CodeIgniter\HTTP\ResponseInterface;

class PermintaanCustomController extends BaseController
{
    protected $permintaanCustom;
    protected $detailPermintaan;
    protected $detailKain;
    protected $riwayatPerubahanModel;
    protected $revisiModel;
    protected $modelCustom;
    protected $customer;
    protected $jenisKain;
    protected $db;

    public function __construct()
    {
        $this->permintaanCustom = new PermintaanCustomModel();
        $this->detailPermintaan = new DetailPermintaanModel();
        $this->detailKain = new DetailKainModel();
        $this->modelCustom = new ModelCustomModel();
        $this->customer = new CustomerModel();
        $this->jenisKain = new JenisKainModel();
        $this->riwayatPerubahanModel = new RiwayatPerubahanModel();
        $this->revisiModel = new RevisiModel();
        $this->db = db_connect();
    }

    /**
     * Normalize datetime-local input from forms to MySQL DATETIME string
     * Accepts formats like 'YYYY-MM-DDTHH:MM' or 'YYYY-MM-DD HH:MM' or full datetime
     */
    protected function formatDatetimeInput($input)
    {
        if (!$input) return null;
        // replace T with space if present
        $normalized = str_replace('T', ' ', $input);
        // If only minute precision, append seconds
        if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $normalized)) {
            $normalized .= ':00';
        }
        // If input is date-only, append midnight
        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $normalized)) {
            $normalized .= ' 00:00:00';
        }
        // Validate and format
        $ts = strtotime($normalized);
        if ($ts === false) return null;
        return date('Y-m-d H:i:s', $ts);
    }

    public function index()
    {
        $data['title'] = 'Pesanan Custom';
        $builder = $this->permintaanCustom->builder();
        $builder->select('tabel_permintaan_custom.*,tabel_customer.nama');
        $builder->join('tabel_customer', 'tabel_customer.id_customer = tabel_permintaan_custom.id_customer', 'inner');
        if (auth()->user()->role == 'customer'):
            $builder->where('tabel_permintaan_custom.id_customer', auth()->user()->user_id);
            $builder->where('tabel_permintaan_custom.status_pesanan !=', 'selesai');
        endif;

        $orders = $builder->orderBy('tabel_permintaan_custom.created_at', 'desc')->get()->getResult();

        // Check meter pemakaian status for each order
        foreach ($orders as $order) {
            $builderDetail = $this->detailPermintaan->builder();
            $builderDetail->select('tabel_detail_kain.meter_pemakaian');
            $builderDetail->join('tabel_detail_kain', 'tabel_detail_kain.id_detail_order = tabel_detail_permintaan.id_detail_order', 'inner');
            $builderDetail->where('tabel_detail_permintaan.no_order_custom', $order->no_order_custom);
            $detailItems = $builderDetail->get()->getResult();

            $order->has_missing_meter = false;
            foreach ($detailItems as $detail) {
                if (empty($detail->meter_pemakaian) || $detail->meter_pemakaian == 0) {
                    $order->has_missing_meter = true;
                    break;
                }
            }
        }
        $data['type'] = 'order';
        $data['data'] = $orders;
        $data['user_id'] = auth()->user()->user_id;

        return view('permintaan_custom/index', $data);
    }

    public function history()
    {
        $data['title'] = 'Riwayat Pesanan';
        $builder = $this->permintaanCustom->builder();
        $builder->select('tabel_permintaan_custom.*,tabel_customer.nama');
        $builder->join('tabel_customer', 'tabel_customer.id_customer = tabel_permintaan_custom.id_customer', 'inner');

        if (auth()->user()->role == 'customer'):
            $builder->where('tabel_permintaan_custom.id_customer', auth()->user()->user_id);
            $builder->where('tabel_permintaan_custom.status_pesanan', 'selesai');
        endif;

        $orders = $builder->orderBy('tabel_permintaan_custom.created_at', 'desc')->get()->getResult();

        // Check meter pemakaian status for each order
        foreach ($orders as $order) {
            $builderDetail = $this->detailPermintaan->builder();
            $builderDetail->select('tabel_detail_kain.meter_pemakaian');
            $builderDetail->join('tabel_detail_kain', 'tabel_detail_kain.id_detail_order = tabel_detail_permintaan.id_detail_order', 'inner');
            $builderDetail->where('tabel_detail_permintaan.no_order_custom', $order->no_order_custom);
            $detailItems = $builderDetail->get()->getResult();

            $order->has_missing_meter = false;
            foreach ($detailItems as $detail) {
                if (empty($detail->meter_pemakaian) || $detail->meter_pemakaian == 0) {
                    $order->has_missing_meter = true;
                    break;
                }
            }
        }

        $data['type'] = 'history';
        $data['data'] = $orders;
        $data['user_id'] = auth()->user()->user_id;

        return view('permintaan_custom/index', $data);
    }


    public function showPemesanan()
    {
        $user_id = $this->request->getPost('user_id');
        $status = $this->request->getPost('status');

        $builder = $this->permintaanCustom->builder();
        $builder->select('tabel_permintaan_custom.*,tabel_customer.nama');
        $builder->join('tabel_customer', 'tabel_customer.id_customer = tabel_permintaan_custom.id_customer', 'inner');
        $builder->where('tabel_permintaan_custom.id_customer', $user_id);

        if ($status == 'lama') {
            $builder->where('tabel_permintaan_custom.status_pesanan', 'selesai');
        } else {
            $builder->where('tabel_permintaan_custom.status_pesanan !=', 'selesai');
        }

        $orders = $builder->orderBy('tabel_permintaan_custom.created_at', 'desc')->get()->getResult();

        return $this->response->setJSON([
            'data' => $orders,
            'message' => 'Data berhasil di dapatkan',
            'success' => $orders ? true : false
        ]);
    }

    public function create()
    {
        if ($this->request->getMethod() == 'POST') {
            $user_id = auth()->user()->id;

            // Different validation rules based on role
            if (auth()->user()->role == 'customer') {
                $rules = [
                    'id_customer'         => 'required|integer',
                    'tanggal_order' => 'required',
                    'kode_model.*' => 'permit_empty|min_length[1]|max_length[255]',
                    'ukuran_gamis.*' => 'permit_empty|min_length[1]|max_length[255]',
                    'jumlah_pcs.*' => 'required|numeric|greater_than[0]',
                    'kode_jenis_kain.*' => 'permit_empty|min_length[1]|max_length[255]',
                    // Customer tidak perlu validasi meter_pemakaian
                ];
            } else {
                $rules = [
                    'id_customer'         => 'required|integer',
                    'tanggal_order' => 'required',
                    'kode_model.*' => 'permit_empty|min_length[1]|max_length[255]',
                    'ukuran_gamis.*' => 'permit_empty|min_length[1]|max_length[255]',
                    'jumlah_pcs.*' => 'required|numeric|greater_than[0]',
                    'kode_jenis_kain.*' => 'permit_empty|min_length[1]|max_length[255]',
                    'meter_pemakaian.*' => 'permit_empty|min_length[1]|max_length[255]',
                ];
            }

            $builder = $this->permintaanCustom->builder();
            $builder->select('tabel_permintaan_custom.*,tabel_customer.nama');
            $builder->join('tabel_customer', 'tabel_customer.id_customer = tabel_permintaan_custom.id_customer', 'inner');

            if (auth()->user()->role == 'customer'):
                $builder->where('tabel_permintaan_custom.id_customer', auth()->user()->id);
            endif;

            $data = $builder->orderBy('tabel_permintaan_custom.created_at', 'desc')->get()->getResult();
            if (!$this->validate($rules)) {
                return view('permintaan_custom/index', [
                    'title'      => 'Model',
                    'data'       => $data,
                    'validation' =>  $this->validator
                ]);
            }

            $invoice_number = $this->permintaanCustom->generateInvoiceNumber();
            $data = [
                'no_order_custom' => $invoice_number,
                'tanggal_order' => $this->formatDatetimeInput($this->request->getPost('tanggal_order')),
                'tanggal_pengambilan' => $this->formatDatetimeInput($this->request->getPost('tanggal_pengambilan')),
                'id_customer' => $this->request->getPost('id_customer'),
                'catatan_pelanggan' => $this->request->getPost('catatan_pelanggan'),
                'status_pengiriman' => $this->request->getPost('status_pengiriman') ?? 1, // Default ambil di toko
                'alamat_pengiriman' => $this->request->getPost('alamat_pengiriman'),
                'created_by_role' => auth()->user()->role, // Save who created this order
                // 'status_pesanan' => 'menunggu_pembayaran', // Set initial status
                // 'status_pesanan' => 'menunggu_input_meter', // Set initial status
                'status_pesanan' => 'menunggu_konfirmasi_admin', // Set initial status
                'status_admin_konfirmasi' => 1,
            ];

            $this->permintaanCustom->insert($data);
            $id_permintaan = $this->permintaanCustom->getInsertID();

            $nominal = 0;
            foreach ($this->request->getPost('kode_model') as $key => $value) {
                // Get upload_model_sendiri flag first
                $upload_model_sendiri = $this->request->getPost('upload_model_sendiri')[$key] ?? 0;

                // Only find model if not uploading custom model
                $model = null;
                $ongkos_pengerjaan = 0;

                if (!$upload_model_sendiri && !empty($value)) {
                    $model = $this->modelCustom->find($value);
                    if ($model) {
                        $ongkos_pengerjaan = $model->ongkos_pengerjaan;
                    }
                }

                // Handle file upload for gambar_referensi
                $gambarReferensi = null;
                $files = $this->request->getFileMultiple('gambar_referensi');
                if (isset($files[$key]) && $files[$key]->isValid() && !$files[$key]->hasMoved()) {
                    $file = $files[$key];
                    $newName = $file->getRandomName();
                    $file->move('uploads/gambar_referensi', $newName);
                    $gambarReferensi = 'uploads/gambar_referensi/' . $newName;
                }

                // Get custom measurements from POST
                $lingkar_dada = $this->request->getPost('lingkar_dada')[$key] ?? null;
                $lingkar_pinggang = $this->request->getPost('lingkar_pinggang')[$key] ?? null;
                $lingkar_panggul = $this->request->getPost('lingkar_panggul')[$key] ?? null;
                $lebar_bahu = $this->request->getPost('lebar_bahu')[$key] ?? null;
                $panjang_lengan = $this->request->getPost('panjang_lengan')[$key] ?? null;
                $panjang_gamis_custom = $this->request->getPost('panjang_gamis_custom')[$key] ?? null;
                $catatan_detail = $this->request->getPost('catatan_detail')[$key] ?? null;
                $bawa_kain_sendiri = $this->request->getPost('bawa_kain_sendiri')[$key] ?? 0;

                // Get ongkos jahit custom for admin/kasir
                $ongkos_jahit_custom = 0;
                if (auth()->user()->role != 'customer') {
                    $ongkos_jahit_custom = $this->request->getPost('ongkos_jahit_custom')[$key] ?? 0;
                }

                $jumlah_pcs = $this->request->getPost('jumlah_pcs')[$key];

                // Calculate subtotal based on item type
                // Priority: ongkos jahit custom > ongkos pengerjaan model

                // if ($upload_model_sendiri && $bawa_kain_sendiri) {
                if ($upload_model_sendiri) {
                    // Custom model + custom fabric = use ongkos jahit custom
                    // $subtotal_detail = $ongkos_jahit_custom * $jumlah_pcs;
                    $subtotal_detail = ($ongkos_jahit_custom + $ongkos_pengerjaan) * $jumlah_pcs;
                    $ongkos_pengerjaan = $ongkos_jahit_custom; // Set for consistency
                } else {
                    // Use model ongkos pengerjaan
                    $subtotal_detail = $ongkos_pengerjaan * $jumlah_pcs;
                }

                $detailData = [
                    'no_order_custom' => $invoice_number,
                    'kode_model' => $upload_model_sendiri ? null : $value,
                    'jumlah_pcs' => $jumlah_pcs,
                    'ukuran_gamis' => $this->request->getPost('ukuran_gamis')[$key],
                    'ongkos_pengerjaan' => $ongkos_pengerjaan,
                    'subtotal_detail_order' => $subtotal_detail,
                    'lingkar_dada' => $lingkar_dada,
                    'lingkar_pinggang' => $lingkar_pinggang,
                    'lingkar_panggul' => $lingkar_panggul,
                    'lebar_bahu' => $lebar_bahu,
                    'panjang_lengan' => $panjang_lengan,
                    'panjang_gamis' => $panjang_gamis_custom,
                    'catatan_detail' => $catatan_detail,
                    'bawa_kain_sendiri' => $bawa_kain_sendiri,
                    'upload_model_sendiri' => $upload_model_sendiri,
                    'ongkos_jahit_custom' => $ongkos_jahit_custom,
                ];

                if ($gambarReferensi) {
                    $detailData['gambar_referensi'] = $gambarReferensi;
                }

                $this->detailPermintaan->insert($detailData);

                $insertedId = $this->detailPermintaan->getInsertID();

                // Handle fabrics
                // meter_pemakaian dari frontend = total meter dari primary fabric saja (untuk backward compatibility)
                // additional_fabrics berisi array fabric tambahan dengan meter masing-masing
                $kode_kain = $this->request->getPost('kode_jenis_kain')[$key];
                $meter_pemakaian = $this->request->getPost('meter_pemakaian')[$key] ?? 0;
                $jumlah_pcs = $this->request->getPost('jumlah_pcs')[$key];

                // Only process if fabric is selected (not "bawa sendiri")
                if (!empty($kode_kain)) {
                    $jenis_kain = $this->jenisKain->find($kode_kain);

                    if ($jenis_kain) {
                        $harga_per_meter = $jenis_kain->harga_per_meter ?? 0;
                        $subtotal_kain = $harga_per_meter * $meter_pemakaian * $jumlah_pcs;

                        // Check for additional fabrics (JSON from frontend)
                        $additional_fabrics_raw = $this->request->getPost('additional_fabrics')[$key] ?? null;
                        $additional_fabrics = null;

                        if (!empty($additional_fabrics_raw)) {
                            // Parse and validate JSON
                            $decoded = json_decode($additional_fabrics_raw, true);
                            if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                                $additional_fabrics = json_encode($decoded);

                                // Calculate total from additional fabrics
                                foreach ($decoded as $addFabric) {
                                    $addKain = $this->jenisKain->find($addFabric['kode'] ?? '');
                                    if ($addKain) {
                                        $addMeter = floatval($addFabric['meter'] ?? 0);
                                        $subtotal_kain += ($addKain->harga_per_meter * $addMeter * $jumlah_pcs);
                                    }
                                }
                            }
                        }

                        $this->detailKain->insert([
                            'id_detail_order' => $insertedId,
                            'kode_jenis_kain' => $kode_kain,
                            'meter_pemakaian' => $meter_pemakaian,
                            'harga_per_meter' => $harga_per_meter,
                            'subtotal_detail_kain' => $subtotal_kain,
                            'additional_fabrics' => $additional_fabrics,
                        ]);

                        $nominal += ($ongkos_pengerjaan * $jumlah_pcs) + $subtotal_kain;
                    } else {
                        // Fabric code not found - still add model cost
                        $nominal += ($ongkos_pengerjaan * $jumlah_pcs);
                    }
                } else {
                    // No fabric selected (bawa sendiri)
                    // Add only model/ongkos jahit cost
                    $nominal += ($ongkos_pengerjaan * $jumlah_pcs);

                    // Insert empty record for consistency (optional, bisa dihapus jika tidak perlu)
                    // $this->detailKain->insert([
                    //     'id_detail_order' => $insertedId,
                    //     'kode_jenis_kain' => null,
                    //     'meter_pemakaian' => 0,
                    //     'harga_per_meter' => 0,
                    //     'subtotal_detail_kain' => 0,
                    //     'additional_fabrics' => null,
                    // ]);
                }
            }
            $this->permintaanCustom->update($id_permintaan, ['nominal_pelunasan' => $nominal, 'total_order' => count($this->request->getPost('kode_model'))]);

            session()->setFlashdata('success', 'Tambah Pesanan Berhasil');
            return redirect()->to('/permintaan_custom');
        }

        $data['title'] = 'Tambah Pesanan Custom';
        $data['customer'] = $this->customer->orderBy('created_at', 'desc')->findAll();
        $data['model'] = $this->modelCustom->orderBy('created_at', 'desc')->findAll();
        $data['jenis_kain'] = $this->jenisKain->orderBy('created_at', 'desc')->findAll();
        return view('permintaan_custom/create', $data);
    }

    public function edit($id)
    {
        helper(['form']);
        $request = $this->request;

        if ($this->request->getMethod() == 'POST') {
            // Different validation rules based on role
            if (auth()->user()->role == 'customer') {
                $rules = [
                    'id_customer'         => 'required|integer',
                    'tanggal_order' => 'required',
                    'kode_model.*' => 'permit_empty|min_length[1]|max_length[255]',
                    'ukuran_gamis.*' => 'permit_empty|min_length[1]|max_length[255]',
                    'jumlah_pcs.*' => 'required|numeric|greater_than[0]',
                    'kode_jenis_kain.*' => 'permit_empty|min_length[1]|max_length[255]',
                    // Customer tidak perlu validasi meter_pemakaian
                ];
            } else {
                $rules = [
                    'id_customer'         => 'required|integer',
                    'tanggal_order' => 'required',
                    'kode_model.*' => 'permit_empty|min_length[1]|max_length[255]',
                    'ukuran_gamis.*' => 'permit_empty|min_length[1]|max_length[255]',
                    'jumlah_pcs.*' => 'required|numeric|greater_than[0]',
                    'kode_jenis_kain.*' => 'permit_empty|min_length[1]|max_length[255]',
                    'meter_pemakaian.*' => 'permit_empty|min_length[1]|max_length[255]',
                ];
            }

            $builder = $this->permintaanCustom->builder();
            $builder->select('tabel_permintaan_custom.*,tabel_customer.nama');
            $builder->join('tabel_customer', 'tabel_customer.id_customer = tabel_permintaan_custom.id_customer', 'inner');
            if (auth()->user()->role == 'customer'):
                $builder->where('tabel_permintaan_custom.id_customer', auth()->user()->id);
            endif;

            $data = $builder->orderBy('tabel_permintaan_custom.created_at', 'desc')->get()->getResult();
            if (!$this->validate($rules)) {
                return view('permintaan_custom/index', [
                    'title'      => 'Model',
                    'data'       => $data,
                    'validation' =>  $this->validator
                ]);
            }

            $dataUpdate = [
                'tanggal_order' => $this->formatDatetimeInput($this->request->getPost('tanggal_order')),
                'tanggal_pengambilan' => $this->formatDatetimeInput($this->request->getPost('tanggal_pengambilan')),
                'id_customer' => $this->request->getPost('id_customer'),
                'catatan_pelanggan' => $this->request->getPost('catatan_pelanggan'),
                'status_pengiriman' => $this->request->getPost('status_pengiriman') ?? 1,
                'alamat_pengiriman' => $this->request->getPost('alamat_pengiriman'),
                'status_admin_konfirmasi' => 1,
            ];

            $this->permintaanCustom->update($id, $dataUpdate);
            $invoice_number = $this->permintaanCustom->find($id)->no_order_custom;
            // Capture previous nominal for revision history
            $oldOrder = $this->permintaanCustom->find($id);
            $old_nominal = $oldOrder->nominal_pelunasan ?? 0;

            // Fetch existing detail rows (with kain) for granular comparison
            $builderOld = $this->detailPermintaan->builder();
            $builderOld->select('tabel_detail_permintaan.*, tabel_detail_kain.kode_jenis_kain as kode_jenis_kain_old, tabel_detail_kain.meter_pemakaian as meter_pemakaian_old, tabel_detail_kain.subtotal_detail_kain as subtotal_detail_kain_old');
            $builderOld->join('tabel_detail_kain', 'tabel_detail_kain.id_detail_order = tabel_detail_permintaan.id_detail_order', 'inner');
            $builderOld->where('tabel_detail_permintaan.no_order_custom', $invoice_number);
            $oldDetails = $builderOld->orderBy('tabel_detail_permintaan.created_at', 'asc')->get()->getResult();

            // Map old details by index to compare with incoming POST arrays
            $oldItems = [];
            foreach ($oldDetails as $od) {
                $oldItems[] = $od;
            }

            // First pass: Collect all history records and item details BEFORE deleting
            $nominal = 0;
            $itemsDetails = []; // Store detail items untuk revisi
            $historyRecords = []; // Collect history records to insert after delete
            $postModels = $this->request->getPost('kode_model');

            foreach ($postModels as $key => $value) {
                $newKodeModel = $value;
                $newJumlah = $this->request->getPost('jumlah_pcs')[$key];
                $newUkuran = $this->request->getPost('ukuran_gamis')[$key];
                $newKodeKain = $this->request->getPost('kode_jenis_kain')[$key];
                $newMeter = $this->request->getPost('meter_pemakaian')[$key];

                // Get custom measurements
                $newLingkarDada = $this->request->getPost('lingkar_dada')[$key] ?? null;
                $newLingkarPinggang = $this->request->getPost('lingkar_pinggang')[$key] ?? null;
                $newLingkarPanggul = $this->request->getPost('lingkar_panggul')[$key] ?? null;
                $newLebarBahu = $this->request->getPost('lebar_bahu')[$key] ?? null;
                $newPanjangLengan = $this->request->getPost('panjang_lengan')[$key] ?? null;
                $newPanjangGamis = $this->request->getPost('panjang_gamis_custom')[$key] ?? null;

                // Get upload flags
                $upload_model_sendiri_tracking = $this->request->getPost('upload_model_sendiri')[$key] ?? 0;
                $bawa_kain_sendiri_tracking = $this->request->getPost('bawa_kain_sendiri')[$key] ?? 0;

                // Get custom sewing fee if applicable
                $ongkos_jahit_custom_tracking = $this->request->getPost('ongkos_jahit_custom')[$key] ?? 0;

                // Only find model/kain if not using custom
                $model = null;
                $jenis_kain = null;
                $ongkos_pengerjaan_tracking = 0;
                $harga_per_meter_tracking = 0;
                $nama_model = '';
                $nama_jenis_kain = '';
                $warna = '';

                if (!$upload_model_sendiri_tracking && !empty($newKodeModel)) {
                    $model = $this->modelCustom->find($newKodeModel);
                    if ($model) {
                        $ongkos_pengerjaan_tracking = $model->ongkos_pengerjaan;
                        $nama_model = $model->nama_model;
                    }
                }

                // Use custom sewing fee if both flags are set
                if ($upload_model_sendiri_tracking && $bawa_kain_sendiri_tracking && $ongkos_jahit_custom_tracking > 0) {
                    $ongkos_pengerjaan_tracking = $ongkos_jahit_custom_tracking;
                }

                if (!$bawa_kain_sendiri_tracking && !empty($newKodeKain)) {
                    $jenis_kain = $this->jenisKain->find($newKodeKain);
                    if ($jenis_kain) {
                        $harga_per_meter_tracking = $jenis_kain->harga_per_meter;
                        $nama_jenis_kain = $jenis_kain->nama_jenis_kain;
                        $warna = $jenis_kain->warna;
                    }
                }

                $new_subtotal_model = $ongkos_pengerjaan_tracking * $newJumlah;
                $new_subtotal_kain = $harga_per_meter_tracking * $newMeter * $newJumlah;
                $new_item_total = $new_subtotal_model + $new_subtotal_kain;

                // Store item detail untuk revisi
                $itemDetail = [
                    'item_number' => $key + 1,
                    'kode_model' => $upload_model_sendiri_tracking ? null : $newKodeModel,
                    'nama_model' => $nama_model,
                    'kode_jenis_kain' => $bawa_kain_sendiri_tracking ? null : $newKodeKain,
                    'nama_jenis_kain' => $nama_jenis_kain,
                    'warna' => $warna,
                    'ukuran' => $newUkuran,
                    'jumlah_pcs' => $newJumlah,
                    'meter_pemakaian' => $newMeter,
                    'harga_model' => $ongkos_pengerjaan_tracking,
                    'harga_kain' => $harga_per_meter_tracking,
                    'subtotal_model' => $new_subtotal_model,
                    'subtotal_kain' => $new_subtotal_kain,
                    'total_item' => $new_item_total,
                    'lingkar_dada' => $newLingkarDada,
                    'lingkar_pinggang' => $newLingkarPinggang,
                    'lingkar_panggul' => $newLingkarPanggul,
                    'lebar_bahu' => $newLebarBahu,
                    'panjang_lengan' => $newPanjangLengan,
                    'panjang_gamis' => $newPanjangGamis,
                    'is_new' => false,
                    'changes' => []
                ];

                // Compare with old item if exists
                $old = $oldItems[$key] ?? null;
                $changes = [];
                $old_item_total = 0;
                $old_id_detail = 0;
                if ($old) {
                    $old_id_detail = $old->id_detail_order;
                    if ($old->kode_model != $newKodeModel) {
                        $changes[] = "Model: {$old->kode_model} → {$newKodeModel}";
                    }
                    if (($old->kode_jenis_kain_old ?? null) != $newKodeKain) {
                        $changes[] = "Jenis Kain: " . ($old->kode_jenis_kain_old ?? '-') . " → {$newKodeKain}";
                    }
                    if (($old->jumlah_pcs ?? null) != $newJumlah) {
                        $changes[] = "Jumlah: " . ($old->jumlah_pcs ?? '-') . " → {$newJumlah}";
                    }
                    if (($old->ukuran_gamis ?? null) != $newUkuran) {
                        $changes[] = "Ukuran: " . ($old->ukuran_gamis ?? '-') . " → {$newUkuran}";
                    }
                    if (($old->meter_pemakaian_old ?? null) != $newMeter) {
                        $changes[] = "Meter: " . ($old->meter_pemakaian_old ?? '-') . " → {$newMeter}";
                    }

                    // Check custom measurements changes
                    if (($old->lingkar_dada ?? null) != $newLingkarDada) {
                        $changes[] = "Lingkar Dada: " . ($old->lingkar_dada ?? '-') . " → " . ($newLingkarDada ?? '-');
                    }
                    if (($old->lingkar_pinggang ?? null) != $newLingkarPinggang) {
                        $changes[] = "Lingkar Pinggang: " . ($old->lingkar_pinggang ?? '-') . " → " . ($newLingkarPinggang ?? '-');
                    }
                    if (($old->lingkar_panggul ?? null) != $newLingkarPanggul) {
                        $changes[] = "Lingkar Panggul: " . ($old->lingkar_panggul ?? '-') . " → " . ($newLingkarPanggul ?? '-');
                    }
                    if (($old->lebar_bahu ?? null) != $newLebarBahu) {
                        $changes[] = "Lebar Bahu: " . ($old->lebar_bahu ?? '-') . " → " . ($newLebarBahu ?? '-');
                    }
                    if (($old->panjang_lengan ?? null) != $newPanjangLengan) {
                        $changes[] = "Panjang Lengan: " . ($old->panjang_lengan ?? '-') . " → " . ($newPanjangLengan ?? '-');
                    }
                    if (($old->panjang_gamis ?? null) != $newPanjangGamis) {
                        $changes[] = "Panjang Gamis: " . ($old->panjang_gamis ?? '-') . " → " . ($newPanjangGamis ?? '-');
                    }

                    // Check custom sewing fee changes
                    if (($old->ongkos_jahit_custom ?? 0) != $ongkos_jahit_custom_tracking) {
                        $changes[] = "Ongkos Jahit Custom: Rp. " . number_format($old->ongkos_jahit_custom ?? 0, 0, ',', '.') . " → Rp. " . number_format($ongkos_jahit_custom_tracking, 0, ',', '.');
                    }

                    $old_subtotal_model = $old->ongkos_pengerjaan ?? 0;
                    $old_subtotal_model = ($old_subtotal_model) * ($old->jumlah_pcs ?? 0);
                    $old_subtotal_kain = $old->subtotal_detail_kain_old ?? 0;
                    $old_item_total = $old_subtotal_model + $old_subtotal_kain;
                } else {
                    $changes[] = 'Item baru ditambahkan';
                    $itemDetail['is_new'] = true;
                }

                // Store changes to itemDetail
                $itemDetail['changes'] = $changes;

                // Collect history record if there are changes (to be inserted AFTER delete)
                $difference = $new_item_total - $old_item_total;
                if (!empty($changes) || $difference != 0) {
                    $keterangan = implode('; ', $changes) . ' (Selisih harga: Rp. ' . number_format($difference, 0, ',', '.') . ')';

                    // Only collect history for valid id_detail_order (skip new items)
                    if ($old_id_detail > 0) {
                        $historyRecords[] = [
                            'id_detail_order' => $old_id_detail,
                            'tanggal_permintaan_revisi' => date('Y-m-d H:i:s'),
                            'keterangan_permintaan_revisi' => $keterangan,
                            'status' => 1,
                            'tipe_revisi' => 'detail_change',
                            'biaya_revisi' => $difference > 0 ? $difference : 0,
                            'tgl_diterima_pegawai' => null
                        ];
                    }
                }

                $itemsDetails[] = $itemDetail;
                $nominal += $new_item_total;
            }

            // Insert all collected history records BEFORE deleting (while old IDs still exist)
            foreach ($historyRecords as $historyRecord) {
                $this->riwayatPerubahanModel->insert($historyRecord);
            }

            // Now delete existing detail rows (this will NOT cascade to history we just inserted)
            $this->detailPermintaan->where('no_order_custom', $invoice_number)->delete();

            // Second pass: Insert new detail and kain records
            foreach ($postModels as $key => $value) {
                $newKodeModel = $value;
                $newJumlah = $this->request->getPost('jumlah_pcs')[$key];
                $newUkuran = $this->request->getPost('ukuran_gamis')[$key];
                $newKodeKain = $this->request->getPost('kode_jenis_kain')[$key];
                $newMeter = $this->request->getPost('meter_pemakaian')[$key];

                // Get upload flags
                $upload_model_sendiri = $this->request->getPost('upload_model_sendiri')[$key] ?? 0;
                $bawa_kain_sendiri = $this->request->getPost('bawa_kain_sendiri')[$key] ?? 0;

                // Get ongkos_jahit_custom from POST (for items with bawa_kain_sendiri & upload_model_sendiri)
                $ongkos_jahit_custom = 0;
                if ($upload_model_sendiri && $bawa_kain_sendiri) {
                    $ongkos_jahit_custom = $this->request->getPost('ongkos_jahit_custom')[$key] ?? 0;
                }

                // Only find model/kain if not using custom
                $model = null;
                $jenis_kain = null;
                $ongkos_pengerjaan = 0;
                $harga_per_meter = 0;

                if (!$upload_model_sendiri && !empty($newKodeModel)) {
                    $model = $this->modelCustom->find($newKodeModel);
                    if ($model) {
                        $ongkos_pengerjaan = $model->ongkos_pengerjaan;
                    }
                } else if ($upload_model_sendiri && $ongkos_jahit_custom > 0) {
                    // Use ongkos_jahit_custom for custom items
                    $ongkos_pengerjaan = $ongkos_jahit_custom;
                }

                if (!$bawa_kain_sendiri && !empty($newKodeKain)) {
                    $jenis_kain = $this->jenisKain->find($newKodeKain);
                    if ($jenis_kain) {
                        $harga_per_meter = $jenis_kain->harga_per_meter;
                    }
                }

                $new_subtotal_model = $ongkos_pengerjaan * $newJumlah;
                $new_subtotal_kain = $harga_per_meter * $newMeter * $newJumlah;

                // Handle file upload for gambar_referensi
                $gambarReferensi = null;
                $files = $this->request->getFileMultiple('gambar_referensi');
                if (isset($files[$key]) && $files[$key]->isValid() && !$files[$key]->hasMoved()) {
                    $file = $files[$key];
                    $newName = $file->getRandomName();
                    $file->move('uploads/gambar_referensi', $newName);
                    $gambarReferensi = 'uploads/gambar_referensi/' . $newName;
                }

                // Get custom measurements from POST
                $lingkar_dada = $this->request->getPost('lingkar_dada')[$key] ?? null;
                $lingkar_pinggang = $this->request->getPost('lingkar_pinggang')[$key] ?? null;
                $lingkar_panggul = $this->request->getPost('lingkar_panggul')[$key] ?? null;
                $lebar_bahu = $this->request->getPost('lebar_bahu')[$key] ?? null;
                $panjang_lengan = $this->request->getPost('panjang_lengan')[$key] ?? null;
                $panjang_gamis_custom = $this->request->getPost('panjang_gamis_custom')[$key] ?? null;
                $catatan_detail = $this->request->getPost('catatan_detail')[$key] ?? null;

                // Insert updated detail and kain
                $detailData = [
                    'no_order_custom' => $invoice_number,
                    'kode_model' => $upload_model_sendiri ? null : $newKodeModel,
                    'jumlah_pcs' => $newJumlah,
                    'ukuran_gamis' => $newUkuran,
                    'ongkos_pengerjaan' => $ongkos_pengerjaan,
                    'subtotal_detail_order' => $new_subtotal_model,
                    'lingkar_dada' => $lingkar_dada,
                    'lingkar_pinggang' => $lingkar_pinggang,
                    'lingkar_panggul' => $lingkar_panggul,
                    'lebar_bahu' => $lebar_bahu,
                    'panjang_lengan' => $panjang_lengan,
                    'panjang_gamis' => $panjang_gamis_custom,
                    'catatan_detail' => $catatan_detail,
                    'bawa_kain_sendiri' => $bawa_kain_sendiri,
                    'upload_model_sendiri' => $upload_model_sendiri,
                    'ongkos_jahit_custom' => $ongkos_jahit_custom, // Save ongkos jahit custom
                ];

                if ($gambarReferensi) {
                    $detailData['gambar_referensi'] = $gambarReferensi;
                }

                $this->detailPermintaan->insert($detailData);

                $insertedId = $this->detailPermintaan->getInsertID();

                // Check for additional fabrics (JSON from frontend)
                $additional_fabrics_raw = $this->request->getPost('additional_fabrics')[$key] ?? null;
                $additional_fabrics = null;

                // DEBUG: Log received additional_fabrics
                log_message('debug', "=== ITEM {$key} - ADDITIONAL FABRICS DEBUG ===");
                log_message('debug', "Received additional_fabrics_raw: " . var_export($additional_fabrics_raw, true));
                error_log("CUSTOM_DEBUG: Item {$key} - additional_fabrics_raw: " . var_export($additional_fabrics_raw, true));

                if (!empty($additional_fabrics_raw)) {
                    // Parse and validate JSON
                    $decoded = json_decode($additional_fabrics_raw, true);
                    log_message('debug', "JSON decode result: " . print_r($decoded, true));
                    log_message('debug', "JSON error: " . json_last_error_msg());
                    error_log("CUSTOM_DEBUG: Item {$key} - Decoded: " . print_r($decoded, true));

                    if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                        $additional_fabrics = json_encode($decoded);
                        log_message('debug', "Will save additional_fabrics: {$additional_fabrics}");
                        error_log("CUSTOM_DEBUG: Item {$key} - Will save: {$additional_fabrics}");

                        // Calculate total from additional fabrics
                        foreach ($decoded as $addFabric) {
                            $addKain = $this->jenisKain->find($addFabric['kode'] ?? '');
                            if ($addKain) {
                                $addMeter = floatval($addFabric['meter'] ?? 0);
                                $new_subtotal_kain += ($addKain->harga_per_meter * $addMeter * $newJumlah);
                            }
                        }
                    }
                } else {
                    log_message('debug', "Item {$key}: additional_fabrics_raw is empty or null");
                }

                log_message('debug', "Item {$key}: Final additional_fabrics to insert: " . ($additional_fabrics ?? 'NULL'));

                $this->detailKain->insert([
                    'id_detail_order' => $insertedId,
                    'kode_jenis_kain' => $bawa_kain_sendiri ? null : $newKodeKain,
                    'meter_pemakaian' => $newMeter,
                    'harga_per_meter' => $harga_per_meter,
                    'subtotal_detail_kain' => $new_subtotal_kain,
                    'additional_fabrics' => $additional_fabrics,
                ]);

                log_message('debug', "Item {$key}: Detail kain inserted with ID: " . $this->detailKain->getInsertID());
            }

            // Calculate difference and save riwayat if there's change
            $new_nominal = $nominal;
            $difference = $new_nominal - $old_nominal;

            // Note: Total nominal difference will be saved to tabel_revisi below using RevisiModel
            // No need to insert to tabel_history_revisi_order with id_detail_order=0

            $this->permintaanCustom->update($id, ['nominal_pelunasan' => $new_nominal, 'total_order' => count($this->request->getPost('kode_model'))]);

            // Save revision history
            $user = $this->customer->where('id_customer', $this->request->getPost('id_customer'))->first();
            $changesData = [
                'old_nominal' => $old_nominal,
                'new_nominal' => $new_nominal,
                'difference' => $difference,
                'total_items' => count($this->request->getPost('kode_model')),
                'items_details' => $itemsDetails, // Include detail items
                'timestamp' => date('Y-m-d H:i:s'),
            ];

            $this->revisiModel->saveRevision(
                $invoice_number,
                $user->id_customer,
                $user->name ?? $user->username,
                $changesData
            );

            // Check if all meters are filled and update status to 'diproses'
            $currentOrder = $this->permintaanCustom->find($id);
            if ($currentOrder->status_pesanan === 'menunggu_input_meter') {
                $builderMeterCheck = $this->detailPermintaan->builder();
                $builderMeterCheck->select('tabel_detail_kain.meter_pemakaian');
                $builderMeterCheck->join('tabel_detail_kain', 'tabel_detail_kain.id_detail_order = tabel_detail_permintaan.id_detail_order', 'inner');
                $builderMeterCheck->where('tabel_detail_permintaan.no_order_custom', $invoice_number);
                $detailItems = $builderMeterCheck->get()->getResult();

                $allMetersFilled = true;
                foreach ($detailItems as $detail) {
                    if (empty($detail->meter_pemakaian) || $detail->meter_pemakaian == 0) {
                        $allMetersFilled = false;
                        break;
                    }
                }

                // If all meters are filled, update status to 'diproses'
                if ($allMetersFilled) {
                    $this->permintaanCustom->update($id, [
                        'status_pesanan' => 'diproses',
                        'meter_completed_at' => date('Y-m-d H:i:s')
                    ]);
                }
            }

            return redirect()->to('permintaan_custom')->with('success', 'Revisi Pesanan Berhasil');
        }

        $data['title'] = 'Edit Pesanan Custom';
        $permintaanCustom = $this->permintaanCustom->find($id);
        $data['data'] = $permintaanCustom;
        $data['customer'] = $this->customer->orderBy('created_at', 'desc')->findAll();
        $data['model'] = $this->modelCustom->orderBy('created_at', 'desc')->findAll();
        $data['jenis_kain'] = $this->jenisKain->orderBy('created_at', 'desc')->findAll();

        $builder = $this->detailPermintaan->builder();
        $builder->select('tabel_detail_permintaan.*, tabel_detail_kain.*, tabel_jenis_kain.nama_jenis_kain, tabel_jenis_kain.warna, tabel_jenis_kain.foto_jenis_kain, tabel_jenis_kain.harga_per_meter, tabel_model.nama_model, tabel_model.foto_model, tabel_model.ongkos_pengerjaan');
        $builder->join('tabel_detail_kain', 'tabel_detail_kain.id_detail_order = tabel_detail_permintaan.id_detail_order', 'left');
        $builder->join('tabel_jenis_kain', 'tabel_jenis_kain.kode_jenis_kain = tabel_detail_kain.kode_jenis_kain', 'left');
        $builder->join('tabel_model', 'tabel_model.kode_model = tabel_detail_permintaan.kode_model', 'left');
        $builder->where('tabel_detail_permintaan.no_order_custom', $permintaanCustom->no_order_custom);
        $data['detail_model'] = $builder->orderBy('tabel_detail_permintaan.created_at', 'desc')->get()->getResult();

        return view('permintaan_custom/edit', $data);
    }

    public function delete($id)
    {
        $this->permintaanCustom->delete($id);
        return redirect()->to('/permintaan_custom')->with('success', 'Pesanan Custom berhasil dihapus.');
    }

    public function detail($id)
    {
        $data['title'] = 'Detail Model';
        $builder = $this->permintaanCustom->builder();
        $builder->select('tabel_permintaan_custom.*,tabel_customer.nama');
        $builder->join('tabel_customer', 'tabel_customer.id_customer = tabel_permintaan_custom.id_customer', 'inner');
        $builder->where('tabel_permintaan_custom.kode_permintaan_custom', $id);
        $permintaanCustom = $builder->orderBy('tabel_permintaan_custom.created_at', 'desc')->get()->getRow();

        if (!$permintaanCustom) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Order tidak ditemukan');
        }

        $data['data'] = $permintaanCustom;

        $builder = $this->detailPermintaan->builder();
        $builder->select('tabel_detail_permintaan.*, tabel_detail_kain.meter_pemakaian, tabel_detail_kain.harga_per_meter, tabel_detail_kain.subtotal_detail_kain, tabel_detail_kain.kode_jenis_kain, tabel_detail_kain.additional_fabrics, tabel_jenis_kain.nama_jenis_kain, tabel_jenis_kain.warna, tabel_jenis_kain.foto_jenis_kain, tabel_model.nama_model, tabel_model.foto_model');
        $builder->join('tabel_detail_kain', 'tabel_detail_kain.id_detail_order = tabel_detail_permintaan.id_detail_order', 'left');
        $builder->join('tabel_jenis_kain', 'tabel_jenis_kain.kode_jenis_kain = tabel_detail_kain.kode_jenis_kain', 'left');
        $builder->join('tabel_model', 'tabel_model.kode_model = tabel_detail_permintaan.kode_model', 'left');
        $builder->where('tabel_detail_permintaan.no_order_custom', $permintaanCustom->no_order_custom);
        $detailResult = $builder->orderBy('tabel_detail_permintaan.created_at', 'desc')->get()->getResult();

        // Debug log
        log_message('debug', 'Detail Model Count: ' . count($detailResult));
        log_message('debug', 'Order: ' . $permintaanCustom->no_order_custom);

        $data['detail_model'] = $detailResult;
        $data['riwayatPerubahanModel'] = $this->riwayatPerubahanModel;

        // Get revision history
        $userRole = auth()->user()->role;
        $userId = auth()->user()->id;
        $data['revisions'] = $this->revisiModel->getRevisionsByOrder($permintaanCustom->no_order_custom, $userRole, $userId);

        return view('permintaan_custom/detail', $data);
    }


    public function ConrfirmOrder($id)
    {
        $data['title'] = 'Konfirmasi Pesanan';
        $builder = $this->permintaanCustom->builder();
        $builder->select('tabel_permintaan_custom.*,tabel_customer.nama');
        $builder->join('tabel_customer', 'tabel_customer.id_customer = tabel_permintaan_custom.id_customer', 'inner');
        $builder->where('tabel_permintaan_custom.kode_permintaan_custom', $id);
        $permintaanCustom = $builder->orderBy('tabel_permintaan_custom.created_at', 'desc')->get()->getRow();

        if (!$permintaanCustom) {
            return redirect()->to('/permintaan_custom')->with('error', 'Order tidak ditemukan');
        }

        $data['data'] = $permintaanCustom;

        $builder = $this->detailPermintaan->builder();
        $builder->select('tabel_detail_permintaan.*, tabel_detail_kain.meter_pemakaian, tabel_detail_kain.harga_per_meter, tabel_detail_kain.subtotal_detail_kain, tabel_detail_kain.kode_jenis_kain, tabel_detail_kain.additional_fabrics, tabel_jenis_kain.nama_jenis_kain, tabel_jenis_kain.warna, tabel_jenis_kain.foto_jenis_kain, tabel_model.nama_model, tabel_model.foto_model');
        $builder->join('tabel_detail_kain', 'tabel_detail_kain.id_detail_order = tabel_detail_permintaan.id_detail_order', 'left');
        $builder->join('tabel_jenis_kain', 'tabel_jenis_kain.kode_jenis_kain = tabel_detail_kain.kode_jenis_kain', 'left');
        $builder->join('tabel_model', 'tabel_model.kode_model = tabel_detail_permintaan.kode_model', 'left');
        $builder->where('tabel_detail_permintaan.no_order_custom', $permintaanCustom->no_order_custom);
        $data['detail_model'] = $builder->orderBy('tabel_detail_permintaan.created_at', 'desc')->get()->getResult();
        $data['riwayatPerubahanModel'] = $this->riwayatPerubahanModel;

        return view('permintaan_custom/detail', $data);
    }

    /**
     * Konfirmasi pesanan oleh admin
     * Mengubah status dari pending menjadi approved
     */
    public function confirmAsAdmin($id)
    {
        $order = $this->permintaanCustom->find($id);
        if (!$order) {
            return $this->response->setStatusCode(404)->setJSON(['status' => 'error', 'message' => 'Order tidak ditemukan']);
        }

        // Hitung estimasi selesai (default ~10 hari) and store with time
        $estimasi_selesai = date('Y-m-d H:i:s', strtotime('+10 days'));

        $data = [
            'status_admin_konfirmasi' => 1,
            'tgl_admin_konfirmasi' => date('Y-m-d H:i:s'),
            'estimasi_selesai' => $estimasi_selesai,
            // 'status_pesanan' => 'menunggu_pembayaran' // Update status after admin confirmation
            'status_pesanan' => 'menunggu_input_meter'
        ];

        $this->permintaanCustom->update($id, $data);

        return redirect()->back()->with('success', 'Pesanan berhasil dikonfirmasi');
    }

    /**
     * Reject pesanan oleh admin dengan alasan
     */
    public function rejectAsAdmin($id)
    {
        if (auth()->user()->role != 'admin') {
            return $this->response->setStatusCode(403)->setJSON(['status' => 'error', 'message' => 'Unauthorized']);
        }

        $order = $this->permintaanCustom->find($id);
        if (!$order) {
            return $this->response->setStatusCode(404)->setJSON(['status' => 'error', 'message' => 'Order tidak ditemukan']);
        }

        $data = [
            'status_admin_konfirmasi' => 2,
            'tgl_admin_konfirmasi' => date('Y-m-d H:i:s'),
            'catatan_toko' => $this->request->getPost('alasan_reject')
        ];

        $this->permintaanCustom->update($id, $data);
        return redirect()->back()->with('warning', 'Pesanan ditolak oleh admin');
    }

    /**
     * Konfirmasi pesanan oleh kasir (setelah pembayaran)
     */
    public function confirmAsKasir($id)
    {
        if (auth()->user()->role != 'kasir') {
            return redirect()->back()->with('error', 'Unauthorized');
        }

        $order = $this->permintaanCustom->find($id);
        if (!$order) {
            return redirect()->back()->with('error', 'Order tidak ditemukan');
        }

        $data = [
            'status_admin_konfirmasi' => 1,
            'tgl_admin_konfirmasi' => date('Y-m-d H:i:s'),
            'tanggal_pengambilan' => $this->request->getPost('tanggal_pengambilan'),
            'status_pesanan' => $this->request->getPost('status_pesanan'),
            'estimasi_pengerjaan' => $this->request->getPost('estimasi_pengerjaan')
        ];

        $this->permintaanCustom->update($id, $data);
        return redirect()->back()->with('success', 'Pesanan berhasil dikonfirmasi');
    }

    /**
     * Update status pesanan oleh kasir (setelah lunas)
     */
    public function updateStatus($id)
    {
        if (auth()->user()->role != 'kasir') {
            return redirect()->back()->with('error', 'Unauthorized');
        }

        $order = $this->permintaanCustom->find($id);
        if (!$order) {
            return redirect()->back()->with('error', 'Order tidak ditemukan');
        }

        // Pastikan sudah lunas dan sudah dikonfirmasi
        if ($order->status_pelunasan != 2 || $order->status_admin_konfirmasi != 1) {
            return redirect()->back()->with('error', 'Pesanan belum memenuhi syarat untuk update status');
        }

        $data = [
            'tanggal_pengambilan' => $this->request->getPost('tanggal_pengambilan'),
            'status_pesanan' => $this->request->getPost('status_pesanan'),
            'estimasi_pengerjaan' => $this->request->getPost('estimasi_pengerjaan')
        ];

        $this->permintaanCustom->update($id, $data);
        return redirect()->back()->with('success', 'Status pesanan berhasil diupdate');
    }

    /**
     * Update status pesanan (diproses -> selesai)
     */
    public function updateOrderStatus($id)
    {
        if (!in_array(auth()->user()->role, ['admin', 'kasir'])) {
            return $this->response->setStatusCode(403)->setJSON(['status' => 'error', 'message' => 'Unauthorized']);
        }

        $status = $this->request->getPost('status_pesanan');
        $validStatus = ['diproses', 'selesai'];

        if (!in_array($status, $validStatus)) {
            return $this->response->setStatusCode(400)->setJSON(['status' => 'error', 'message' => 'Status tidak valid']);
        }

        $updateData = ['status_pesanan' => $status];

        // Add timestamp when production is completed
        if ($status === 'selesai') {
            $updateData['production_completed_at'] = date('Y-m-d H:i:s');
        } elseif ($status === 'diproses') {
            // When admin/kasir manually sets to diproses
            $updateData['production_started_at'] = date('Y-m-d H:i:s');
        }

        $this->permintaanCustom->update($id, $updateData);

        return $this->response->setStatusCode(200)->setJSON(['status' => 'success', 'message' => 'Status pesanan berhasil diperbarui']);
    }

    /**
     * Tambah catatan pada pesanan
     */
    public function addNotes($id)
    {
        $order = $this->permintaanCustom->find($id);
        if (!$order) {
            return $this->response->setStatusCode(404)->setJSON(['status' => 'error', 'message' => 'Order tidak ditemukan']);
        }

        $type = $this->request->getPost('type'); // 'customer' atau 'toko'
        $notes = $this->request->getPost('notes');

        if ($type == 'customer') {
            $data = ['catatan_pelanggan' => $notes];
        } elseif ($type == 'toko') {
            $data = ['catatan_toko' => $notes];
        } else {
            return $this->response->setStatusCode(400)->setJSON(['status' => 'error', 'message' => 'Type tidak valid']);
        }

        $this->permintaanCustom->update($id, $data);
        return redirect()->back()->with('success', 'Catatan disimpan');
    }

    /**
     * Update estimasi selesai (hanya kasir)
     */
    public function updateEstimationDate($id)
    {
        if (auth()->user()->role != 'kasir') {
            return $this->response->setStatusCode(403)->setJSON(['status' => 'error', 'message' => 'Unauthorized']);
        }

        $estimasi = $this->request->getPost('estimasi_selesai');
        if (!$estimasi) {
            return $this->response->setStatusCode(400)->setJSON(['status' => 'error', 'message' => 'Tanggal estimasi tidak ditemukan']);
        }

        $this->permintaanCustom->update($id, ['estimasi_selesai' => $estimasi]);
        return $this->response->setJSON(['status' => 'success', 'message' => 'Estimasi tanggal selesai diperbarui']);
    }

    public function pay($id)
    {
        $data['title'] = 'Bayar Model';
        $builder = $this->permintaanCustom->builder();
        $builder->select('tabel_permintaan_custom.*,tabel_customer.nama');
        $builder->join('tabel_customer', 'tabel_customer.id_customer = tabel_permintaan_custom.id_customer', 'inner');
        $builder->where('tabel_permintaan_custom.kode_permintaan_custom', $id);
        $permintaanCustom = $builder->orderBy('tabel_permintaan_custom.created_at', 'desc')->get()->getRow();

        if (!$permintaanCustom) {
            return redirect()->to('/permintaan_custom')->with('error', 'Order tidak ditemukan');
        }

        $data['data'] = $permintaanCustom;

        $builder = $this->detailPermintaan->builder();
        $builder->select('tabel_detail_permintaan.*, tabel_detail_kain.meter_pemakaian, tabel_detail_kain.harga_per_meter, tabel_detail_kain.subtotal_detail_kain, tabel_detail_kain.kode_jenis_kain, tabel_detail_kain.additional_fabrics, tabel_jenis_kain.nama_jenis_kain, tabel_jenis_kain.warna, tabel_jenis_kain.foto_jenis_kain, tabel_model.nama_model, tabel_model.foto_model');
        $builder->join('tabel_detail_kain', 'tabel_detail_kain.id_detail_order = tabel_detail_permintaan.id_detail_order', 'left');
        $builder->join('tabel_jenis_kain', 'tabel_jenis_kain.kode_jenis_kain = tabel_detail_kain.kode_jenis_kain', 'left');
        $builder->join('tabel_model', 'tabel_model.kode_model = tabel_detail_permintaan.kode_model', 'left');
        $builder->where('tabel_detail_permintaan.no_order_custom', $permintaanCustom->no_order_custom);
        $detailResult = $builder->orderBy('tabel_detail_permintaan.created_at', 'desc')->get()->getResult();

        // Debug log
        log_message('debug', 'Pay - Detail Model Count: ' . count($detailResult));
        log_message('debug', 'Pay - Order: ' . $permintaanCustom->no_order_custom);

        $data['detail_model'] = $detailResult;
        $data['riwayatPerubahanModel'] = $this->riwayatPerubahanModel;

        return view('permintaan_custom/pay', $data);
    }

    /**
     * Kasir-only function to edit meter_pemakaian without creating revision history
     */
    public function kasir_edit_meter($id)
    {
        // Only kasir can access
        if (auth()->user()->role != 'kasir') {
            return redirect()->to('/permintaan_custom')->with('error', 'Akses ditolak. Hanya kasir yang dapat mengedit meter pemakaian.');
        }

        if ($this->request->getMethod() == 'POST') {

            $meterPemakaian = $this->request->getPost('meter_pemakaian');
            $idDetailOrder = $this->request->getPost('id_detail_order');
            $hargaPerMeter = $this->request->getPost('harga_per_meter');
            $isCustom = $this->request->getPost('is_custom');
            $ongkosJahitCustom = $this->request->getPost('ongkos_jahit_custom');
            $ongkosPengerjaan = $this->request->getPost('ongkos_pengerjaan');
            $jumlahPcsCustom = $this->request->getPost('jumlah_pcs_custom');

            // Validation: Check if at least id_detail_order exists
            // meter_pemakaian might be empty for custom items (only ongkos_jahit_custom)
            if (!$idDetailOrder) {
                return redirect()->to('/permintaan_custom')->with('error', 'Data tidak lengkap');
            }

            $this->db->transStart();

            // Update each detail kain by id_detail_order
            foreach ($idDetailOrder as $index => $detailOrderId) {
                $isItemCustom = ($isCustom[$index] ?? 0) == 1;

                if ($isItemCustom) {
                    // For custom items (bawa kain + upload model sendiri), update ongkos jahit
                    $ongkos = $ongkosJahitCustom[$index] ?? 0;
                    $pengerjaan = $ongkosPengerjaan[$index] ?? 0;
                    $jumlah = $jumlahPcsCustom[$index] ?? 1;
                    $subtotalOngkos = ($ongkos + $pengerjaan) * $jumlah;

                    // Update tabel_detail_permintaan with ongkos jahit
                    $this->detailPermintaan->update($detailOrderId, [
                        'ongkos_jahit_custom' => $ongkos,
                        'ongkos_pengerjaan' => $pengerjaan,
                        'subtotal_detail_order' => $subtotalOngkos
                    ]);

                    // No need to update detail_kain for custom items
                    continue;
                }

                // For regular items with fabric, update meter pemakaian
                $meter = $meterPemakaian[$index] ?? 0;
                $harga = $hargaPerMeter[$index] ?? 0;
                $subtotal = $meter * $harga;

                // Check if there are additional fabrics for this detail
                $addFabricMeterKey = "additional_fabric_meters_{$detailOrderId}";
                $addFabricCodeKey = "additional_fabric_codes_{$detailOrderId}";
                $addFabricHargaKey = "additional_fabric_hargas_{$detailOrderId}";

                $additionalFabricsData = [];
                if ($this->request->getPost($addFabricMeterKey)) {
                    $addMeters = $this->request->getPost($addFabricMeterKey);
                    $addCodes = $this->request->getPost($addFabricCodeKey);
                    $addHargas = $this->request->getPost($addFabricHargaKey);

                    foreach ($addMeters as $idx => $addMeter) {
                        $additionalFabricsData[] = [
                            'kode_jenis_kain' => $addCodes[$idx] ?? '',
                            'meter_pemakaian' => floatval($addMeter),
                            'harga_per_meter' => floatval($addHargas[$idx] ?? 0)
                        ];
                    }
                }

                // Update tabel_detail_kain where id_detail_order matches
                $updateData = [
                    'meter_pemakaian' => $meter,
                    'subtotal_detail_kain' => $subtotal
                ];

                // Update additional_fabrics JSON if exists
                if (!empty($additionalFabricsData)) {
                    $updateData['additional_fabrics'] = json_encode($additionalFabricsData);
                }

                $this->detailKain->where('id_detail_order', $detailOrderId)->set($updateData)->update();
            }

            // Recalculate total nominal_pelunasan
            $permintaan = $this->permintaanCustom->find($id);
            $builder = $this->detailPermintaan->builder();
            $builder->select('tabel_detail_permintaan.subtotal_detail_order, tabel_detail_permintaan.jumlah_pcs, tabel_detail_permintaan.ongkos_jahit_custom, tabel_detail_permintaan.ongkos_pengerjaan, tabel_detail_kain.subtotal_detail_kain, tabel_detail_kain.additional_fabrics');
            $builder->join('tabel_detail_kain', 'tabel_detail_kain.id_detail_order = tabel_detail_permintaan.id_detail_order', 'left');
            $builder->where('tabel_detail_permintaan.no_order_custom', $permintaan->no_order_custom);
            $details = $builder->get()->getResult();

            $totalNominal = 0;


            foreach ($details as $detail) {
                // Check if this is a custom item (with ongkos jahit)
                if ($detail->ongkos_jahit_custom > 0) {
                    $totalNominal += ($detail->ongkos_jahit_custom + $detail->ongkos_pengerjaan + $detail->subtotal_detail_kain) * $detail->jumlah_pcs;
                } else {
                    // Regular item: ongkos pengerjaan + fabric cost
                    $totalNominal += $detail->subtotal_detail_order + ($detail->subtotal_detail_kain ?? 0);
                }

                // Additional fabrics subtotal
                if (!empty($detail->additional_fabrics)) {
                    $additionalFabrics = json_decode($detail->additional_fabrics, true);
                    if (is_array($additionalFabrics)) {
                        foreach ($additionalFabrics as $addFabric) {
                            $addMeter = $addFabric['meter_pemakaian'] ?? 0;
                            $addHarga = $addFabric['harga_per_meter'] ?? 0;
                            $totalNominal += ($addMeter * $addHarga * $detail->jumlah_pcs);
                        }
                    }
                }
            }

            // Update nominal pelunasan dan sisa pembayaran
            $dpPembayaran = $permintaan->dp_pembayaran ?? 0;

            $updateData = [
                'nominal_pelunasan' => $totalNominal,
                'sisa_pembayaran' => $totalNominal - $dpPembayaran,
                'status_pesanan' => 'menunggu_pembayaran'
            ];

            // Update tanggal pengambilan confirmation if provided
            if ($this->request->getPost('tanggal_pengambilan_konfirmasi')) {
                $updateData['tanggal_pengambilan_konfirmasi'] = $this->formatDatetimeInput($this->request->getPost('tanggal_pengambilan_konfirmasi'));
            }

            $this->permintaanCustom->update($id, $updateData);

            $this->db->transComplete();

            session()->setFlashdata('success', 'Meter pemakaian dan ongkos jahit berhasil diupdate');
            return redirect()->to('/permintaan_custom');
        }

        // GET - Load form
        $data['title'] = 'Edit Meter Pemakaian & Ongkos Jahit';

        $builder = $this->permintaanCustom->builder();
        $builder->select('tabel_permintaan_custom.*, tabel_customer.nama');
        $builder->join('tabel_customer', 'tabel_customer.id_customer = tabel_permintaan_custom.id_customer', 'inner');
        $builder->where('tabel_permintaan_custom.kode_permintaan_custom', $id);
        $permintaanCustom = $builder->get()->getRow();
        $data['data'] = $permintaanCustom;

        $builder = $this->detailPermintaan->builder();
        $builder->select('tabel_detail_permintaan.*, tabel_detail_kain.id_detail_order as kain_id_detail, tabel_detail_kain.meter_pemakaian, tabel_detail_kain.harga_per_meter, tabel_detail_kain.subtotal_detail_kain, tabel_detail_kain.additional_fabrics, tabel_jenis_kain.nama_jenis_kain, tabel_jenis_kain.warna, tabel_jenis_kain.harga_per_meter as jenis_harga_per_meter, tabel_model.nama_model');
        $builder->join('tabel_detail_kain', 'tabel_detail_kain.id_detail_order = tabel_detail_permintaan.id_detail_order', 'left');
        $builder->join('tabel_jenis_kain', 'tabel_jenis_kain.kode_jenis_kain = tabel_detail_kain.kode_jenis_kain', 'left');
        $builder->join('tabel_model', 'tabel_model.kode_model = tabel_detail_permintaan.kode_model', 'left');
        $builder->where('tabel_detail_permintaan.no_order_custom', $permintaanCustom->no_order_custom);
        $data['detail_model'] = $builder->get()->getResult();

        // print_r($data['detail_model']);
        // exit;

        return view('permintaan_custom/kasir_edit_meter', $data);
    }

    /**
     * Customer request perubahan alamat setelah alamat terkunci
     */
    public function request_change_alamat($id)
    {
        if (!$this->request->isAJAX()) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Invalid request'
            ]);
        }

        $role = auth()->user()->role ?? null;

        // Hanya customer yang bisa request
        if ($role != 'customer') {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Hanya customer yang dapat mengajukan perubahan alamat'
            ]);
        }

        $alamat_baru = $this->request->getPost('alamat_baru');

        if (empty($alamat_baru)) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Alamat baru harus diisi'
            ]);
        }

        // Cek apakah alamat terkunci
        if (!$this->permintaanCustom->isAlamatLocked($id)) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Alamat belum terkunci, Anda masih bisa mengubah langsung'
            ]);
        }

        // Simpan request perubahan
        $success = $this->permintaanCustom->requestAlamatChange($id, $alamat_baru);

        if ($success) {
            return $this->response->setJSON([
                'success' => true,
                'message' => 'Permintaan perubahan alamat berhasil diajukan. Menunggu approval admin/kasir.'
            ]);
        } else {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Gagal mengajukan perubahan alamat'
            ]);
        }
    }

    /**
     * Admin/Kasir approve atau reject perubahan alamat
     */
    public function approve_change_alamat($id)
    {
        if (!$this->request->isAJAX()) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Invalid request'
            ]);
        }

        $role = auth()->user()->role ?? null;

        // Hanya admin dan kasir yang bisa approve
        if (!in_array($role, ['admin', 'kasir'])) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Hanya admin/kasir yang dapat menyetujui perubahan alamat'
            ]);
        }

        $approved = $this->request->getPost('approved') == '1';
        $note = $this->request->getPost('note');
        $user_id = auth()->user()->id;

        // Cek apakah ada pending request
        if (!$this->permintaanCustom->hasPendingAlamatChangeRequest($id)) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Tidak ada permintaan perubahan alamat yang pending'
            ]);
        }

        // Approve atau reject
        $success = $this->permintaanCustom->approveAlamatChange($id, $approved, $user_id, $note);

        if ($success) {
            $message = $approved
                ? 'Perubahan alamat telah disetujui dan alamat sudah diperbarui'
                : 'Perubahan alamat telah ditolak';

            return $this->response->setJSON([
                'success' => true,
                'message' => $message
            ]);
        } else {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Gagal memproses perubahan alamat'
            ]);
        }
    }
}
