<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\DetailKainModel;
use App\Models\DetailPermintaanModel;
use App\Models\PermintaanCustomModel;
use App\Models\RiwayatPerubahanModel;
use CodeIgniter\HTTP\ResponseInterface;

class PermintaanPerubahanController extends BaseController
{
    protected $permintaanCustom;
    protected $detailKain;
    protected $detailPermintaan;
    protected $riwayatPerubahanModel;

    public function __construct()
    {
        $this->permintaanCustom = new PermintaanCustomModel();
        $this->riwayatPerubahanModel = new RiwayatPerubahanModel();
        $this->detailKain = new DetailKainModel();
        $this->detailPermintaan = new DetailPermintaanModel();
    }

    public function index()
    {
        $data['title'] = 'Revisi Permintaan';
        $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);
        endif;
        $data['data'] = $builder->orderBy('tabel_permintaan_custom.created_at', 'desc')->get()->getResult();

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

    public function create($id = null)
    {
        if ($this->request->getMethod() == 'POST') {
            $id_detail_order = $this->request->getPost('id_detail_order');
            $revisi = $this->request->getPost('keterangan_revisi');
            $kode_model_selected = $this->request->getPost('kode_model_selected');
            $kode_jenis_kain_selected = $this->request->getPost('kode_jenis_kain_selected');
            $subtotal_model_new = $this->request->getPost('subtotal_model_new');
            $subtotal_kain_new = $this->request->getPost('subtotal_kain_new');

            $totalOrderBaru = 0;
            $noOrderCustom = null;

            foreach ($id_detail_order as $index => $id) {
                $keterangan_revisi = trim($revisi[$index] ?? '');

                // Get current detail
                $currentDetail = $this->detailPermintaan->find($id);
                if (!$currentDetail) continue;

                if (!$noOrderCustom) {
                    $noOrderCustom = $currentDetail['no_order_custom'];
                }

                $hasModelChange = false;
                $hasKainChange = false;
                $newSubtotalModel = $currentDetail['subtotal_detail_order'];
                $newSubtotalKain = 0;

                // Check if model changed
                if (!empty($kode_model_selected[$index]) && $kode_model_selected[$index] != $currentDetail['kode_model']) {
                    $hasModelChange = true;
                    if (!empty($subtotal_model_new[$index])) {
                        $newSubtotalModel = floatval($subtotal_model_new[$index]);
                    }
                    // Update detail permintaan
                    $this->detailPermintaan->update($id, [
                        'kode_model' => $kode_model_selected[$index],
                        'subtotal_detail_order' => $newSubtotalModel
                    ]);
                } elseif (!empty($subtotal_model_new[$index])) {
                    // Model same but price changed
                    $newSubtotalModel = floatval($subtotal_model_new[$index]);
                    $this->detailPermintaan->update($id, [
                        'subtotal_detail_order' => $newSubtotalModel
                    ]);
                }

                // Get current kain detail
                $currentKain = $this->detailKain->where('id_detail_order', $id)->first();
                if ($currentKain) {
                    $newSubtotalKain = $currentKain['subtotal_detail_kain'];

                    // Check if kain changed
                    if (!empty($kode_jenis_kain_selected[$index]) && $kode_jenis_kain_selected[$index] != $currentKain['kode_jenis_kain']) {
                        $hasKainChange = true;
                        if (!empty($subtotal_kain_new[$index])) {
                            $newSubtotalKain = floatval($subtotal_kain_new[$index]);
                        }
                        // Update detail kain
                        $this->detailKain->where('id_detail_order', $id)->set([
                            'kode_jenis_kain' => $kode_jenis_kain_selected[$index],
                            'subtotal_detail_kain' => $newSubtotalKain
                        ])->update();
                    } elseif (!empty($subtotal_kain_new[$index])) {
                        // Kain same but price changed
                        $newSubtotalKain = floatval($subtotal_kain_new[$index]);
                        $this->detailKain->where('id_detail_order', $id)->set([
                            'subtotal_detail_kain' => $newSubtotalKain
                        ])->update();
                    }
                }

                $totalOrderBaru += ($newSubtotalModel + $newSubtotalKain);

                // Insert riwayat only if there's keterangan or changes
                if (!empty($keterangan_revisi) || $hasModelChange || $hasKainChange) {
                    $revisiText = $keterangan_revisi;
                    if ($hasModelChange) {
                        $revisiText .= ($revisiText ? ' | ' : '') . 'Model diganti. Harga baru: Rp ' . number_format($newSubtotalModel, 0, ',', '.');
                    }
                    if ($hasKainChange) {
                        $revisiText .= ($revisiText ? ' | ' : '') . 'Kain diganti. Harga baru: Rp ' . number_format($newSubtotalKain, 0, ',', '.');
                    }

                    $dataRiwayat = [
                        'id_detail_order' => $id,
                        'keterangan_permintaan_revisi' => $revisiText,
                        'tanggal_permintaan_revisi' => date('Y-m-d H:i:s'),
                        'status' => auth()->user()->role != 'customer' ? 1 : 0,
                    ];

                    $this->riwayatPerubahanModel->insert($dataRiwayat);
                }
            }

            // Update total order di permintaan_custom
            if ($noOrderCustom && $totalOrderBaru > 0) {
                $permintaan = $this->permintaanCustom->where('no_order_custom', $noOrderCustom)->first();
                if ($permintaan) {
                    $dpPembayaran = floatval($permintaan['dp_pembayaran']);
                    $nominalPelunasan = floatval($permintaan['nominal_pelunasan']);
                    $totalDibayar = $dpPembayaran + $nominalPelunasan;
                    $sisaPembayaran = $totalOrderBaru - $totalDibayar;

                    // Determine status_pelunasan
                    $statusPelunasan = 0; // Belum bayar
                    if ($totalDibayar >= $totalOrderBaru) {
                        $statusPelunasan = 2; // Lunas
                        $sisaPembayaran = 0;
                    } elseif ($dpPembayaran > 0) {
                        $statusPelunasan = 1; // DP
                    }

                    $this->permintaanCustom->update($permintaan['kode_permintaan_custom'], [
                        'total_order' => $totalOrderBaru,
                        'sisa_pembayaran' => $sisaPembayaran,
                        'status_pelunasan' => $statusPelunasan
                    ]);
                }
            }

            session()->setFlashdata('success', 'Revisi berhasil disimpan. Total order dan status pembayaran telah diperbarui.');
            return redirect()->to('/permintaan_perubahan');
        }

        $data['title'] = 'Tambah Revisi Permintaan';
        $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();
        $data['data'] = $permintaanCustom;

        $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_model.nama_model,tabel_model.foto_model');
        $builder->join('tabel_detail_kain', 'tabel_detail_kain.id_detail_order = tabel_detail_permintaan.id_detail_order', 'inner');
        $builder->join('tabel_jenis_kain', 'tabel_jenis_kain.kode_jenis_kain = tabel_detail_kain.kode_jenis_kain', 'inner');
        $builder->join('tabel_model', 'tabel_model.kode_model = tabel_detail_permintaan.kode_model', 'inner');
        $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_perubahan/create', $data);
    }
}
