<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreClientRequest;
use App\Http\Requests\UpdateClientRequest;
use App\Models\Client;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class ClientController extends Controller
{
    public function __construct()
    {
        $this->authorizeResource(Client::class, 'client');
    }

    public function index(Request $request): View
    {
        $q = Client::query()->orderByDesc('updated_at');
        if ($search = trim((string) $request->get('q'))) {
            $q->where(function ($query) use ($search): void {
                $query->where('name', 'like', "%{$search}%")
                    ->orWhere('document_number', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });
        }
        $clients = $q->paginate(15)->withQueryString();

        return view('clients.index', compact('clients'));
    }

    public function create(): View
    {
        return view('clients.create');
    }

    public function store(StoreClientRequest $request): RedirectResponse
    {
        $data = $request->safe()->except('photo');
        if ($request->hasFile('photo')) {
            $data['photo_path'] = $request->file('photo')->store('client-photos', 'public');
        }
        $client = Client::query()->create($data);

        return redirect()->route('clients.show', $client)
            ->with('success', __('Cliente registrado correctamente.'));
    }

    public function show(Client $client): View
    {
        $client->load(['activePatients']);

        return view('clients.show', compact('client'));
    }

    public function edit(Client $client): View
    {
        return view('clients.edit', compact('client'));
    }

    public function update(UpdateClientRequest $request, Client $client): RedirectResponse
    {
        $data = $request->safe()->except(['photo', 'remove_photo']);
        if ($request->boolean('remove_photo') && $client->photo_path) {
            Storage::disk('public')->delete($client->photo_path);
            $data['photo_path'] = null;
        }
        if ($request->hasFile('photo')) {
            if ($client->photo_path) {
                Storage::disk('public')->delete($client->photo_path);
            }
            $data['photo_path'] = $request->file('photo')->store('client-photos', 'public');
        }
        $client->update($data);

        return redirect()->route('clients.show', $client)
            ->with('success', __('Cliente actualizado.'));
    }

    public function destroy(Client $client): RedirectResponse
    {
        if ($client->photo_path) {
            Storage::disk('public')->delete($client->photo_path);
        }
        foreach ($client->patients as $patient) {
            if ($patient->photo_path) {
                Storage::disk('public')->delete($patient->photo_path);
            }
        }
        $client->delete();

        return redirect()->route('clients.index')
            ->with('success', __('Cliente eliminado.'));
    }
}
