<?php
declare(strict_types=1);

namespace App\Controllers\Web;

use App\Middleware\AuthSession;
use App\Middleware\TenantScope;
use App\Models\Asset;
use App\Models\Permit;
use App\Models\Role;
use App\Models\Site;
use App\Models\WorkOrder;
use Core\Controller;
use Core\Session;
use Core\Tool;

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

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

    private function canApprove(): bool
    {
        $role = Session::user()['role_code'] ?? '';
        return in_array($role, [Role::ADMIN, Role::EXECUTIVE, Role::PROJECT_MANAGER], true);
    }

    public function index(): void
    {
        $tenantId = $this->tenantId();
        $filters = array_filter([
            'status'         => $_GET['status'] ?? null,
            'permit_type_id' => $_GET['permit_type_id'] ?? null,
        ]);
        $this->render('permits/index', [
            'permits'    => Permit::listForTenant($tenantId, $filters),
            'counts'     => Permit::countsForTenant($tenantId),
            'types'      => Permit::typesForTenant($tenantId),
            'filters'    => $filters,
            'canApprove' => $this->canApprove(),
            'flash'      => Session::flash('permit_msg'),
        ]);
    }

    public function create(): void
    {
        $tenantId = $this->tenantId();
        $preselectWo = isset($_GET['wo']) ? (int) $_GET['wo'] : 0;
        $this->render('permits/form', [
            'permit'      => null,
            'types'       => Permit::typesForTenant($tenantId),
            'assets'      => Asset::optionsForTenant($tenantId),
            'sites'       => Site::optionsForTenant($tenantId),
            'workOrders'  => WorkOrder::listForTenant($tenantId),
            'preselectWo' => $preselectWo,
            'csrf'        => Tool::generateCsrf(),
        ]);
    }

    public function edit(int $id): void
    {
        $tenantId = $this->tenantId();
        $p = Permit::findInTenant($tenantId, $id);
        if (!$p) { Session::flash('permit_msg', 'Permit not found.'); redirect('/Permits'); }
        $this->render('permits/form', [
            'permit'      => $p,
            'types'       => Permit::typesForTenant($tenantId),
            'assets'      => Asset::optionsForTenant($tenantId),
            'sites'       => Site::optionsForTenant($tenantId),
            'workOrders'  => WorkOrder::listForTenant($tenantId),
            'preselectWo' => 0,
            'csrf'        => Tool::generateCsrf(),
        ]);
    }

    public function save(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/Permits');
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) redirect('/Permits');
        $tenantId = $this->tenantId();
        $userId   = (int) (Session::user()['user_id'] ?? 0) ?: null;
        $id       = (int) ($_POST['permit_id'] ?? 0);
        if (trim((string) ($_POST['title'] ?? '')) === '' || empty($_POST['permit_type_id'])) {
            Session::flash('permit_msg', 'Title and permit type are required.');
            redirect($id > 0 ? "/Permits/edit/{$id}" : '/Permits/create');
        }
        if ($id > 0) {
            Permit::update($tenantId, $id, $_POST);
            Session::flash('permit_msg', 'Permit updated.');
        } else {
            $id = Permit::create($tenantId, $userId, $_POST);
            Session::flash('permit_msg', 'Permit submitted for approval.');
        }
        redirect('/Permits/show/' . $id);
    }

    public function show(int $id): void
    {
        $tenantId = $this->tenantId();
        $p = Permit::findInTenant($tenantId, $id);
        if (!$p) { Session::flash('permit_msg', 'Permit not found.'); redirect('/Permits'); }
        $this->render('permits/show', [
            'permit'     => $p,
            'canApprove' => $this->canApprove(),
            'csrf'       => Tool::generateCsrf(),
            'flash'      => Session::flash('permit_msg'),
        ]);
    }

    public function approve(int $id): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect("/Permits/show/{$id}");
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null) || !$this->canApprove()) redirect("/Permits/show/{$id}");
        Permit::approve($this->tenantId(), $id, (int) (Session::user()['user_id'] ?? 0));
        Session::flash('permit_msg', 'Permit approved. Work Order can now start.');
        redirect("/Permits/show/{$id}");
    }

    public function reject(int $id): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect("/Permits/show/{$id}");
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null) || !$this->canApprove()) redirect("/Permits/show/{$id}");
        Permit::reject($this->tenantId(), $id, (int) (Session::user()['user_id'] ?? 0), $_POST['rejection_note'] ?? null);
        Session::flash('permit_msg', 'Permit rejected.');
        redirect("/Permits/show/{$id}");
    }

    public function activate(int $id): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect("/Permits/show/{$id}");
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) redirect("/Permits/show/{$id}");
        Permit::activate($this->tenantId(), $id);
        Session::flash('permit_msg', 'Permit activated.');
        redirect("/Permits/show/{$id}");
    }

    public function close(int $id): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect("/Permits/show/{$id}");
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) redirect("/Permits/show/{$id}");
        Permit::close($this->tenantId(), $id, (int) (Session::user()['user_id'] ?? 0));
        Session::flash('permit_msg', 'Permit closed.');
        redirect("/Permits/show/{$id}");
    }

    public function delete(int $id): void
    {
        if (!$this->canApprove()) redirect('/Permits');
        Permit::softDelete($this->tenantId(), $id);
        Session::flash('permit_msg', 'Permit deleted.');
        redirect('/Permits');
    }
}
