<?php
declare(strict_types=1);

namespace App\Controllers\Api;

use App\Middleware\ApiToken;
use App\Middleware\TenantScope;
use App\Models\Permit;
use Core\Controller;

/**
 * Mobile-facing Permits API.
 * The field tech can list, view and request permits from the phone; approval
 * still happens on the web (PMs / admins).
 *
 *   GET  /api/v1/permits/index[?work_order_id=n]
 *   GET  /api/v1/permits/show/{id}
 *   POST /api/v1/permits/create           body: permit_type_id, title, ...
 *   GET  /api/v1/permits/types            → catalog of permit types
 */
final class PermitsController extends Controller
{
    public function middleware(): array
    {
        return [ApiToken::class, TenantScope::class];
    }

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

    public function index(): void
    {
        $tenantId = $this->tenantId();
        $filters = array_filter([
            'status'         => $_GET['status'] ?? null,
            'permit_type_id' => $_GET['permit_type_id'] ?? null,
        ]);
        if (!empty($_GET['work_order_id'])) {
            $this->json(['data' => Permit::forWorkOrder($tenantId, (int) $_GET['work_order_id'])]);
        }
        $this->json(['data' => Permit::listForTenant($tenantId, $filters)]);
    }

    public function show(int $id): void
    {
        $p = Permit::findInTenant($this->tenantId(), $id);
        if (!$p) $this->json(['error' => 'Not found'], 404);
        $this->json(['data' => $p]);
    }

    public function types(): void
    {
        $this->json(['data' => Permit::typesForTenant($this->tenantId())]);
    }

    public function create(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') $this->json(['error' => 'POST required'], 405);
        $body = $this->input();
        if (empty($body['permit_type_id']) || empty($body['title'])) {
            $this->json(['error' => 'permit_type_id and title are required'], 422);
        }
        $id = Permit::create($this->tenantId(), $this->userId() ?: null, $body);
        $this->json(['success' => true, 'permit_id' => $id, 'permit' => Permit::findInTenant($this->tenantId(), $id)]);
    }
}
