<?php

namespace App\Controllers;

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

class RiwayatController extends BaseController
{
    protected $riwayatPerubahan;
    protected $revisiModel;
    protected $detailPermintaan;
    protected $permintaanCustom;

    public function __construct()
    {
        $this->riwayatPerubahan = new RiwayatPerubahanModel();
        $this->revisiModel = new RevisiModel();
        $this->detailPermintaan = new DetailPermintaanModel();
        $this->permintaanCustom = new PermintaanCustomModel();
    }

    protected function formatDatetimeInput($input)
    {
        if (!$input) return null;
        $normalized = str_replace('T', ' ', $input);
        if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $normalized)) {
            $normalized .= ':00';
        }
        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $normalized)) {
            $normalized .= ' 00:00:00';
        }
        $ts = strtotime($normalized);
        if ($ts === false) return null;
        return date('Y-m-d H:i:s', $ts);
    }

    /**
     * Menampilkan riwayat pesanan dan revisi
     * Jika customer: hanya riwayat mereka
     * Jika admin/kasir: semua riwayat dengan filter nama customer
     */
    public function index()
    {
        $data['title'] = 'Riwayat Pesanan';
        $builder = $this->revisiModel->builder();
        $builder->select('tabel_revisi.*');

        if (auth()->user()->role == 'customer') {
            $builder->where('tabel_revisi.user_id', auth()->user()->user_id);
        }

        $data['data'] = $builder->orderBy('tabel_revisi.created_at', 'desc')->get()->getResult();
        return view('riwayat/index', $data);
    }

    /**
     * Show detail revisi
     */
    public function detail($id_revisi)
    {
        $data['title'] = 'Detail Riwayat Pesanan';

        $builder = $this->revisiModel->builder();
        $builder->select('tabel_revisi.*, tabel_customer.nama as customer_name, tabel_permintaan_custom.nominal_pelunasan');
        $builder->join('tabel_permintaan_custom', 'tabel_permintaan_custom.no_order_custom = tabel_revisi.no_order_custom', 'inner');
        $builder->join('tabel_customer', 'tabel_customer.id_customer = tabel_permintaan_custom.id_customer', 'inner');
        $builder->where('tabel_revisi.id_revisi', $id_revisi);

        $data['revisi'] = $builder->get()->getRow();

        if (!$data['revisi']) {
            return redirect()->back()->with('error', 'Data revisi tidak ditemukan');
        }

        // Decode JSON perubahan_data
        if ($data['revisi']->perubahan_data) {
            $data['perubahan'] = json_decode($data['revisi']->perubahan_data);
        } else {
            $data['perubahan'] = null;
        }

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

    /**
     * Create revision request dari customer atau kasir
     */
    public function createRevision($id_detail_order)
    {
        if ($this->request->getMethod() == 'POST') {
            $tipe_revisi = $this->request->getPost('tipe_revisi');
            $keterangan = $this->request->getPost('keterangan_permintaan_revisi');

            if (!$tipe_revisi || !$keterangan) {
                return redirect()->back()->with('error', 'Tipe revisi dan keterangan harus diisi');
            }

            $data = [
                'id_detail_order' => $id_detail_order,
                'tanggal_permintaan_revisi' => date('Y-m-d H:i:s'),
                'keterangan_permintaan_revisi' => $keterangan,
                'tipe_revisi' => $tipe_revisi,
                'status' => 0,
                'biaya_revisi' => $this->request->getPost('biaya_revisi') ?? 0
            ];

            $this->riwayatPerubahan->insert($data);
            session()->setFlashdata('success', 'Permintaan revisi berhasil dibuat');
            return redirect()->back();
        }

        $data['title'] = 'Buat Permintaan Revisi';
        $data['detail'] = $this->detailPermintaan->find($id_detail_order);
        return view('riwayat/create_revision', $data);
    }

    /**
     * Approve revision dan optionally add additional cost
     */
    public function approveRevision($id)
    {
        if (auth()->user()->role != 'admin') {
            return redirect()->back()->with('error', 'Hanya admin yang bisa approve revisi');
        }

        $biaya_tambahan = (float) $this->request->getPost('biaya_revisi') ?? 0;

        $dataUpdate = [
            'status' => 1,
            'tgl_diterima_pegawai' => date('Y-m-d H:i:s'),
            'biaya_revisi' => $biaya_tambahan
        ];

        $revision = $this->riwayatPerubahan->find($id);
        if (!$revision) {
            return redirect()->back()->with('error', 'Revisi tidak ditemukan');
        }

        $this->riwayatPerubahan->update($id, $dataUpdate);

        // Jika ada biaya tambahan, update nominal pesanan
        if ($biaya_tambahan > 0) {
            $detail = $this->detailPermintaan->find($revision->id_detail_order);
            $order = $this->permintaanCustom->where('no_order_custom', $detail->no_order_custom)->first();

            $newNominal = $order->nominal_pelunasan + $biaya_tambahan;
            $this->permintaanCustom->update($order->kode_permintaan_custom, ['nominal_pelunasan' => $newNominal]);
        }

        session()->setFlashdata('success', 'Revisi disetujui dan disimpan ke riwayat');
        return redirect()->back();
    }

    /**
     * Reject revision
     */
    public function rejectRevision($id)
    {
        if (auth()->user()->role != 'admin') {
            return redirect()->back()->with('error', 'Hanya admin yang bisa reject revisi');
        }

        $this->riwayatPerubahan->delete($id);
        session()->setFlashdata('success', 'Permintaan revisi ditolak dan dihapus');
        return redirect()->back();
    }

    /**
     * Delete revision (legacy)
     */
    public function delete($id)
    {
        $this->riwayatPerubahan->delete($id);
        return redirect()->to('/riwayat_perubahan')->with('success', 'Riwayat Revisi Berhasil Dihapus.');
    }

    /**
     * Confirm revision (legacy - untuk backward compatibility)
     */
    public function confirm_revision($id = null)
    {
        $dataRiwayat = [
            'status' => 1,
            'tgl_diterima_pegawai' => date('Y-m-d H:i:s')
        ];

        $this->riwayatPerubahan->update($id, $dataRiwayat);
        session()->setFlashdata('success', 'Konfirmasi Revisi Permintaan berhasil');
        return redirect()->to('/riwayat_perubahan');
    }

    /**
     * Get revision statistics for report
     */
    public function getRevisionStats()
    {
        $start_date = $this->request->getGet('start_date');
        $end_date = $this->request->getGet('end_date');

        if (!$start_date || !$end_date) {
            return $this->response->setStatusCode(400)->setJSON(['error' => 'Tanggal awal dan akhir diperlukan']);
        }

        $builder = $this->riwayatPerubahan->builder();
        $builder->select('tipe_revisi, COUNT(*) as total, SUM(biaya_revisi) as total_cost');
        $start_norm = $this->formatDatetimeInput($start_date) ?? $start_date;
        $end_norm = $this->formatDatetimeInput($end_date) ?? $end_date;
        $builder->where('created_at >=', $start_norm);
        $builder->where('created_at <=', $end_norm);
        $builder->groupBy('tipe_revisi');

        $stats = $builder->get()->getResult();

        return $this->response->setJSON([
            'success' => true,
            'period' => "$start_date to $end_date",
            'stats' => $stats
        ]);
    }
}
