<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreProviderRequest;
use App\Http\Requests\UpdateProviderRequest;
use App\Models\Provider;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class ProviderController extends Controller
{
    public function index()
    {
        $providers = Provider::with('user')->orderBy('created_at', 'desc')->paginate(15);
        return view('admin.providers.index', compact('providers'));
    }

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

    public function store(StoreProviderRequest $request)
    {
        DB::beginTransaction();
        try {
            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'role' => 'provider',
                'is_active' => $request->has('is_active'),
            ]);

            $logoPath = $request->hasFile('logo') 
                ? $request->file('logo')->store('logos', 'public') 
                : null;

            Provider::create([
                'user_id' => $user->id,
                '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 redirect()->route('admin.providers.index')->with('success', 'Provider created successfully.');
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->withInput()->with('error', 'Failed to create provider.');
        }
    }

    public function edit($uuid)
    {
        $provider = Provider::where('uuid', $uuid)->with('user')->firstOrFail();
        return view('admin.providers.edit', compact('provider'));
    }

    public function update(UpdateProviderRequest $request, $uuid)
    {
        $provider = Provider::where('uuid', $uuid)->firstOrFail();
        
        DB::beginTransaction();
        try {
            // Mise à jour des données utilisateur
            $userData = [
                'name' => $request->name,
                'email' => $request->email,
                'is_active' => $request->has('is_active'),
            ];
            
            // Mise à jour du mot de passe si fourni
            if ($request->filled('password')) {
                $userData['password'] = Hash::make($request->password);
            }
            
            $provider->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 redirect()->route('admin.providers.index')->with('success', 'Prestataire modifié avec succès.');
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->withInput()->with('error', 'Échec de la modification du prestataire.');
        }
    }

    public function destroy($uuid)
    {
        $provider = Provider::where('uuid', $uuid)->firstOrFail();
        
        DB::beginTransaction();
        try {
            if ($provider->logo) Storage::disk('public')->delete($provider->logo);
            $provider->delete();
            $provider->user->delete();
            
            DB::commit();
            return redirect()->route('admin.providers.index')->with('success', 'Provider deleted successfully.');
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Failed to delete provider.');
        }
    }
}
