<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\OrderModel;
use App\Models\CompanySettingModel;
use App\Services\MonthlyPoScheduler;

class Dashboard extends BaseController
{
    public function index()
    {
        $db         = \Config\Database::connect();
        $orderModel = new OrderModel();
        
        // Pengaturan Kapasitas Produksi (Bulan Berjalan)
        $thisMonth  = date('m');
        $thisYear   = date('Y');
        $startMonth = "$thisYear-$thisMonth-01"; 
        $endMonth   = date('Y-m-t', strtotime($startMonth)); 

        $setting = (new CompanySettingModel())->first(); 
        $poLimit = (int) ($setting['monthly_po_limit'] ?? 0);

        // Menghitung Kapasitas PO Terpakai
        $poUsed      = (new MonthlyPoScheduler())->quantityForMonth($startMonth);
        $poRemaining = max(0, $poLimit - $poUsed);
        $poPercent   = ($poLimit > 0) ? round(($poUsed / $poLimit) * 100) : 0;

        // Menggunakan OrderModel untuk efisiensi & arsitektur Thin Controller
        $todaySales   = (float) $orderModel->getTodaySales();
        $paymentSummary = $orderModel->getPaymentSummary();
        $receivable   = (float) $paymentSummary['outstanding_amount'];
        $activeOrders = (int) $orderModel->getActiveOrdersCount();

        // Data Pembayaran (Untuk Chart Doughnut Lifecycle)
        $totalPaid    = (int) $paymentSummary['paid_orders'];
        $totalPartial = (int) $paymentSummary['partial_orders'];
        $totalUnpaid  = (int) $paymentSummary['unpaid_orders'];

        // Data Deadline Terdekat (Maksimal 8 data)
        $deadlines    = $orderModel->getUpcomingDeadlines(8);

        // Lempar data ke View
        $data = [
            'title'         => 'Admin Dashboard',
            'poLimit'       => $poLimit,
            'poUsed'        => $poUsed,
            'poRemaining'   => $poRemaining,
            'poPercent'     => $poPercent,
            'todaySales'    => $todaySales,
            'receivable'    => $receivable,
            'activeOrders'  => $activeOrders,
            'totalUnpaid'   => $totalUnpaid,
            'totalPaid'     => $totalPaid,
            'totalPartial'  => $totalPartial,
            'receivedAmount' => (float) $paymentSummary['received_amount'],
            'settledAmount' => (float) $paymentSummary['settled_amount'],
            'unpaidAmount' => (float) $paymentSummary['unpaid_amount'],
            'partialOutstandingAmount' => (float) $paymentSummary['partial_outstanding_amount'],
            'deadlines'     => $deadlines
        ];

        return view('admin/dashboard', $data);
    }

    /**
     * FUNGSI AJAX: Ambil data event kalender berdasarkan bulan dan tahun
     * 
     * @param int|string $year
     * @param int|string $month
     * @return \CodeIgniter\HTTP\ResponseInterface
     */
    public function getEvents($year, $month) 
    { 
        $db    = \Config\Database::connect(); 
        $year  = (int) $year;
        $month = (int) $month;

        $startMonth = sprintf('%04d-%02d-01', $year, $month);

        if ($db->tableExists('order_production_schedules')) {
            $events = $db->table('order_production_schedules ops')
                ->select('ops.id_order, o.order_number, ops.scheduled_month AS target_date, o.customer_name, SUM(ops.quantity) AS total_qty')
                ->join('orders o', 'o.id_order = ops.id_order')
                ->where('ops.scheduled_month', $startMonth)
                ->where('o.order_status !=', 'cancelled')
                ->groupBy(['ops.id_order', 'ops.scheduled_month'])
                ->get()->getResultArray();
        } else {
            $events = $db->table('orders o')
                ->select('o.id_order, o.order_number, o.target_date, o.customer_name, SUM(oi.qty) as total_qty')
                ->join('order_items oi', 'oi.id_order = o.id_order', 'left')
                ->where('YEAR(o.target_date)', $year)
                ->where('MONTH(o.target_date)', $month)
                ->where('o.order_status !=', 'cancelled')
                ->groupBy('o.id_order')
                ->get()->getResultArray();
        }
            
        return $this->response->setJSON($events); 
    }
}
