<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\InvoiceModel;
use App\Models\ServiceModel;

class DashboardController extends BaseController
{
    public function index()
    {
        $companyModel = new CompanyModel();
        $companyId = $this->currentCompanyId() ?? $companyModel->first()['id'] ?? null;

        $pnl = $companyId ? $companyModel->profitAndLoss(
            $companyId,
            date('Y-m-01'),
            date('Y-m-t')
        ) : ['revenue' => 0, 'expenses' => 0, 'net_profit' => 0];

        $invoiceModel = new InvoiceModel();
        $serviceModel = new ServiceModel();

        $upcomingRenewals = $companyId
            ? $serviceModel->where('company_id', $companyId)->where('status', 'active')
                ->orderBy('renewal_date', 'ASC')->findAll(5)
            : [];

        $recentInvoices = $companyId
            ? $invoiceModel->where('company_id', $companyId)->orderBy('created_at', 'DESC')->findAll(5)
            : [];

        return view('admin/dashboard', [
            'pnl' => $pnl,
            'upcomingRenewals' => $upcomingRenewals,
            'recentInvoices' => $recentInvoices,
        ]);
    }
}
