<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Models\ExpenseCategory;

class ExpenseCategoryController {
    public function index() {
        if (!Auth::hasPermission('expenses')) {
            redirect('/login');
            exit;
        }

        $db = \App\Core\Database::getInstance();
        $categories = $db->query("SELECT ec.*, (SELECT COUNT(*) FROM expenses WHERE expense_category_id = ec.id) as usage_count 
                                  FROM expense_categories ec ORDER BY ec.name ASC")->fetchAll();

        $title = 'Expense Categories';
        require_once __DIR__ . '/../../views/admin/expense_categories.php';
    }

    public function save() {
        if (!Auth::hasPermission('expenses')) {
            redirect('/login');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $categoryModel = new ExpenseCategory();
            $data = [
                'id' => $_POST['id'] ?? null,
                'name' => $_POST['name']
            ];

            try {
                $categoryModel->save($data);
                $_SESSION['toast'] = ['message' => $data['id'] ? 'Category updated!' : 'Category created!', 'type' => 'success'];
            } catch (\Exception $e) {
                $_SESSION['toast'] = ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
            }
        }
        redirect('/admin/expense-categories');
        exit;
    }

    public function delete() {
        if (!Auth::hasPermission('expenses')) {
            redirect('/login');
            exit;
        }

        if (isset($_GET['id'])) {
            try {
                $categoryModel = new ExpenseCategory();
                $categoryModel->delete($_GET['id']);
                $_SESSION['toast'] = ['message' => 'Category deleted.', 'type' => 'info'];
            } catch (\Exception $e) {
                $_SESSION['toast'] = ['message' => 'Error: Cannot delete category. It might be in use.', 'type' => 'error'];
            }
        }
        redirect('/admin/expense-categories');
        exit;
    }
}
