<?php
declare(strict_types=1);

namespace App\Controllers\Web;

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

final class AssetTypesController 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
    {
        $this->render('asset-types/index', [
            'types' => AssetType::listForTenant($this->tenantId()),
            'flash' => Session::flash('asset_types_msg'),
        ]);
    }

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

    public function edit(int $id): void
    {
        $type = AssetType::findInTenant($this->tenantId(), $id);
        if (!$type) { Session::flash('asset_types_msg', 'Not found.'); redirect('/AssetTypes'); }
        $this->render('asset-types/form', [
            'type' => $type,
            'csrf' => Tool::generateCsrf(),
        ]);
    }

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

        if (trim((string) ($_POST['code'] ?? '')) === '' || trim((string) ($_POST['name'] ?? '')) === '') {
            Session::flash('asset_types_msg', 'Code and name are required.');
            redirect($id > 0 ? "/AssetTypes/edit/{$id}" : '/AssetTypes/create');
        }

        if ($id > 0) {
            $existing = AssetType::findInTenant($tenantId, $id);
            if (!$existing) { Session::flash('asset_types_msg', 'Not found.'); redirect('/AssetTypes'); }
            AssetType::update($tenantId, $id, $_POST);
            Session::flash('asset_types_msg', 'Type updated.');
        } else {
            $id = AssetType::create($tenantId, $userId, $_POST);
            Session::flash('asset_types_msg', 'Type created.');
        }
        redirect("/AssetTypes/show/{$id}");
    }

    public function show(int $id): void
    {
        $type = AssetType::findInTenant($this->tenantId(), $id);
        if (!$type) { Session::flash('asset_types_msg', 'Not found.'); redirect('/AssetTypes'); }
        $this->render('asset-types/show', [
            'type'   => $type,
            'fields' => AssetTypeField::forType($this->tenantId(), $id),
            'csrf'   => Tool::generateCsrf(),
            'flash'  => Session::flash('asset_types_msg'),
        ]);
    }

    public function delete(int $id): void
    {
        AssetType::softDelete($this->tenantId(), $id);
        Session::flash('asset_types_msg', 'Type deleted.');
        redirect('/AssetTypes');
    }

    public function saveField(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/AssetTypes');
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) {
            Session::flash('asset_types_msg', 'Session expired.'); redirect('/AssetTypes');
        }
        $tenantId = $this->tenantId();
        $typeId   = (int) ($_POST['asset_type_id'] ?? 0);
        $fieldId  = (int) ($_POST['field_id'] ?? 0);

        // Make sure asset type belongs to this tenant.
        $type = AssetType::findInTenant($tenantId, $typeId);
        if (!$type) { Session::flash('asset_types_msg', 'Type not found.'); redirect('/AssetTypes'); }

        if (trim((string) ($_POST['field_key'] ?? '')) === '' || trim((string) ($_POST['field_label'] ?? '')) === '') {
            Session::flash('asset_types_msg', 'Field key and label are required.');
            redirect("/AssetTypes/show/{$typeId}");
        }

        if ($fieldId > 0) {
            $existing = AssetTypeField::findInTenant($tenantId, $fieldId);
            if (!$existing) { Session::flash('asset_types_msg', 'Field not found.'); redirect("/AssetTypes/show/{$typeId}"); }
            AssetTypeField::update($fieldId, $_POST);
            Session::flash('asset_types_msg', 'Field updated.');
        } else {
            AssetTypeField::create($typeId, $_POST);
            Session::flash('asset_types_msg', 'Field added.');
        }
        redirect("/AssetTypes/show/{$typeId}");
    }

    public function deleteField(int $fieldId): void
    {
        $tenantId = $this->tenantId();
        $field = AssetTypeField::findInTenant($tenantId, $fieldId);
        if (!$field) { Session::flash('asset_types_msg', 'Field not found.'); redirect('/AssetTypes'); }
        AssetTypeField::delete($fieldId);
        Session::flash('asset_types_msg', 'Field removed.');
        redirect('/AssetTypes/show/' . (int) $field['asset_type_id']);
    }
}
