<?php
declare(strict_types=1);

namespace App\Controllers\Web;

use App\Middleware\AuthSession;
use App\Middleware\TenantScope;
use App\Models\ProductService;
use Core\Controller;
use Core\Session;
use Core\Tool;

final class ProductsServicesController extends Controller
{
    public function middleware(): array
    {
        return [AuthSession::class, TenantScope::class];
    }

    private function tenantId(): int
    {
        return (int) ($_SESSION['tenant_id'] ?? 0);
    }

    public function index(): void
    {
        $filters = [
            'type'      => $_GET['type']      ?? null,
            'category'  => $_GET['category']  ?? null,
            'is_active' => $_GET['is_active'] ?? null,
            'q'         => $_GET['q']         ?? null,
        ];
        if (isset($filters['is_active']) && $filters['is_active'] === '') {
            $filters['is_active'] = null;
        }
        $sort      = $_GET['sort'] ?? 'name_asc';
        $tenantId  = $this->tenantId();
        $active    = array_filter($filters, fn($v) => $v !== null && $v !== '');
        $perPage   = (int) ($_GET['per_page'] ?? 25);
        $perPage   = max(10, min($perPage, 100));
        $page      = max(1, (int) ($_GET['page'] ?? 1));
        $total     = ProductService::countForTenant($tenantId, $active);
        $lastPage  = max(1, (int) ceil($total / $perPage));
        if ($page > $lastPage) $page = $lastPage;

        $this->render('products-services/index', [
            'items'      => ProductService::listForTenant($tenantId, $active, $perPage, ($page - 1) * $perPage, $sort),
            'sort'       => $sort,
            'filters'    => $filters,
            'categories' => ProductService::categoriesForTenant($tenantId),
            'flash'      => Session::flash('ps_msg'),
            'pager'      => [
                'total'    => $total,
                'per_page' => $perPage,
                'page'     => $page,
                'last'     => $lastPage,
                'from'     => $total > 0 ? ($page - 1) * $perPage + 1 : 0,
                'to'       => min($page * $perPage, $total),
            ],
        ]);
    }

    public function create(): void
    {
        $this->render('products-services/form', [
            'item' => null,
            'csrf' => Tool::generateCsrf(),
        ]);
    }

    public function edit(int $id): void
    {
        $tenantId = $this->tenantId();
        $item = ProductService::findInTenant($tenantId, $id);
        if (!$item) { Session::flash('ps_msg', 'Item not found.'); redirect('/ProductsServices'); }
        $this->render('products-services/form', [
            'item' => $item,
            'csrf' => Tool::generateCsrf(),
        ]);
    }

    public function save(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/ProductsServices');
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) {
            Session::flash('ps_msg', 'Session expired.'); redirect('/ProductsServices');
        }
        $tenantId = $this->tenantId();
        $id = (int) ($_POST['item_id'] ?? 0);

        if (trim((string) ($_POST['name'] ?? '')) === '') {
            Session::flash('ps_msg', 'Name is required.');
            redirect($id > 0 ? "/ProductsServices/edit/{$id}" : '/ProductsServices/create');
        }

        if ($id > 0) {
            ProductService::update($tenantId, $id, $_POST);
            Session::flash('ps_msg', 'Item updated.');
        } else {
            $id = ProductService::create($tenantId, $_POST);
            Session::flash('ps_msg', 'Item created.');
        }
        redirect("/ProductsServices/edit/{$id}");
    }

    public function delete(int $id): void
    {
        ProductService::softDelete($this->tenantId(), $id);
        Session::flash('ps_msg', 'Item deleted.');
        redirect('/ProductsServices');
    }
}