<?php

namespace App\Http\Controllers\Seller;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Seller;
use App\Models\SellerMessage;
use Illuminate\Support\Facades\Schema;
use App\Services\NotificationService;

class KycController extends Controller
{
    public function index()
    {
        try {
            $seller = Seller::where('user_id', auth()->id())->first();
            $messages = [];
            
            if (Schema::hasTable('seller_messages')) {
                $messages = SellerMessage::where('seller_id', $seller->id)
                    ->with('user')
                    ->orderBy('created_at', 'desc')
                    ->get();
            }
            
            return view('seller.kyc.index', compact('seller', 'messages'));
        } catch (\Exception $e) {
            return back()->withError('Erreur: ' . $e->getMessage());
        }
    }

    public function store(Request $request)
    {
        $request->validate([
            'business_name' => 'required|string|max:255',
            'business_type' => 'required|string',
            'business_registration' => 'nullable|string',
            'tax_id' => 'nullable|string',
            'id_document' => 'required|file|mimes:jpg,jpeg,png,pdf|max:5120',
            'address_proof' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:5120',
            'business_document' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:5120',
            'business_photo' => 'nullable|file|mimes:jpg,jpeg,png|max:5120',
        ]);

        $seller = Seller::where('user_id', auth()->id())->first();
        
        // Utiliser storeAs avec nom lisible : timestamp_nomoriginal.ext
        $idDoc = $request->file('id_document');
        $idDocName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $idDoc->getClientOriginalName());
        $idDocPath = $idDoc->storeAs('kyc/' . $seller->id . '/id', $idDocName, 'public');
        
        $addressProofPath = null;
        if ($request->hasFile('address_proof')) {
            $addressDoc = $request->file('address_proof');
            $addressName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $addressDoc->getClientOriginalName());
            $addressProofPath = $addressDoc->storeAs('kyc/' . $seller->id . '/address', $addressName, 'public');
        }
            
        $businessDocPath = null;
        if ($request->hasFile('business_document')) {
            $businessDoc = $request->file('business_document');
            $businessName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $businessDoc->getClientOriginalName());
            $businessDocPath = $businessDoc->storeAs('kyc/' . $seller->id . '/business', $businessName, 'public');
        }
            
        $businessPhotoPath = null;
        if ($request->hasFile('business_photo')) {
            $photoDoc = $request->file('business_photo');
            $photoName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $photoDoc->getClientOriginalName());
            $businessPhotoPath = $photoDoc->storeAs('kyc/' . $seller->id . '/photo', $photoName, 'public');
        }

        $seller->update([
            'business_name' => $request->business_name,
            'business_type' => $request->business_type,
            'business_registration' => $request->business_registration,
            'tax_id' => $request->tax_id,
            'id_document' => $idDocPath,
            'address_proof' => $addressProofPath,
            'business_document' => $businessDocPath,
            'business_photo' => $businessPhotoPath,
            'kyc_status' => 'submitted', // Documents soumis, en attente de vérification
            'kyc_submitted_at' => now(),
        ]);

        // Notification de soumission KYC
        NotificationService::sellerKycSubmitted(auth()->id());

        return redirect()->route('seller.kyc.index')
            ->with('success', 'Documents KYC soumis avec succes. En attente de verification.');
    }

    public function sendMessage(Request $request)
    {
        try {
            $request->validate([
                'message' => 'required|string|max:1000',
            ]);

            $seller = Seller::where('user_id', auth()->id())->first();

            if (!Schema::hasTable('seller_messages')) {
                return back()->withError('Service de messages non disponible.');
            }

            SellerMessage::create([
                'seller_id' => $seller->id,
                'user_id' => auth()->id(),
                'message' => $request->message,
                'is_admin' => false,
            ]);

            return back()->with('success', 'Message envoye au verificateur.');
        } catch (\Exception $e) {
            return back()->withError('Erreur: ' . $e->getMessage());
        }
    }
}
