<?php

namespace App\Http\Controllers\Admin;

use App\Models\Facility;
use App\Constants\Status;
use App\Models\FleetType;
use App\Models\SeatLayout;
use App\Lib\RequiredConfig;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class FleetTypeController extends Controller {
    public function type() {
        $pageTitle   = 'Fleet Type';
        $seatLayouts = SeatLayout::all();
        $fleetType   = FleetType::with('facilities')->orderBy('id', 'desc')->paginate(getPaginate());
        $facilities  = Facility::active()->get();
        return view('admin.fleet.type', compact('pageTitle', 'fleetType', 'seatLayouts', 'facilities'));
    }

    public function typeStore(Request $request, $id = 0) {
        $request->validate([
            'name'         => 'required|unique:fleet_types,name,' . $id,
            'seat_layout'  => 'required',
            'deck'         => 'required|numeric|gt:0',
            'deck_seats'   => 'required|array|min:1',
            'deck_seats.*' => 'required|numeric|gt:0',
            'facilities.*' => 'nullable',
        ], [
            'deck_seats.*.required' => 'Seat number for all deck is required',
            'deck_seats.*.numeric'  => 'Seat number for all deck is must be a number',
            'deck_seats.*.gt:0'     => 'Seat number for all deck is must be greater than 0',
        ]);

        if ($id) {
            $fleetType = FleetType::findOrFail($id);
            $message   = "Fleet type updated successfully";
        } else {
            $fleetType = new FleetType();
            $message   = "Fleet type added successfully";
        }

        $fleetType->name        = $request->name;
        $fleetType->seat_layout = $request->seat_layout;
        $fleetType->deck        = $request->deck;
        $fleetType->deck_seats  = $request->deck_seats;
        $fleetType->has_ac      = $request->has_ac ? Status::ENABLE : Status::DISABLE;
        $fleetType->status      = Status::ENABLE;
        $fleetType->save();

        if ($id) {
            $fleetType->facilities()->sync($request->facilities);
        } else {
            $fleetType->facilities()->attach($request->facilities);
        }

        RequiredConfig::configured('fleet_type');
        $notify[] = ['success', $message];
        return back()->withNotify($notify);
    }

    public function typeStatus($id) {
        return FleetType::changeStatus($id);
    }
}
