<?php

namespace App\Controllers;

use App\Models\InvoiceModel;
use App\Models\ClientModel;
use CodeIgniter\Controller;

class DashboardController extends Controller
{
    protected $helpers = ['url', 'form'];

    public function index()
    {
        $companyId = session()->get('company_id') ?? 1;

        $invoiceModel = new InvoiceModel();
        $clientModel = new ClientModel();

        $stats = $invoiceModel->getDashboardStats($companyId);
        $monthlyRevenue = $invoiceModel->getMonthlyRevenue($companyId, 12);

        $recentInvoices = $invoiceModel->where('company_id', $companyId)
            ->orderBy('created_at', 'DESC')
            ->limit(10)
            ->findAll();

        $db = \Config\Database::connect();
        $topClients = $db->query("
            SELECT c.company_name, COUNT(i.id) as invoice_count, SUM(i.total_ttc) as total_revenue
            FROM satt_clients c
            JOIN satt_invoices i ON c.id = i.client_id
            WHERE c.company_id = ? AND i.deleted_at IS NULL
            GROUP BY c.id
            ORDER BY total_revenue DESC
            LIMIT 5
        ", [$companyId])->getResultArray();

        $data = [
            'stats' => $stats,
            'monthlyRevenue' => $monthlyRevenue,
            'recentInvoices' => $recentInvoices,
            'topClients' => $topClients,
        ];

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