<?php

namespace App\Http\Controllers\Provider;

use App\Http\Controllers\Controller;
use App\Http\Requests\UpdateProviderProfileRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class ProfileController extends Controller
{
    public function edit()
    {
        $provider = auth()->user()->provider;
        return view('provider.profile.edit', compact('provider'));
    }

    public function update(UpdateProviderProfileRequest $request)
    {
        $provider = auth()->user()->provider;
        
        DB::beginTransaction();
        try {
            // Mise à jour des données utilisateur
            $userData = [
                'name' => $request->name,
                'email' => $request->email,
            ];
            
            // Mise à jour du mot de passe si fourni
            if ($request->filled('password')) {
                $userData['password'] = Hash::make($request->password);
            }
            
            auth()->user()->update($userData);

            // Gestion du logo
            $logoPath = $provider->logo;
            
            // Supprimer le logo si demandé
            if ($request->remove_logo) {
                if ($logoPath) {
                    Storage::disk('public')->delete($logoPath);
                    $logoPath = null;
                }
            }
            
            // Nouveau logo uploadé
            if ($request->hasFile('logo')) {
                if ($logoPath) Storage::disk('public')->delete($logoPath);
                $logoPath = $request->file('logo')->store('logos', 'public');
            }

            $provider->update([
                'business_name' => $request->business_name,
                'phone' => $request->phone,
                'address' => $request->address,
                'city' => $request->city,
                'country' => $request->country,
                'logo' => $logoPath,
                'description' => $request->description,
            ]);

            DB::commit();
            return back()->with('success', 'Profil mis à jour avec succès.');
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->withInput()->with('error', 'Échec de la mise à jour du profil.');
        }
    }
}
