<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\AdminModels\Product;
use App\Models\AdminModels\CouponCode;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
use Carbon\Carbon;
use DB;
use App\Models\Cart;

class CartController
{
    public function addCart(Request $request){
        
        $user = $userId = (Auth::guard('user')->check()) ? Auth::guard('user')->id() : Session::get('guest_session_id');
        
        $product = Product::findOrFail($request->product_id);
        $cart = Cart::where('user_id', $user)->where('product_id', $request->product_id)
                ->first();

        if ($cart) {
            if($cart->quantity < $product->stock){
            $cart->quantity += 1;
            $cart->stock = $product->stock;
            $cart->sub_total = $cart->price*$cart->quantity;
            $cart->save();
            $status = true;
            }
            else{
                $status = false;
            }
        } else {
            // Check if user is logged in
            $userId = (Auth::guard('user')->check()) ? Auth::guard('user')->id() : null;

            // Handle guest session ID
            if (!$userId) {
                if (!Session::has('guest_session_id')) {
                    Session::put('guest_session_id', Str::uuid()->toString());
                }
                $userId = Session::get('guest_session_id');
            }
            $cartsave = new Cart;
            $cartsave->user_id = $userId;
            $cartsave->quantity = 1;
            $cartsave->stock = $product->stock ?? 1;
            $cartsave->product_id = $request->product_id;
            if($product->selling_price && $product->selling_price != 0){
               $cartsave->price = $product->selling_price;
            }
            else{
               $cartsave->price = $product->mrp;
            }
            
            $cartsave->sub_total = $cartsave->price;
            $cartsave->save();
            $status = true;

        }
        
        return redirect()->route('cart')->with('status', $status);
    }

    public function cart(Request $request)
    {
        $userId = (Auth::guard('user')->check()) ? Auth::guard('user')->id() : null;
        if (!$userId) {
            if (!Session::has('guest_session_id')) {
                Session::put('guest_session_id', Str::uuid()->toString());
            }
            $userId = Session::get('guest_session_id');
        }
        // dd($userId);
        $aa = Cart::where('user_id', $userId)
            ->whereHas('product', function ($q) {
                $q->where('stock', 0);
            })->delete();

        $cart = Cart::select("*")
            ->where('user_id', $userId)
            ->where('stock', '<>', 0)
            ->with([ 'product.category' => function ($q) {
                $q->select('id', 'slug');
            }, 'product'=> function ($q) {
                $q->select('id', 'name', 'featured_image', 'size', 'color', 'mrp', 'selling_price', 'sub_sku', 'slug', 'product_id', 'category_id');
            }])
            ->get();        
        // dd($cart[0]->product->category->slug);
        $productId = $cart->pluck('product_id')->values()->all();
        $products = Product::select('id', 'category_id', 'stock', 'mrp', 'selling_price')
            ->with('category:id,name')
            ->whereIn('id', $productId)
            ->get()
            ->keyBy('id');

        $subtotalmrp = 0;
        foreach ($cart as $cartItem) {
            $product = $products[$cartItem->product_id] ?? null;

            if ($product) {
                $price = ($product->selling_price && $product->selling_price != 0)
                    ? $product->selling_price
                    : $product->mrp;

                    $quantity = $cartItem->quantity > $product->stock ? $product->stock : $cartItem->quantity; 
                    $subt = $quantity * $price;
                    $cartItem->update([
                    'price' => $price,
                    'quantity' => $quantity,
                    'sub_total' => $subt,
                    'stock' => $product->stock
                ]);
                                
                $subtotalmrp += $product->mrp * $cartItem->quantity;
            }
        }

        $sub_total = $cart->sum('sub_total');
        
        $apply_coupon = $this->applyCoupon($userId, $productId, $request->coupon_code, $products, $subtotalmrp, $sub_total);
        
        $coupon_code_price = $apply_coupon['coupon_code_price'];
        $total_discount = ($subtotalmrp - $sub_total) + $coupon_code_price;
        $coupon = $apply_coupon['coupon'] ?? '';
        $msg = $apply_coupon['msg'];

        return view('cart', compact('cart', 'sub_total', 'subtotalmrp', 'coupon_code_price', 'coupon', 'total_discount', 'msg'));
    }

    

    public function applyCoupon($userId, $productId, $couponcode, $products, $subtotalmrp, $sub_total){
        // Coupon Code logic
        $coupon_code_price = 0;
        $msg = '';
        // Get coupon code either from request or session
        if ($couponcode && !empty($couponcode)) {
            $coupon = $couponcode;

            Session::forget('coupon_code');
            Session::forget('coupon_discount');
        } else {
            $coupon = Session::get('coupon_code');
        }

        // If there's a coupon to check
        if ($coupon){
            $coupon_code = CouponCode::where('coupon_code', $coupon)->first();
           
            if ($coupon_code) {
                $isValid = Carbon::parse($coupon_code->expiry_date)->isToday() || Carbon::parse($coupon_code->expiry_date)->isFuture();

                if ($isValid) {
                    // $used_times = Cart::where('user_id', $userId)
                    //     ->where('coupon_code', $coupon_code->coupon_code)
                    //     ->sum('applicable_times');
                    
                    // $total = $subtotalmrp - ($subtotalmrp - $sub_total);
                    $validCouponApplied = false;

                    foreach ($products as $prod) {
                        if ($prod->category && $prod->category->name === $coupon_code->applicable_on || $coupon_code->applicable_on === 'all') {
                            // Calculate total based on applicable category
                            $total = 0;
                            if ($coupon_code->applicable_on === 'all') {
                                $total = $sub_total; // full cart subtotal
                            } else {
                                $products_cat_wise = Product::select('id', 'category_id', 'stock', 'mrp', 'selling_price')
                                    ->with(['category' => function ($q) use ($coupon_code) {
                                        $q->select('id', 'name')->where('name', $coupon_code->applicable_on);
                                    }])
                                    ->whereIn('id', $productId)
                                    ->get()
                                    ->keyBy('id');

                                foreach ($products_cat_wise as $prod) {
                                    if ($prod->category && $prod->category->name === $coupon_code->applicable_on) {
                                        $cartItem = Cart::where('user_id', $userId)->where('product_id', $prod->id)->first();
                                        if ($cartItem) {
                                            $total += $cartItem->sub_total;
                                        }
                                    }
                                }
                            }
                          
                            if ($total >= $coupon_code->min_card_value) {
                                $max_discount = ($total * $coupon_code->max_discount) / 100;
                                $coupon_code_price = min($max_discount, $coupon_code->max_discount_value);
                                
                            } else {
                                Session::forget('coupon_code');
                                Session::forget('coupon_discount');
                              
                                $msg = "Minimum cart value must be ₹{$coupon_code->min_card_value} to apply this coupon.";
                            }

                            // Save coupon session values
                            Session::put('coupon_code', $coupon_code->coupon_code);
                            Session::put('coupon_discount', $coupon_code_price);

                            Cart::where('user_id', $userId)
                                ->where('product_id', $prod->id)
                                ->update([
                                    'coupon_code' => $coupon_code->coupon_code,
                                    'applicable_times' => DB::raw('applicable_times + 1'),
                                ]);

                            $validCouponApplied = true;
                            break;
                        }
                    }

                    if (!$validCouponApplied) {
                        Session::forget('coupon_code');
                        Session::forget('coupon_discount');
                        $msg = "Invalid coupon code.";
                    }
                } else {
                    Session::forget('coupon_code');
                    Session::forget('coupon_discount');
                    $msg = "Coupon code has expired.";
                }
            } else {
                Session::forget('coupon_code');
                Session::forget('coupon_discount');
                $msg = "Coupon code not found.";
            }
        }

        // Fallback to session coupon_discount
        // $coupon_code_price = $coupon_code_price ?: Session::get('coupon_discount', 0);
        // dd($subtotalmrp);
        $total_discount = ($subtotalmrp - $sub_total) + $coupon_code_price;
        $coupon = $coupon ?? '';

        return [
            'msg' => $msg,
            'coupon_code_price' => $coupon_code_price,
            'total_discount' => $total_discount,
            'coupon' => $coupon
        ];
    }

    public function updateCart(Request $request, $id){
        $request->validate([
        'quantity' => 'required|integer|min:1',
        ]);
        $cart = Cart::findOrFail($id);

        $cart->quantity = $request->quantity;
        $cart->sub_total = $cart->price*$request->quantity;
        $cart->save();
        Session::forget('coupon_code');
        return redirect()->route('cart');
    }

    public function deleteCart($id){
        
        $cart = Cart::where('id', $id)->first();
        $cart->delete();
        Session::forget('coupon_code');
        return redirect()->route('cart');
    }
}
