<?php

namespace App\Controllers\API;

use App\Controllers\BaseController;

class ReportController extends BaseController
{
    protected $db;

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

    public function index()
    {
        $start = $this->request->getGet('start');
        $end   = $this->request->getGet('end');

        $builder = $this->db->table('orders o')
            ->select("
                o.id,
                o.invoice_code,
                o.total_price,
                o.order_date,
                c.name as customer_name,

                (
                    SELECT status 
                    FROM order_tracking 
                    WHERE order_tracking.order_id = o.id
                    ORDER BY id DESC 
                    LIMIT 1
                ) as last_status
            ")
            ->join('customers c', 'c.id = o.customer_id');

        // 📅 FILTER TANGGAL
        if ($start && $end) {
            $builder->where('DATE(o.order_date) >=', $start)
                    ->where('DATE(o.order_date) <=', $end);
        }

        $orders = $builder
            ->orderBy('o.id', 'DESC')
            ->get()
            ->getResult();

        // 🔥 SUMMARY
        $totalOrder = count($orders);
        $totalIncome = 0;
        $done = 0;
        $process = 0;
        $picked = 0;
        $new = 0;
        foreach ($orders as $o) {
            $totalIncome += $o->total_price;

            if ($o->last_status === 'new') $new++;
            if ($o->last_status === 'done') $done++;
            if ($o->last_status === 'process') $process++;
            if ($o->last_status === 'picked') $picked++;
        }

        return $this->response->setJSON([
            'status' => true,
            'data' => [
                'summary' => [
                    'total_order' => $totalOrder,
                    'total_income' => $totalIncome,
                    'new' => $new,
                    'done' => $done,
                    'process' => $process,
                    'picked' => $picked,
                ],
                'orders' => $orders
            ]
        ]);
    }
}