<?php

namespace App\Controllers\Api;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;

class Dashboard extends BaseController
{
    use ResponseTrait;

    public function index()
    {
        $db = \Config\Database::connect();

        // 🔥 QUERY UTAMA (OPERASIONAL + KEUANGAN)
        $result = $db->query("
            SELECT 
                COUNT(*) as total_order,

                -- 📊 HARI INI
                SUM(CASE 
                    WHEN DATE(order_date) = CURDATE() THEN 1 
                    ELSE 0 
                END) as transaksi_hari_ini,

                SUM(CASE 
                    WHEN DATE(order_date) = CURDATE() AND status = 'new' THEN 1 
                    ELSE 0 
                END) as order_baru,

                -- 📦 STATUS
                SUM(CASE 
                    WHEN status IN ('new','proses') THEN 1 
                    ELSE 0 
                END) as proses,

                SUM(CASE 
                    WHEN status = 'selesai' THEN 1 
                    ELSE 0 
                END) as selesai,

                -- 💰 KEUANGAN
                SUM(CASE 
                    WHEN payment_status = 'unpaid' THEN 1 
                    ELSE 0 
                END) as belum_bayar,

                -- 💰 PENDAPATAN HARI INI (berdasarkan order)
                SUM(CASE 
                    WHEN DATE(order_date) = CURDATE() 
                    AND payment_status = 'paid'
                    THEN total_price 
                    ELSE 0 
                END) as pendapatan_hari_ini,

                -- 💰 TOTAL PENDAPATAN (SEMUA)
                SUM(CASE 
                    WHEN payment_status = 'paid'
                    THEN total_price 
                    ELSE 0 
                END) as total_pendapatan

            FROM orders
        ")->getRow();

        // 👤 TOTAL CUSTOMER
        $pelanggan = $db->table('customers')->countAllResults();

        return $this->respond([
            'status' => true,
            'data' => [
                'total_order' => (int)$result->total_order,
                'transaksi_hari_ini' => (int)$result->transaksi_hari_ini,
                'order_baru' => (int)$result->order_baru,
                'proses' => (int)$result->proses,
                'selesai' => (int)$result->selesai,
                'belum_bayar' => (int)$result->belum_bayar,
                'pendapatan_hari_ini' => (float)$result->pendapatan_hari_ini,
                'total_pendapatan' => (float)$result->total_pendapatan,
                'pelanggan' => $pelanggan,
            ]
        ]);
    }
}