<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Response;
use App\Models\ExpenseModel;
use Exception;

class ExpenseController extends Controller
{
    private ExpenseModel $expenseModel;

    public function __construct()
    {
        $this->expenseModel = new ExpenseModel();
    }

    public function index(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $filters = $_GET;
        $page = (int) ($_GET['page'] ?? 1);
        $perPage = (int) ($_GET['per_page'] ?? 20);

        $expenses = $this->expenseModel->getAll($tenantId, $filters, $page, $perPage);
        Response::success($expenses);
    }

    public function show(string $id): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $expense = $this->expenseModel->getById((int)$id, $tenantId);

        if (!$expense) {
            Response::error('Expense not found', [], 404);
        }

        Response::success($expense);
    }

    public function store(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $userId = (int) $_REQUEST['user']['sub'];
        $data = $this->getJsonBody();

        $this->validate($data, [
            'expense_category' => 'required',
            'amount' => 'required|numeric'
        ]);

        try {
            $result = $this->expenseModel->createExpense($tenantId, $data, $userId);
            Response::success($result, 'Expense recorded successfully', 201);
        } catch (Exception $e) {
            Response::error($e->getMessage());
        }
    }

    public function getCategories(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $categories = $this->expenseModel->getCategories($tenantId);
        Response::success($categories);
    }
}
