<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Coupon;
use App\Models\Category;
use App\Models\Product;
use App\Models\Seller;
use App\Services\CouponService;
use Illuminate\Http\Request;

class CouponController extends Controller
{
    protected CouponService $couponService;

    public function __construct(CouponService $couponService)
    {
        $this->couponService = $couponService;
    }

    public function index(Request $request)
    {
        $query = Coupon::query();

        // Filtre par créateur (admin ou vendeur)
        if ($request->filled('created_by')) {
            $query->where('created_by_type', $request->created_by);
        }

        // Filtre par scope
        if ($request->filled('scope')) {
            $query->where('scope', $request->scope);
        }

        if ($request->filled('status')) {
            if ($request->status === 'active') {
                $query->where('is_active', true)->where(function($q) {
                    $q->whereNull('expires_at')->orWhere('expires_at', '>', now());
                });
            } else {
                $query->where(function($q) {
                    $q->where('is_active', false)->orWhere('expires_at', '<=', now());
                });
            }
        }

        $coupons = $query->latest()->paginate(20);
        
        // Scopes disponibles pour le filtre
        $scopes = [
            'all' => 'Tous les produits',
            'shop_only' => 'Boutique uniquement',
            'investment_only' => 'Investissement uniquement',
            'category' => 'Catégories spécifiques',
            'product' => 'Produits spécifiques',
            'seller' => 'Vendeurs spécifiques',
            'seller_own' => 'Produits du vendeur (coupons vendeur)'
        ];
        
        return view('admin.coupons.index', compact('coupons', 'scopes'));
    }

    public function create()
    {
        $categories = Category::where('is_active', true)->get();
        $sellers = Seller::where('is_verified', true)->with('user')->get();
        $products = Product::where('is_active', true)->select('id', 'name', 'seller_id')->limit(500)->get();
        
        $scopes = [
            Coupon::SCOPE_ALL => 'Tous les produits',
            Coupon::SCOPE_SHOP_ONLY => 'Produits boutique uniquement',
            Coupon::SCOPE_INVESTMENT_ONLY => 'Produits investissement uniquement',
            Coupon::SCOPE_CATEGORY => 'Catégories spécifiques',
            Coupon::SCOPE_PRODUCT => 'Produits spécifiques',
            Coupon::SCOPE_SELLER => 'Vendeurs spécifiques',
        ];
        
        return view('admin.coupons.create', compact('categories', 'sellers', 'products', 'scopes'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'code' => 'required|string|max:50|unique:coupons',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'type' => 'required|in:percentage,fixed,free_shipping',
            'value' => 'required|numeric|min:0',
            'min_order_amount' => 'nullable|numeric|min:0',
            'max_discount' => 'nullable|numeric|min:0',
            'usage_limit' => 'nullable|integer|min:1',
            'usage_per_user' => 'nullable|integer|min:1',
            'starts_at' => 'nullable|date',
            'expires_at' => 'nullable|date|after_or_equal:starts_at',
            'scope' => 'required|in:all,shop_only,investment_only,category,product,seller',
            'applicable_categories' => 'nullable|array',
            'applicable_categories.*' => 'exists:categories,id',
            'applicable_products' => 'nullable|array',
            'applicable_products.*' => 'exists:products,id',
            'applicable_sellers' => 'nullable|array',
            'applicable_sellers.*' => 'exists:sellers,id',
            'includes_free_shipping' => 'nullable|boolean'
        ]);

        try {
            $coupon = $this->couponService->createAdminCoupon(auth()->id(), [
                'code' => $request->code,
                'name' => $request->name,
                'description' => $request->description,
                'type' => $request->type,
                'value' => $request->value,
                'min_order_amount' => $request->min_order_amount ?? 0,
                'max_discount' => $request->max_discount,
                'usage_limit' => $request->usage_limit,
                'usage_per_user' => $request->usage_per_user,
                'starts_at' => $request->starts_at,
                'expires_at' => $request->expires_at,
                'scope' => $request->scope,
                'applicable_categories' => $request->applicable_categories,
                'applicable_products' => $request->applicable_products,
                'applicable_sellers' => $request->applicable_sellers,
                'includes_free_shipping' => $request->boolean('includes_free_shipping'),
                'is_active' => $request->boolean('is_active', true),
            ]);

            return redirect()->route('admin.coupons.index')
                ->with('success', 'Coupon créé avec succès');
        } catch (\InvalidArgumentException $e) {
            return back()->withInput()->with('error', $e->getMessage());
        }
    }

    public function show(Coupon $coupon)
    {
        $stats = $this->couponService->getCouponStats($coupon->id);
        
        // Charger les relations pour l'affichage
        $coupon->load(['seller.user', 'admin']);
        
        // Récupérer les noms des catégories/produits/vendeurs applicables
        $applicableCategories = [];
        $applicableProducts = [];
        $applicableSellers = [];
        
        if ($coupon->applicable_categories) {
            $applicableCategories = Category::whereIn('id', $coupon->applicable_categories)->pluck('name', 'id');
        }
        if ($coupon->applicable_products) {
            $applicableProducts = Product::whereIn('id', $coupon->applicable_products)->pluck('name', 'id');
        }
        if ($coupon->applicable_sellers) {
            $applicableSellers = Seller::whereIn('id', $coupon->applicable_sellers)->with('user')->get();
        }
        
        return view('admin.coupons.show', compact('coupon', 'stats', 'applicableCategories', 'applicableProducts', 'applicableSellers'));
    }

    public function edit(Coupon $coupon)
    {
        $categories = Category::where('is_active', true)->get();
        $sellers = Seller::where('is_verified', true)->with('user')->get();
        $products = Product::where('is_active', true)->select('id', 'name', 'seller_id')->limit(500)->get();
        
        $scopes = [
            Coupon::SCOPE_ALL => 'Tous les produits',
            Coupon::SCOPE_SHOP_ONLY => 'Produits boutique uniquement',
            Coupon::SCOPE_INVESTMENT_ONLY => 'Produits investissement uniquement',
            Coupon::SCOPE_CATEGORY => 'Catégories spécifiques',
            Coupon::SCOPE_PRODUCT => 'Produits spécifiques',
            Coupon::SCOPE_SELLER => 'Vendeurs spécifiques',
        ];
        
        return view('admin.coupons.edit', compact('coupon', 'categories', 'sellers', 'products', 'scopes'));
    }

    public function update(Request $request, Coupon $coupon)
    {
        $request->validate([
            'code' => 'required|string|max:50|unique:coupons,code,' . $coupon->id,
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'type' => 'required|in:percentage,fixed,free_shipping',
            'value' => 'required|numeric|min:0',
            'min_order_amount' => 'nullable|numeric|min:0',
            'max_discount' => 'nullable|numeric|min:0',
            'usage_limit' => 'nullable|integer|min:1',
            'usage_per_user' => 'nullable|integer|min:1',
            'starts_at' => 'nullable|date',
            'expires_at' => 'nullable|date',
            'scope' => 'required|in:all,shop_only,investment_only,category,product,seller,seller_own',
            'applicable_categories' => 'nullable|array',
            'applicable_products' => 'nullable|array',
            'applicable_sellers' => 'nullable|array',
            'includes_free_shipping' => 'nullable|boolean'
        ]);

        $data = [
            'code' => strtoupper($request->code),
            'name' => $request->name,
            'description' => $request->description,
            'type' => $request->type,
            'value' => $request->value,
            'min_order_amount' => $request->min_order_amount ?? 0,
            'max_discount' => $request->max_discount,
            'usage_limit' => $request->usage_limit,
            'usage_per_user' => $request->usage_per_user,
            'starts_at' => $request->starts_at,
            'expires_at' => $request->expires_at,
            'scope' => $request->scope,
            'applicable_categories' => $request->applicable_categories,
            'applicable_products' => $request->applicable_products,
            'applicable_sellers' => $request->applicable_sellers,
            'includes_free_shipping' => $request->boolean('includes_free_shipping'),
            'is_active' => $request->boolean('is_active', true),
        ];

        $coupon->update($data);

        return redirect()->route('admin.coupons.index')
            ->with('success', 'Coupon mis à jour avec succès');
    }

    public function destroy(Coupon $coupon)
    {
        $coupon->delete();
        return redirect()->route('admin.coupons.index')
            ->with('success', 'Coupon supprimé avec succès');
    }

    public function toggle(Coupon $coupon)
    {
        $coupon->update(['is_active' => !$coupon->is_active]);
        return redirect()->back()
            ->with('success', $coupon->is_active ? 'Coupon activé' : 'Coupon désactivé');
    }

    /**
     * API: Recherche de produits pour la sélection dans le formulaire
     */
    public function searchProducts(Request $request)
    {
        $query = $request->get('q', '');
        
        $products = Product::where('is_active', true)
            ->where(function($q) use ($query) {
                $q->where('name', 'LIKE', "%{$query}%")
                  ->orWhere('id', $query);
            })
            ->limit(50)
            ->get(['id', 'name', 'seller_id']);
        
        return response()->json($products);
    }
}
