<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Location;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class LocationController extends Controller
{
    public function index()
    {
        $locations = Location::query()->orderBy('name')->paginate(15);

        return view('locations.index', compact('locations'));
    }

    public function create()
    {
        return view('locations.create');
    }

    public function store(Request $request)
    {
        $companyId = Auth::user()?->company_id;
        $validated = $request->validate($this->rules($companyId));
        $validated['company_id'] = $companyId;

        Location::create($validated);

        return redirect()->route('locations.index')->with('success', 'Location created successfully.');
    }

    public function edit(Location $location)
    {
        return view('locations.edit', compact('location'));
    }

    public function update(Request $request, Location $location)
    {
        $companyId = Auth::user()?->company_id;
        $validated = $request->validate($this->rules($companyId, $location->id));
        $location->update($validated);

        return redirect()->route('locations.index')->with('success', 'Location updated successfully.');
    }

    public function destroy(Location $location)
    {
        $assignedEmployees = $location->users()->count();
        if ($assignedEmployees > 0) {
            return redirect()
                ->route('locations.index')
                ->with('error', "Location cannot be deleted because it is assigned to {$assignedEmployees} employee(s).");
        }

        $location->delete();

        return redirect()->route('locations.index')->with('success', 'Location deleted successfully.');
    }

    /**
     * @return array<string, mixed>
     */
    private function rules(?int $companyId, ?int $ignoreLocationId = null): array
    {
        $uniqueCodeRule = Rule::unique('locations', 'code')->ignore($ignoreLocationId);
        if ($companyId === null) {
            $uniqueCodeRule = $uniqueCodeRule->where(fn ($query) => $query->whereNull('company_id'));
        } else {
            $uniqueCodeRule = $uniqueCodeRule->where(fn ($query) => $query->where('company_id', $companyId));
        }

        return [
            'name' => ['required', 'string', 'max:191'],
            'code' => [
                'required',
                'string',
                'max:100',
                $uniqueCodeRule,
            ],
            'address' => ['nullable', 'string'],
        ];
    }
}
