<?php

declare(strict_types=1);

namespace App\Modules\Expenses\Presentation\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\Request;
use App\Core\Response;
use App\Modules\Expenses\Application\Services\ExpenseFormService;
use Throwable;

final class ExpenseFormController
{
    public function __construct(private ?ExpenseFormService $service = null)
    {
        $this->service ??= new ExpenseFormService(db());
    }

    public function categoryForm(): void
    {
        Auth::requireLogin();
        $this->service->ensureSchema();

        $id = (int) Request::get('id', 0);
        require_permission('expenses.categories.create');

        try {
            if (Request::isPost()) {
                Csrf::verify();
                $this->service->saveCategory($id, Request::all());
                Response::flash('success', 'تم حفظ مجموعة المصروفات.');
                Response::redirect('/finance/expenses/categories');
                return;
            }

            $data = $this->service->loadCategoryForm($id);
            Response::view('pages/expenses/category_form', $data + [
                'errors' => [],
                'page_title' => $id > 0 ? 'تعديل مجموعة مصروفات' : 'إضافة مجموعة مصروفات',
                'breadcrumbs' => [
                    ['label' => 'لوحة التحكم', 'url' => '/admin/dashboard'],
                    ['label' => 'المصاريف'],
                    ['label' => 'مجموعات المصروفات', 'url' => '/finance/expenses/categories'],
                    ['label' => $id > 0 ? 'تعديل مجموعة مصروفات' : 'إضافة مجموعة مصروفات'],
                ],
            ]);
        } catch (Throwable $e) {
            $data = $this->service->loadCategoryForm($id);
            if (Request::isPost()) {
                $data['category'] = array_merge($data['category'], [
                    'name' => trim((string) Request::post('name', '')),
                    'code' => trim((string) Request::post('code', '')),
                    'is_active' => (int) Request::post('is_active', 1),
                    'sort_order' => (int) Request::post('sort_order', 0),
                    'notes' => trim((string) Request::post('notes', '')),
                ]);
            }

            Response::view('pages/expenses/category_form', $data + [
                'errors' => [$e->getMessage()],
                'page_title' => $id > 0 ? 'تعديل مجموعة مصروفات' : 'إضافة مجموعة مصروفات',
                'breadcrumbs' => [
                    ['label' => 'لوحة التحكم', 'url' => '/admin/dashboard'],
                    ['label' => 'المصاريف'],
                    ['label' => 'مجموعات المصروفات', 'url' => '/finance/expenses/categories'],
                    ['label' => $id > 0 ? 'تعديل مجموعة مصروفات' : 'إضافة مجموعة مصروفات'],
                ],
            ]);
        }
    }

    public function itemForm(): void
    {
        Auth::requireLogin();
        $this->service->ensureSchema();

        $id = (int) Request::get('id', 0);
        $categoryId = (int) Request::get('category_id', 0);
        require_permission('expenses.items.create');

        try {
            if (Request::isPost()) {
                Csrf::verify();
                $this->service->saveItem($id, Request::all());
                Response::flash('success', 'تم حفظ بند المصروف.');
                Response::redirect('/finance/expenses/items');
                return;
            }

            $data = $this->service->loadItemForm($id, $categoryId);
            Response::view('pages/expenses/item_form', $data + [
                'errors' => [],
                'page_title' => $id > 0 ? 'تعديل بند مصروف' : 'إضافة بند مصروف',
                'breadcrumbs' => [
                    ['label' => 'لوحة التحكم', 'url' => '/admin/dashboard'],
                    ['label' => 'المصاريف'],
                    ['label' => 'بنود المصروفات', 'url' => '/finance/expenses/items'],
                    ['label' => $id > 0 ? 'تعديل بند مصروف' : 'إضافة بند مصروف'],
                ],
            ]);
        } catch (Throwable $e) {
            $data = $this->service->loadItemForm($id, $categoryId);
            if (Request::isPost()) {
                $data['item'] = array_merge($data['item'], [
                    'category_id' => (int) Request::post('category_id', 0),
                    'name' => trim((string) Request::post('name', '')),
                    'code' => trim((string) Request::post('code', '')),
                    'is_active' => (int) Request::post('is_active', 1),
                    'sort_order' => (int) Request::post('sort_order', 0),
                    'notes' => trim((string) Request::post('notes', '')),
                ]);
            }

            Response::view('pages/expenses/item_form', $data + [
                'errors' => [$e->getMessage()],
                'page_title' => $id > 0 ? 'تعديل بند مصروف' : 'إضافة بند مصروف',
                'breadcrumbs' => [
                    ['label' => 'لوحة التحكم', 'url' => '/admin/dashboard'],
                    ['label' => 'المصاريف'],
                    ['label' => 'بنود المصروفات', 'url' => '/finance/expenses/items'],
                    ['label' => $id > 0 ? 'تعديل بند مصروف' : 'إضافة بند مصروف'],
                ],
            ]);
        }
    }
}
