<?php

namespace Modules\Bms\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Bms\Entities\BmsArea;
use Modules\Bms\Services\Matching\MatchingEngine;

/**
 * P1 Matching Tester (scenario 2.1). Lets staff run the matching engine with
 * ad-hoc criteria and see scored halls with reasons — the same engine the
 * client PWA (P3) and employee workspace (P2) call through the REST API.
 */
class MatchController extends BmsBaseController
{
    public function tester()
    {
        $this->guard('bms.halls.view');

        return view('bms::matching.tester', [
            'areas'      => BmsArea::where('business_id', $this->businessId())->orderBy('name')->pluck('name', 'id')->toArray(),
            'fnbLevels'  => $this->fnbLevels(),
            'venueTypes' => $this->venueTypes(),
        ]);
    }

    public function run(Request $request, MatchingEngine $engine)
    {
        $this->guard('bms.halls.view');

        $criteria = $request->validate([
            'attendees'        => 'nullable|integer|min:0',
            'fnb_level'        => 'nullable|in:high_tea,drinks_only,set_menu,open_buffet,custom',
            'venue_preference' => 'nullable|in:open,closed,both',
            'area_id'          => 'nullable|integer',
            'budget'           => 'nullable|numeric|min:0',
            'dates'            => 'nullable|string', // comma-separated Y-m-d
        ]);

        $outcome = $engine->run($this->businessId(), $criteria);

        // Log the run for sales context (no lead linkage from the ad-hoc tester).
        $engine->logRun($this->businessId(), $outcome, ['source' => 'employee']);

        // Carry the criteria so each result can deep-link into a prefilled
        // New Booking (the staff-driven funnel: match → pick hall → book).
        return view('bms::matching._results', [
            'outcome'   => $outcome,
            'criteria'  => $criteria,
            'canBook'   => auth()->user()->can('bms.bookings.manage'),
        ]);
    }
}
