<?php

namespace App\Http\Controllers;

use App\Models\ORM\Place;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;

class PlacesController extends Controller
{
    public function index(): View
    {
        $places = Place::paginate(10);
        return view('places.index', compact('places'));
    }

    public function create()
    {
        return view('places.create');
    }

    public function store(Request $request): Redirector|RedirectResponse
    {
        // Очистка телефона (только цифры)
        if ($request->has('phone')) {
            $cleanPhone = preg_replace('/\D/', '', $request->phone);
            $request->merge(['phone' => $cleanPhone]);
        }

        $data = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'nullable|digits:11',
            'address' => 'required|string|max:255',
            'url' => 'required|string|max:255',
            'gps' => [
                'nullable',
                'regex:/^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/'
            ],
            'description' => 'nullable',
        ],[
            'phone.digits' => 'Номер телефона должен содержать 11 цифр.',
            'gps.regex' => "Неверный формат GPS координат"
        ]);

        if ($request->has('gps')) {
            $data['gps'] = $this->convertGPS($request->gps);
        }

        Place::create($data);

        return redirect()
            ->route('places.index')
            ->with('status', 'Локация создана!');
    }

    private function convertGPS(string $gps): string
    {
        return str_replace([',',' '], ['|',''], $gps);
    }

    public function edit(int $id): VIEW
    {
        $place = Place::find($id);
        return view('places.edit', compact('place'));
    }

    public function update(Request $request, int $id)
    {
        // Очистка телефона от маски перед валидацией
        if ($request->filled('phone')) {
            $request->merge(['phone' => preg_replace('/\D/', '', $request->phone)]);
        }

        $validated = $request->validate([
            'name' => 'required|max:512',
            'address' => 'nullable|max:512',
            'phone' => 'nullable|digits:11',
            'gps' => [
                'nullable',
                'regex:/^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/'
            ],
            'url' => 'nullable|url|max:255',
            'description' => 'nullable',
        ]);

        $place = Place::findOrFail($id);
        $place->update($validated);

        return redirect()
            ->route('places.index')
            ->with('success', 'Данные обновлены');
    }

    public function delete(int $id): Redirector|RedirectResponse
    {
        $place = Place::findOrFail($id);
        $place->delete();

        return redirect()
            ->route('places.index')
            ->with('status', 'Удалено!');
    }
}
