<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\Coupon;
use Illuminate\Http\Request;

class CartController extends Controller
{
    public function index()
    {
        $cart = session()->get('cart', []);
        $couponSession = session()->get('coupon');

        $subtotal = 0;
        foreach ($cart as $item) {
            $subtotal += $item['price'] * $item['quantity'];
        }

        $discount = 0;
        $activeCouponModel = null;

        if ($couponSession) {
            $couponModel = Coupon::where('code', $couponSession['code'])->first();
            if ($couponModel) {
                $validation = $couponModel->isValid($subtotal);
                if ($validation['valid']) {
                    $discount = $couponModel->calculateDiscount($subtotal);
                    $activeCouponModel = $couponModel;
                } else {
                    session()->forget('coupon');
                }
            }
        }

        // Fetch active available coupons for 1-click cart drawer
        $availableCoupons = Coupon::where('is_active', true)
            ->where(function($q) {
                $q->whereNull('expires_at')->orWhere('expires_at', '>', now());
            })
            ->latest()
            ->get();

        return view('pages.cart', [
            'cart' => $cart,
            'subtotal' => $subtotal,
            'discount' => $discount,
            'coupon' => $couponSession,
            'availableCoupons' => $availableCoupons,
        ]);
    }

    public function add(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'variant_id' => 'nullable|exists:product_variants,id',
            'quantity' => 'required|integer|min:1',
        ]);

        $product = Product::findOrFail($request->product_id);
        $variant = null;
        if ($request->filled('variant_id')) {
            $variant = ProductVariant::find($request->variant_id);
        }

        $price = $variant ? $variant->price : $product->price;
        $size = $variant ? $variant->name : 'Standard';
        $quantity = (int) $request->quantity;

        $cartKey = $product->id . '_' . ($variant ? $variant->id : '0');

        $cart = session()->get('cart', []);

        if (isset($cart[$cartKey])) {
            $cart[$cartKey]['quantity'] += $quantity;
        } else {
            $cart[$cartKey] = [
                'key' => $cartKey,
                'product_id' => $product->id,
                'variant_id' => $variant ? $variant->id : null,
                'name' => $product->name,
                'price' => (float) $price,
                'size' => $size,
                'quantity' => $quantity,
                'image' => $product->image,
                'slug' => $product->slug,
            ];
        }

        session()->put('cart', $cart);

        return redirect()->back()->with('success', "'{$product->name}' ({$size}) added to your shopping bag!");
    }

    public function update(Request $request)
    {
        $request->validate([
            'key' => 'required|string',
            'quantity' => 'required|integer|min:1',
        ]);

        $cart = session()->get('cart', []);
        if (isset($cart[$request->key])) {
            $cart[$request->key]['quantity'] = (int) $request->quantity;
            session()->put('cart', $cart);
        }

        return redirect()->route('cart')->with('success', 'Shopping bag updated.');
    }

    public function remove(Request $request)
    {
        $request->validate(['key' => 'required|string']);

        $cart = session()->get('cart', []);
        if (isset($cart[$request->key])) {
            unset($cart[$request->key]);
            session()->put('cart', $cart);
        }

        return redirect()->route('cart')->with('success', 'Item removed from shopping bag.');
    }

    public function applyCoupon(Request $request)
    {
        $request->validate(['code' => 'required|string']);

        $code = strtoupper(trim($request->code));
        $coupon = Coupon::where('code', $code)->first();

        if (!$coupon) {
            return redirect()->route('cart')->with('error', "Coupon code '{$code}' does not exist.");
        }

        $cart = session()->get('cart', []);
        $subtotal = 0;
        foreach ($cart as $item) {
            $subtotal += $item['price'] * $item['quantity'];
        }

        $validation = $coupon->isValid($subtotal);
        if (!$validation['valid']) {
            return redirect()->route('cart')->with('error', $validation['message']);
        }

        $discount = $coupon->calculateDiscount($subtotal);

        session()->put('coupon', [
            'code' => $coupon->code,
            'type' => $coupon->type,
            'value' => (float) $coupon->value,
            'max_discount_amount' => $coupon->max_discount_amount ? (float) $coupon->max_discount_amount : null,
            'discount_amount' => (float) $discount,
        ]);

        return redirect()->route('cart')->with('success', "Coupon '{$code}' applied successfully!");
    }

    public function removeCoupon()
    {
        session()->forget('coupon');
        return redirect()->route('cart')->with('success', 'Coupon code removed.');
    }
}
