<?php

namespace App\Http\Controllers\Seller;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use App\Models\UserAddress;

class ProfileController extends Controller
{
    public function index()
    {
        $seller = Auth::user()->seller;
        $addresses = UserAddress::where('user_id', Auth::id())->get();
        
        return view('seller.profile.index', compact('seller', 'addresses'));
    }

    public function update(Request $request)
    {
        $seller = Auth::user()->seller;
        $user = Auth::user();

        $validated = $request->validate([
            'shop_name' => 'required|string|max:255',
            'description' => 'nullable|string|max:1000',
            'phone' => 'required|string|max:20',
            'whatsapp' => 'nullable|string|max:20',
            'email' => 'required|email',
            'address' => 'required|string',
            'city' => 'required|string|max:255',
            'country' => 'required|string|max:255',
            'business_type' => 'nullable|string|in:individual,company,association',
            'business_name' => 'nullable|string|max:255',
            'business_registration' => 'nullable|string|max:100',
            'tax_id' => 'nullable|string|max:100',
            'logo' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
            'banner' => 'nullable|image|mimes:jpg,jpeg,png|max:5120',
        ]);

        // Upload logo si fourni - Nom lisible
        if ($request->hasFile('logo')) {
            if ($seller->logo) {
                Storage::disk('public')->delete($seller->logo);
            }
            $logoFile = $request->file('logo');
            $logoName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $logoFile->getClientOriginalName());
            $validated['logo'] = $logoFile->storeAs('sellers/logos', $logoName, 'public');
        }

        // Upload banner si fourni - Nom lisible
        if ($request->hasFile('banner')) {
            if ($seller->banner) {
                Storage::disk('public')->delete($seller->banner);
            }
            $bannerFile = $request->file('banner');
            $bannerName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $bannerFile->getClientOriginalName());
            $validated['banner'] = $bannerFile->storeAs('sellers/banners', $bannerName, 'public');
        }

        $seller->update($validated);

        // Mettre à jour aussi les infos utilisateur
        $user->update([
            'phone' => $validated['phone'],
            'address' => $validated['address'],
            'city' => $validated['city'],
            'country' => $validated['country'],
        ]);

        // Mettre à jour l'adresse par défaut
        $defaultAddress = UserAddress::where('user_id', Auth::id())->where('is_default', true)->first();
        if ($defaultAddress) {
            $defaultAddress->update([
                'phone' => $validated['phone'],
                'address' => $validated['address'],
                'city' => $validated['city'],
                'country' => $validated['country'],
            ]);
        }

        return back()->with('success', 'Profil mis à jour avec succès.');
    }

    public function updatePassword(Request $request)
    {
        $request->validate([
            'current_password' => 'required',
            'password' => 'required|string|min:6|confirmed',
        ]);

        $user = Auth::user();

        if (!Hash::check($request->current_password, $user->password)) {
            return back()->with('error', 'Le mot de passe actuel est incorrect.');
        }

        $user->update([
            'password' => Hash::make($request->password),
        ]);

        return back()->with('success', 'Mot de passe modifié avec succès.');
    }

    // Gestion des adresses
    public function addresses()
    {
        $addresses = UserAddress::where('user_id', Auth::id())->get();
        return view('seller.profile.addresses', compact('addresses'));
    }

    public function storeAddress(Request $request)
    {
        $validated = $request->validate([
            'label' => 'required|string|max:100',
            'full_name' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'country' => 'required|string|max:255',
            'city' => 'required|string|max:255',
            'district' => 'nullable|string|max:255',
            'address' => 'required|string',
            'is_default' => 'boolean',
        ]);

        // Si c'est l'adresse par défaut, enlever le défaut des autres
        if ($request->is_default) {
            UserAddress::where('user_id', Auth::id())->update(['is_default' => false]);
        }

        $validated['user_id'] = Auth::id();
        UserAddress::create($validated);

        return back()->with('success', 'Adresse ajoutée avec succès.');
    }

    public function updateAddress(Request $request, UserAddress $address)
    {
        if ($address->user_id !== Auth::id()) {
            abort(403);
        }

        $validated = $request->validate([
            'label' => 'required|string|max:100',
            'full_name' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'country' => 'required|string|max:255',
            'city' => 'required|string|max:255',
            'district' => 'nullable|string|max:255',
            'address' => 'required|string',
            'is_default' => 'boolean',
        ]);

        if ($request->is_default) {
            UserAddress::where('user_id', Auth::id())->update(['is_default' => false]);
        }

        $address->update($validated);

        return back()->with('success', 'Adresse mise à jour avec succès.');
    }

    public function deleteAddress(UserAddress $address)
    {
        if ($address->user_id !== Auth::id()) {
            abort(403);
        }

        $address->delete();

        return back()->with('success', 'Adresse supprimée avec succès.');
    }

    public function setDefaultAddress(UserAddress $address)
    {
        if ($address->user_id !== Auth::id()) {
            abort(403);
        }

        UserAddress::where('user_id', Auth::id())->update(['is_default' => false]);
        $address->update(['is_default' => true]);

        return back()->with('success', 'Adresse par défaut mise à jour.');
    }

    /**
     * Mettre à jour les méthodes de paiement du seller
     */
    public function updatePayment(Request $request)
    {
        $seller = Auth::user()->seller;

        $validated = $request->validate([
            'payment_method' => 'required|string|in:mobile_money,wave,orange_money,bank_transfer',
            'mobile_money_provider' => 'nullable|string|in:mtn,moov,wave,orange',
            'mobile_money_number' => 'nullable|string|max:20',
            'bank_name' => 'nullable|string|max:255',
            'bank_account_number' => 'nullable|string|max:100',
            'bank_account_name' => 'nullable|string|max:255',
            'payment_details' => 'nullable|string|max:500',
        ]);

        $seller->update($validated);

        return back()->with('success', 'Informations de paiement mises à jour avec succès.');
    }
}
