<?php

    namespace App\Controllers\Owner;

    use App\Controllers\BaseController;
    use App\Models\CashflowModel;
    use App\Models\LedgerModel;
    use App\Models\ReceivableModel;
    use App\Models\PurchaseModel;
    use App\Models\OrderModel;
    use App\Models\PayrollModel;
    use App\Models\ProfitTargetModel;

    class Finance extends BaseController
    {
        protected $cashflow;
        protected $ledger;
        protected $receivable;
        protected $purchase;
        protected $order;
        protected $payroll;
        protected $target;

        public function __construct()
        {
            helper(['form', 'url']);

            $this->cashflow   = new CashflowModel();
            $this->ledger     = new LedgerModel();
            $this->receivable = new ReceivableModel();
            $this->purchase   = new PurchaseModel();
            $this->order      = new OrderModel();

            if(class_exists(\App\Models\PayrollModel::class)){
                $this->payroll = new PayrollModel();
            }

            if(class_exists(\App\Models\ProfitTargetModel::class)){
                $this->target = new ProfitTargetModel();
            }
        }

        public function index()
        {
            $db = \Config\Database::connect();
            $cashMasuk = $this->cashflow
                ->selectSum('jumlah')
                ->where('jenis', 'Masuk')
                ->first();

            $cashKeluar = $this->cashflow
                ->selectSum('jumlah')
                ->where('jenis', 'Keluar')
                ->first();

            // Diperbaiki: dari grand_total ke total
            $omzet = $this->order
                ->selectSum('paid_amount')
                ->first();

            $material = $this->purchase
                ->selectSum('total_biaya')
                ->first();

            // Piutang berasal langsung dari order admin agar selalu sinkron.
            $piutang = $this->order
                ->selectSum('remaining_amount')
                ->where('payment_status !=', 'paid')
                ->where('order_status !=', 'cancelled')
                ->first();

            $payroll = 0;
            if($this->payroll && $db->tableExists('payrolls')){
                $gaji = $this->payroll
                    ->selectSum('total_gaji')
                    ->first();
                $payroll = $gaji['total_gaji'] ?? 0;
            }

            $target = 0;
            if($this->target){
                $profit = $this->target
                    ->orderBy('id_target', 'DESC')
                    ->first();
                if($profit){
                    $target = $profit['target_nominal'];
                }
            }

            // Diperbaiki: akses array key 'total'
            $omzetValue = $omzet['total'] ?? 0;
            $materialValue = $material['total_biaya'] ?? 0;
            $cashIn = $cashMasuk['jumlah'] ?? 0;
            $cashOut = $cashKeluar['jumlah'] ?? 0;
            $piutangValue = $piutang['sisa_piutang'] ?? 0;

            $laba = $omzetValue - $materialValue - $payroll;

            return view('owner/finance/index', [
                'title'        => 'Finance',
                'cashMasuk'    => $cashIn,
                'cashKeluar'   => $cashOut,
                'omzet'        => $omzetValue,
                'material'     => $materialValue,
                'payroll'      => $payroll,
                'piutang'      => $piutangValue,
                'laba'         => $laba,
                'targetProfit' => $target
            ]);
        }

        public function ledger()
        {
            $ledger = $this->ledger->orderBy('tanggal', 'DESC')->findAll();
            return view('owner/finance/ledger', ['title' => 'General Ledger', 'ledger' => $ledger]);
        }

        public function cashflow()
        {
            $cashflows = $this->cashflow->orderBy('tanggal', 'DESC')->findAll();
            return view('owner/finance/cashflow', ['title' => 'Cash Flow', 'cashflows' => $cashflows]);
        }

        public function receivable()
        {
            $receivables = $this->order->where('payment_status !=', 'paid')->where('order_status !=', 'cancelled')->orderBy('created_at', 'DESC')->findAll();
            return view('owner/finance/receivable', ['title' => 'Piutang', 'receivables' => $receivables]);
        }

        public function profit()
        {
            // Diperbaiki: dari grand_total ke total
            $omzet = $this->order->selectSum('total')->first();
            $material = $this->purchase->selectSum('total_biaya')->first();
            $payroll = 0;

            if($this->payroll){
                $gaji = $this->payroll->selectSum('total_gaji')->first();
                $payroll = $gaji['total_gaji'] ?? 0;
            }

            // Diperbaiki: akses array key 'total'
            $profit = ($omzet['total'] ?? 0) - ($material['total_biaya'] ?? 0) - $payroll;

            return view('owner/finance/profit', [
                'title'  => 'Laba Bersih',
                'profit' => $profit
            ]);
        }
    }
