<?php

namespace App\Controllers\Owner;

use App\Controllers\BaseController;
use App\Models\CustomerModel;
use App\Models\OrderModel;
use App\Models\ProductModel;
use App\Models\ProductionQueueModel;
use App\Models\ProfitTargetModel;

class Dashboard extends BaseController
{
    protected $db;

    public function __construct()
    {
        $this->db = \Config\Database::connect();
    }

    public function index()
    {
        $start = date('Y-m-01');
        $end = date('Y-m-t');
        $paymentSummary = (new OrderModel())->getPaymentSummary();

        // 1. Ambil Data Finansial & Statistik
        $fin = $this->getFinancialData($start, $end, $paymentSummary);
        $stats = $this->getOperationalStats($start, $end);

        // 2. Gabungkan data untuk View
        return view('owner/dashboard/index', [
            'title'        => 'Pusat Kendali & Analisis Keuangan',
            'periodLabel'  => date('F Y'),
            
            // Data Keuangan
            'omzet'        => $fin['omzet'],
            'material'     => $fin['beban_material'],
            'payroll'      => $fin['beban_payroll'],
            'adminExpense' => $fin['admin_expense'],
            'beban'        => $fin['beban_total'],
            'laba'         => $fin['laba_bersih'],
            'piutang'      => $fin['piutang'],
            'cashMasuk'    => $fin['cash_masuk'],
            'cashKeluar'   => $fin['cash_keluar'],
            'targetProfit' => $fin['target_profit'],

            // Ringkasan pembayaran dari semua order yang dibuat admin
            'paidOrders'               => $paymentSummary['paid_orders'],
            'partialOrders'            => $paymentSummary['partial_orders'],
            'unpaidOrders'             => $paymentSummary['unpaid_orders'],
            'receivedAmount'           => $paymentSummary['received_amount'],
            'settledAmount'            => $paymentSummary['settled_amount'],
            'unpaidAmount'             => $paymentSummary['unpaid_amount'],
            'partialOutstandingAmount' => $paymentSummary['partial_outstanding_amount'],
            'outstandingAmount'        => $paymentSummary['outstanding_amount'],

            // Data Statistik
            'totalOrder'    => $stats['total_order'],
            'totalCustomer' => $stats['total_customer'],
            'totalProduct'  => $stats['total_product'],
            'queue'         => $stats['queue_count'],

            // Data untuk Chart JS
            'chartData'    => json_encode([
                'omzet' => $fin['omzet'],
                'beban' => $fin['beban_total'],
                'laba'  => $fin['laba_bersih']
            ])
        ]);
    }

    /**
     * Helper untuk menghitung total dari database
     */
    private function sum($table, $field, $where = [])
    {
        return (float) ($this->db->table($table)->selectSum($field)->where($where)->get()->getRowArray()[$field] ?? 0);
    }

  private function getFinancialData($start, $end, array $paymentSummary)
    {
        // 1. Omzet: seluruh dana yang benar-benar sudah diterima, termasuk DP/cicilan.
        $omzet = $this->sum('orders', 'paid_amount', [
            'DATE(created_at) >=' => $start, 
            'DATE(created_at) <=' => $end, 
            'order_status !=' => 'cancelled'
        ]);

        // 2. Beban Material
        $bebanMaterial = $this->sum('purchases', 'total_biaya', [
            'tanggal_beli >=' => $start, 
            'tanggal_beli <=' => $end
        ]);

        // 3. Beban Admin
        $adminExpense = $this->sum('expenses', 'jumlah', [
            'tanggal_expense >=' => $start, 
            'tanggal_expense <=' => $end
        ]);

        // 4. Beban Payroll (Dengan perbaikan metode Query Builder)
        $payrollResult = $this->db->table('payrolls')
            ->selectSum('total_gaji')
            // Logika: (periode >= start AND periode <= end) OR (created_at >= start AND created_at <= end)
            ->groupStart()
                ->where('periode >=', $start)
                ->where('periode <=', $end)
            ->groupEnd()
            ->orGroupStart()
                ->where('created_at >=', $start . ' 00:00:00')
                ->where('created_at <=', $end . ' 23:59:59')
            ->groupEnd()
            ->get()
            ->getRowArray();
        
        $bebanPayroll = (float) ($payrollResult['total_gaji'] ?? 0);

        // 5. Cashflow
        $cashMasuk  = $this->sum('cashflows', 'jumlah', ['tanggal >=' => $start, 'tanggal <=' => $end, 'jenis' => 'Masuk']);
        $cashKeluar = $this->sum('cashflows', 'jumlah', ['tanggal >=' => $start, 'tanggal <=' => $end, 'jenis' => 'Keluar']);

        // 6. Lain-lain
        $piutang      = (float) $paymentSummary['outstanding_amount'];
        $targetProfit = (float) ((new ProfitTargetModel())->orderBy('id_target', 'DESC')->first()['target_nominal'] ?? 0);

        return [
            'omzet'         => $omzet,
            'beban_material'=> $bebanMaterial,
            'beban_payroll' => $bebanPayroll,
            'admin_expense' => $adminExpense,
            'beban_total'   => $bebanMaterial + $bebanPayroll + $adminExpense,
            'laba_bersih'   => $omzet - ($bebanMaterial + $bebanPayroll + $adminExpense),
            'piutang'       => $piutang,
            'cash_masuk'    => $cashMasuk,
            'cash_keluar'   => $cashKeluar,
            'target_profit' => $targetProfit
        ];
    }

    private function getOperationalStats($start, $end)
    {
        return [
            'total_order'    => (new OrderModel())->where('DATE(created_at) >=', $start)->where('DATE(created_at) <=', $end)->countAllResults(),
            'total_customer' => (new CustomerModel())->countAll(),
            'total_product'  => (new ProductModel())->where('status', 'active')->countAllResults(),
            // Batch bulan berikutnya tidak dihitung sebagai beban operasional
            // bulan berjalan pada dashboard owner.
            'queue_count'    => (new ProductionQueueModel())
                ->whereIn('status', ['antrian', 'produksi'])
                ->where('tanggal_produksi >=', $start)
                ->where('tanggal_produksi <=', $end)
                ->countAllResults(),
        ];
    }
}
