<?php

namespace App\Controllers;

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

class LaporanController extends BaseController
{
    protected $laporan;
    protected $permintaanCustom;
    protected $riwayatPerubahan;
    protected $detailPermintaan;
    protected $detailKain;
    protected $db;

    public function __construct()
    {
        $this->laporan = new LaporanModel();
        $this->permintaanCustom = new PermintaanCustomModel();
        $this->riwayatPerubahan = new RiwayatPerubahanModel();
        $this->detailPermintaan = new DetailPermintaanModel();
        $this->detailKain = new DetailKainModel();
        $this->db = \Config\Database::connect();
    }

    /**
     * Normalize datetime-local input from forms to MySQL DATETIME string
     */
    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);
    }

    /**
     * Halaman laporan - hanya tampil form filter, no CRUD buttons
     */
    public function index()
    {
        $data['title'] = 'Laporan Pemesanan';

        // Get quick stats
        $data['stats'] = [
            'total_orders' => $this->permintaanCustom->countAll(),
            'total_revenue' => $this->permintaanCustom->selectSum('nominal_pelunasan')->first()->nominal_pelunasan ?? 0,
            'paid_full' => $this->permintaanCustom->where('sisa_pembayaran', 0)->countAllResults(),
            'pending_payment' => $this->permintaanCustom->where('sisa_pembayaran >', 0)->countAllResults(),
        ];

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

    /**
     * Generate laporan berdasarkan periode filter
     * Tidak menyimpan ke database, hanya filter real-time
     */
    public function generateReport()
    {
        if ($this->request->getMethod() == 'GET') {
            $tanggal = $this->request->getGet('tanggal');

            if (!$tanggal) {
                return redirect()->back()->with('error', 'Tanggal harus diisi');
            }

            // Normalize tanggal input
            $tanggal_norm = $this->formatDatetimeInput($tanggal) ?? $tanggal;

            // Set start and end of day for the selected date
            $tanggal_awal = date('Y-m-d 00:00:00', strtotime($tanggal_norm));
            $tanggal_akhir = date('Y-m-d 23:59:59', strtotime($tanggal_norm));

            // Query data untuk tanggal tersebut
            $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.tanggal_order >=', $tanggal_awal);
            $builder->where('tabel_permintaan_custom.tanggal_order <=', $tanggal_akhir);
            $items = $builder->orderBy('tabel_permintaan_custom.tanggal_order', 'asc')->get()->getResult();

            // Calculate summary
            $summary = [
                'total_orders' => count($items),
                'total_dp_collected' => 0,
                'total_full_payment' => 0,
                'total_revenue' => 0,
                'remaining_payment' => 0,
            ];

            foreach ($items as $item) {
                $summary['total_revenue'] += $item->nominal_pelunasan;
                $summary['total_dp_collected'] += $item->dp_pembayaran;
                if ($item->sisa_pembayaran == 0) {
                    $summary['total_full_payment'] += $item->nominal_pelunasan;
                }
                $summary['remaining_payment'] += $item->sisa_pembayaran;
            }

            $data['items'] = $items;
            $data['summary'] = $summary;
            $data['tanggal'] = $tanggal;
            $data['title'] = 'Laporan Pemesanan';

            return view('laporan/report_view', $data);
        }
    }

    /**
     * Export laporan ke PDF dengan summary di bawah
     */
    public function exportPDF()
    {
        $tanggal = $this->request->getGet('tanggal');

        if (!$tanggal) {
            return redirect()->back()->with('error', 'Tanggal harus diisi');
        }

        // Query data
        $tanggal_norm = $this->formatDatetimeInput($tanggal) ?? $tanggal;

        // Set start and end of day for the selected date
        $tanggal_awal = date('Y-m-d 00:00:00', strtotime($tanggal_norm));
        $tanggal_akhir = date('Y-m-d 23:59:59', strtotime($tanggal_norm));

        $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.tanggal_order >=', $tanggal_awal);
        $builder->where('tabel_permintaan_custom.tanggal_order <=', $tanggal_akhir);
        $items = $builder->orderBy('tabel_permintaan_custom.tanggal_order', 'asc')->get()->getResult();

        // Calculate summary
        $summary = [
            'total_orders' => count($items),
            'total_dp_collected' => 0,
            'total_full_payment' => 0,
            'total_revenue' => 0,
            'remaining_payment' => 0,
        ];

        foreach ($items as $item) {
            $summary['total_revenue'] += $item->nominal_pelunasan;
            $summary['total_dp_collected'] += $item->dp_pembayaran;
            if ($item->sisa_pembayaran == 0) {
                $summary['total_full_payment'] += $item->nominal_pelunasan;
            }
            $summary['remaining_payment'] += $item->sisa_pembayaran;
        }

        // Get detail items untuk setiap order
        foreach ($items as $item) {
            // Get customer full info
            $customerBuilder = $this->db->table('tabel_customer');
            $customerBuilder->select('nama, telepon, alamat');
            $customerBuilder->where('id_customer', $item->id_customer);
            $item->customer_info = $customerBuilder->get()->getRow();

            // Get order details
            $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', 'left');
            $builder->join('tabel_model', 'tabel_model.kode_model = tabel_detail_permintaan.kode_model', 'inner');
            $builder->where('tabel_detail_permintaan.no_order_custom', $item->no_order_custom);
            $item->detail_items = $builder->get()->getResult();

            // Enrich additional_fabrics with full fabric info
            foreach ($item->detail_items as $detail) {
                if (!empty($detail->additional_fabrics)) {
                    $additionalFabrics = json_decode($detail->additional_fabrics, true);
                    if (is_array($additionalFabrics)) {
                        $enrichedFabrics = [];
                        foreach ($additionalFabrics as $fabric) {
                            $kodeKain = $fabric['kode_jenis_kain'] ?? $fabric['kode'] ?? '';
                            if (!empty($kodeKain)) {
                                // Get fabric details from database
                                $fabricInfo = $this->db->table('tabel_jenis_kain')
                                    ->where('kode_jenis_kain', $kodeKain)
                                    ->get()
                                    ->getRow();

                                if ($fabricInfo) {
                                    $enrichedFabrics[] = [
                                        'kode_jenis_kain' => $kodeKain,
                                        'nama_jenis_kain' => $fabricInfo->nama_jenis_kain,
                                        'warna' => $fabricInfo->warna,
                                        'foto_jenis_kain' => $fabricInfo->foto_jenis_kain,
                                        'meter_pemakaian' => $fabric['meter_pemakaian'] ?? $fabric['meter'] ?? 0,
                                        'harga_per_meter' => $fabric['harga_per_meter'] ?? $fabricInfo->harga_per_meter
                                    ];
                                }
                            }
                        }
                        $detail->additional_fabrics_enriched = $enrichedFabrics;
                    }
                }
            }
        }

        // Generate HTML untuk PDF
        $html = view('laporan/report_pdf', [
            'items' => $items,
            'summary' => $summary,
            'tanggal' => $tanggal,
        ]);

        // Setup Dompdf
        $options = new Options();
        $options->set('isRemoteEnabled', true);
        $dompdf = new Dompdf($options);

        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        // Output PDF
        return $dompdf->stream("Laporan-{$tanggal}.pdf", ["Attachment" => false]);
    }

    /**
     * Legacy methods - disabled dalam revisi (create, edit, delete dihapus)
     * Tapi disimpan untuk backward compatibility
     */

    public function create()
    {
        return redirect()->to('/laporan')->with('warning', 'Fitur tambah laporan tidak lagi tersedia. Gunakan form filter di halaman laporan.');
    }

    public function edit($id)
    {
        return redirect()->to('/laporan')->with('warning', 'Fitur edit laporan tidak lagi tersedia.');
    }

    public function delete($id)
    {
        return redirect()->to('/laporan')->with('warning', 'Fitur hapus laporan tidak lagi tersedia.');
    }

    /**
     * Laporan berdasarkan payment method
     */
    public function reportByPaymentMethod()
    {
        $periode_awal = $this->request->getGet('periode_awal');
        $periode_akhir = $this->request->getGet('periode_akhir');

        if (!$periode_awal || !$periode_akhir) {
            return $this->response->setStatusCode(400)->setJSON(['error' => 'Periode diperlukan']);
        }

        $builder = $this->permintaanCustom->builder();
        $builder->select('metode_pembayaran, COUNT(*) as total, SUM(nominal_pelunasan) as revenue');
        $builder->where("DATE(tanggal_order) >=", $periode_awal);
        $builder->where("DATE(tanggal_order) <=", $periode_akhir);
        $builder->groupBy('metode_pembayaran');

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

        return $this->response->setJSON([
            'success' => true,
            'periode' => "$periode_awal to $periode_akhir",
            'breakdown' => $data
        ]);
    }

    /**
     * Laporan berdasarkan status konfirmasi admin/kasir
     */
    public function reportByConfirmationStatus()
    {
        $periode_awal = $this->request->getGet('periode_awal');
        $periode_akhir = $this->request->getGet('periode_akhir');

        if (!$periode_awal || !$periode_akhir) {
            return $this->response->setStatusCode(400)->setJSON(['error' => 'Periode diperlukan']);
        }

        $builder = $this->permintaanCustom->builder();
        $builder->select('status_admin_konfirmasi, status_kasir_konfirmasi, COUNT(*) as total');
        $builder->where("DATE(tanggal_order) >=", $periode_awal);
        $builder->where("DATE(tanggal_order) <=", $periode_akhir);
        $builder->groupBy('status_admin_konfirmasi, status_kasir_konfirmasi');

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

        return $this->response->setJSON([
            'success' => true,
            'periode' => "$periode_awal to $periode_akhir",
            'stats' => $data
        ]);
    }

    /**
     * Laporan statistik revisi
     */
    public function reportByRevisionStats()
    {
        $periode_awal = $this->request->getGet('periode_awal');
        $periode_akhir = $this->request->getGet('periode_akhir');

        if (!$periode_awal || !$periode_akhir) {
            return $this->response->setStatusCode(400)->setJSON(['error' => 'Periode diperlukan']);
        }

        $builder = $this->riwayatPerubahan->builder();
        $builder->select('tipe_revisi, COUNT(*) as total, SUM(biaya_revisi) as total_cost');
        $builder->where("DATE(created_at) >=", $periode_awal);
        $builder->where("DATE(created_at) <=", $periode_akhir);
        $builder->groupBy('tipe_revisi');

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

        return $this->response->setJSON([
            'success' => true,
            'periode' => "$periode_awal to $periode_akhir",
            'revision_stats' => $stats
        ]);
    }
}
