<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Http\Resources\ClientResource;
use App\Models\Client;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class ProfilController extends Controller
{
    /**
     * GET /api/client/profil
     * Retourne le profil complet du client connecté
     */
    public function show(Request $request): JsonResponse
    {
        try {
            $client = $request->user()->client()->with('ville', 'quartier')->firstOrFail();
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json(['message' => 'Accès non autorisé'], 403);
        }
        
        return response()->json([
            'user' => $request->user(),
            'client' => new ClientResource($client)
        ]);
    }

    /**
     * PUT /api/client/profil
     * Mise à jour du profil client
     */
    public function update(Request $request): JsonResponse
    {
        try {
            $client = $request->user()->client()->firstOrFail();
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json(['message' => 'Accès non autorisé'], 403);
        }

        $request->validate([
            'type_client' => ['sometimes', 'in:particulier,entreprise,evenementiel'],
            'nom_complet' => ['sometimes', 'string', 'max:200'],
            'raison_sociale' => ['sometimes', 'string', 'max:200'],
            'nom_contact' => ['sometimes', 'string', 'max:200'],
            'telephone_principal' => ['sometimes', 'string', 'max:30'],
            'telephone_secondaire' => ['sometimes', 'nullable', 'string', 'max:30'],
            'adresse_complete' => ['sometimes', 'nullable', 'string'],
            'quartier_id' => ['sometimes', 'nullable', 'exists:quartiers,id'],
            'ville_id' => ['sometimes', 'exists:villes,id'],
        ]);

        $client->update($request->only([
            'type_client', 'nom_complet', 'raison_sociale', 'nom_contact',
            'telephone_principal', 'telephone_secondaire', 'adresse_complete',
            'quartier_id', 'ville_id',
        ]));

        return response()->json([
            'message' => 'Profil mis à jour avec succès',
            'client' => new ClientResource($client->load('ville', 'quartier'))
        ]);
    }
}
