<?php
declare(strict_types=1);

namespace App\Controllers\Web;

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

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

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

    /** Only admin/exec/PM can approve/reject/convert. Everyone can raise. */
    private function canReview(): 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,
            'priority' => $_GET['priority'] ?? null,
            'q'        => $_GET['q']        ?? null,
        ]);
        $this->render('work-requests/index', [
            'requests' => WorkRequest::listForTenant($tenantId, $filters),
            'counts'   => WorkRequest::countsForTenant($tenantId),
            'filters'  => $filters,
            'canReview'=> $this->canReview(),
            'flash'    => Session::flash('wr_msg'),
        ]);
    }

    public function create(): void
    {
        $tenantId = $this->tenantId();
        $this->render('work-requests/form', [
            'request' => null,
            'assets'  => Asset::optionsForTenant($tenantId),
            'sites'   => Site::optionsForTenant($tenantId),
            'csrf'    => Tool::generateCsrf(),
        ]);
    }

    public function save(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/WorkRequests');
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) {
            Session::flash('wr_msg', 'Session expired.'); redirect('/WorkRequests');
        }
        $tenantId = $this->tenantId();
        $userId   = (int) (Session::user()['user_id'] ?? 0) ?: null;
        if (trim((string) ($_POST['title'] ?? '')) === '') {
            Session::flash('wr_msg', 'Title is required.'); redirect('/WorkRequests/create');
        }
        $id = WorkRequest::create($tenantId, $userId, $_POST);
        Session::flash('wr_msg', 'Request submitted.');
        redirect('/WorkRequests/show/' . $id);
    }

    public function show(int $id): void
    {
        $tenantId = $this->tenantId();
        $req = WorkRequest::findInTenant($tenantId, $id);
        if (!$req) { Session::flash('wr_msg', 'Request not found.'); redirect('/WorkRequests'); }
        $this->render('work-requests/show', [
            'request'   => $req,
            'canReview' => $this->canReview(),
            'csrf'      => Tool::generateCsrf(),
            'flash'     => Session::flash('wr_msg'),
        ]);
    }

    public function review(int $id): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/WorkRequests');
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) redirect('/WorkRequests');
        if (!$this->canReview()) {
            Session::flash('wr_msg', 'Not allowed.'); redirect('/WorkRequests/show/' . $id);
        }
        $tenantId = $this->tenantId();
        $status = $_POST['review_status'] ?? '';
        $note   = trim((string) ($_POST['review_note'] ?? ''));
        WorkRequest::markReviewed($tenantId, $id, (int) (Session::user()['user_id'] ?? 0), $status, $note ?: null);
        Session::flash('wr_msg', 'Request ' . $status . '.');
        redirect('/WorkRequests/show/' . $id);
    }

    /**
     * Approve → materialise into a Work Order. Uses the request as the seed for
     * the WO (title, description, asset, priority) and links back via converted_wo_id.
     */
    public function convert(int $id): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/WorkRequests');
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) redirect('/WorkRequests');
        if (!$this->canReview()) {
            Session::flash('wr_msg', 'Not allowed.'); redirect('/WorkRequests/show/' . $id);
        }
        $tenantId = $this->tenantId();
        $req = WorkRequest::findInTenant($tenantId, $id);
        if (!$req) redirect('/WorkRequests');
        if ($req['status'] === 'converted' && !empty($req['converted_wo_id'])) {
            redirect('/WorkOrders/show/' . (int) $req['converted_wo_id']);
        }
        $userId = (int) (Session::user()['user_id'] ?? 0);
        $woId = WorkOrder::create($tenantId, $userId, [
            'title'       => 'Req #' . $id . ': ' . $req['title'],
            'description' => $req['description'],
            'wo_type'     => 'corrective',
            'priority'    => $req['priority'] ?? 'medium',
            'status'      => 'draft',
            'asset_id'    => $req['asset_id'] ?? null,
            'site_id'     => $req['site_id']  ?? null,
        ]);
        WorkRequest::markConverted($tenantId, $id, $woId);
        Session::flash('wo_msg', 'Work Order created from request #' . $id . '.');
        redirect('/WorkOrders/show/' . $woId);
    }

    public function delete(int $id): void
    {
        if (!$this->canReview()) redirect('/WorkRequests');
        WorkRequest::softDelete($this->tenantId(), $id);
        Session::flash('wr_msg', 'Request deleted.');
        redirect('/WorkRequests');
    }
}
