<?php

namespace App\Http\Controllers\Employee;

use App\Http\Controllers\Controller;
use App\Models\Service;
use App\Support\Tenant;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ServiceController extends Controller
{
    public function index(): View
    {
        $employee = auth()->user()->employee?->load('services:id');
        $services = Service::active()
            ->with('category:id,name')
            ->orderBy('name')
            ->get();

        $selectedServices = $employee?->services->pluck('id')->all() ?? [];

        return view('employee.services', compact('employee', 'services', 'selectedServices'));
    }

    public function update(Request $request): RedirectResponse
    {
        $employee = auth()->user()->employee;

        abort_if(! $employee, 403, 'No tienes un perfil de empleado asociado.');

        $data = $request->validate([
            'service_ids' => ['nullable', 'array'],
            'service_ids.*' => ['integer'],
        ]);

        $serviceIds = Service::active()
            ->whereIn('id', collect($data['service_ids'] ?? [])->map(fn ($id) => (int) $id)->all())
            ->pluck('id')
            ->all();

        $sync = collect($serviceIds)
            ->mapWithKeys(fn ($id) => [$id => ['company_id' => Tenant::id()]])
            ->all();

        $employee->services()->sync($sync);

        return back()->with('success', 'Tus servicios fueron actualizados correctamente.');
    }
}
