<?php

namespace App\Http\Controllers\Tenant;

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

class EmployeeController extends Controller
{
    public function index(): View
    {
        return view('tenant.employees.index');
    }

    public function create(): View
    {
        return view('tenant.employees.create', [
            'employee' => new Employee([
                'color' => '#4f46e5',
                'is_active' => true,
                'is_bookable' => true,
            ]),
            'services' => Service::active()->orderBy('name')->get(['id', 'name']),
            'selectedServices' => [],
        ]);
    }

    public function edit(Employee $employee): View
    {
        $this->authorize('update', $employee);
        $employee->load('services:id');

        return view('tenant.employees.edit', [
            'employee' => $employee,
            'services' => Service::active()->orderBy('name')->get(['id', 'name']),
            'selectedServices' => $employee->services->pluck('id')->all(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $this->validatedData($request);
        unset($data['photo'], $data['service_ids']);
        $data['is_active'] = $request->boolean('is_active');
        $data['is_bookable'] = $request->boolean('is_bookable');
        $data['branch_id'] = Tenant::current()?->mainBranch?->id;

        if ($request->hasFile('photo')) {
            $data['photo_path'] = PublicUploader::store($request->file('photo'), 'employees');
        }

        $employee = Employee::create($data);
        $this->syncServices($employee, $request->input('service_ids', []));

        return redirect()->route('tenant.employees.index')
            ->with('success', 'Empleado creado correctamente.');
    }

    public function update(Request $request, Employee $employee): RedirectResponse
    {
        $this->authorize('update', $employee);

        $data = $this->validatedData($request);
        unset($data['photo'], $data['service_ids']);
        $data['is_active'] = $request->boolean('is_active');
        $data['is_bookable'] = $request->boolean('is_bookable');

        if ($request->hasFile('photo')) {
            if ($employee->photo_path) {
                PublicUploader::delete($employee->photo_path);
            }

            $data['photo_path'] = PublicUploader::store($request->file('photo'), 'employees');
        }

        $employee->update($data);
        $this->syncServices($employee, $request->input('service_ids', []));

        return redirect()->route('tenant.employees.index')
            ->with('success', 'Empleado actualizado correctamente.');
    }

    public function destroy(Employee $employee): RedirectResponse
    {
        $this->authorize('delete', $employee);
        $employee->delete();

        return redirect()->route('tenant.employees.index')
            ->with('success', 'Empleado eliminado correctamente.');
    }

    protected function validatedData(Request $request): array
    {
        return $request->validate([
            'first_name' => ['required', 'string', 'max:100'],
            'last_name' => ['nullable', 'string', 'max:100'],
            'email' => ['nullable', 'email', 'max:255'],
            'phone' => ['nullable', 'string', 'max:25'],
            'position' => ['nullable', 'string', 'max:100'],
            'bio' => ['nullable', 'string', 'max:1000'],
            'color' => ['required', 'regex:/^#[0-9a-fA-F]{6}$/'],
            'photo' => ['nullable', 'image', 'max:2048'],
            'service_ids' => ['nullable', 'array'],
            'service_ids.*' => ['integer', 'exists:services,id'],
        ]);
    }

    protected function syncServices(Employee $employee, array $serviceIds): void
    {
        $sync = collect($serviceIds)
            ->map(fn ($id) => (int) $id)
            ->unique()
            ->mapWithKeys(fn ($id) => [$id => ['company_id' => Tenant::id()]])
            ->all();

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