<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\Products;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CartController extends Controller
{
    // public function addToCart(Request $request)
    // {
    //     $request->validate([
    //         'product_id' => 'required|exists:products,id',
    //         'quantity' => 'required|integer|min:1'
    //     ]);

    //     // Check if product already in cart
    //     $existingCart = Cart::where('user_id', Auth::id())
    //                         ->where('product_id', $request->product_id)
    //                         ->first();

    //     if ($existingCart) {
    //         $existingCart->update([
    //             'quantity' => $existingCart->quantity + $request->quantity
    //         ]);
    //     } else {
    //         // Cart::create([
    //         //     'user_id' => Auth::id(),
    //         //     'size '=> $request->size,
    //         //     'product_id' => $request->product_id,
    //         //     'quantity' => $request->quantity
    //         // ]);

    //         $cart=new Cart();
    //         $cart->user_id=auth()->user()->id;
    //         $cart->size=$request->size;
    //         $cart->product_id=$request->product_id;
    //         $cart->quantity=$request->quantity;
    //         $cart->save();
    //     }

    //     return redirect()->back()->with('success', 'Product added to cart successfully!');
    // }

    public function addToCart(Request $request)
    {
        $productId = $request->input('product_id');
        $quantity  = $request->input('quantity', 1);
        $size      = $request->input('size');
    
        // 1) Session cart update
        $cart = session()->get('cart', []);
        if (isset($cart[$productId])) {
            $cart[$productId]['quantity'] += $quantity;
        } else {
            $product = Products::findOrFail($productId);
            $cart[$productId] = [
                'name'     => $product->name,
                'price'    => $product->price,
                'quantity' => $quantity,
                'image'    => $product->image,
                'size'     => $size,
            ];
        }
        session()->put('cart', $cart);
    
        // 2) DB cart update/create (without user_id)
        $existingCart = Cart::where('product_id', $productId)->first();
    
        if ($existingCart) {
            $existingCart->increment('quantity', $quantity);
        } else {
            // Cart::create([
            //     'product_id' => $productId,
            //     'quantity'   => $quantity,
            //     'size'       => $size,
            //     'user_id'    => Auth::check() ? Auth::id() : 0,
            // ]);
            $cart=new Cart();
                    $cart->user_id=Auth::check() ? Auth::id() : null;
                    $cart->size=$request->size;
                    $cart->product_id=$request->product_id;
                    $cart->quantity=$request->quantity;
                    $cart->save();
                
            
        }
    
        return redirect()->back()->with('success', 'Product added to cart!');
    }
    


    // public function viewCart()
    // {

    //     $cartItems = Cart::with('product')->where('user_id', Auth::id())->get();
    //     $products = Products::limit(6)->get();
    //     $user=auth()->user()->id;
    //     $cart=Cart::where('user_id',$user)->count();
    //     return view('cart.view', compact('cartItems','products','cart'));
    // }

    public function viewCart()
{
    $cartItems = session()->get('cart', []);
    $products = Products::limit(6)->get();
    $cart = count($cartItems);

    return view('cart.view', compact('cartItems', 'products', 'cart'));
}


    // public function removeFromCart(Cart $cart)
    // {
    //     $cart->delete();
    //     return redirect()->back()->with('success', 'Product removed from cart!');
    // }

    public function updateCart(Request $request, $id)
    {
        $cart = session()->get('cart', []);
        
        if(isset($cart[$id])) {
            $quantity = (int)$request->input('quantity');
            
            // Ensure quantity is at least 1
            $cart[$id]['quantity'] = max(1, $quantity);
            
            session()->put('cart', $cart);
            
            // Also update database if user is logged in
            if(Auth::check()) {
                $dbCart = Cart::where('product_id', $id)
                            ->where('user_id', Auth::id())
                            ->first();
                            
                if($dbCart) {
                    $dbCart->update(['quantity' => $cart[$id]['quantity']]);
                }
            }
            
            return redirect()->back()->with('success', 'Cart updated!');
        }
        
        return redirect()->back()->with('error', 'Product not found in cart!');
    }
    
    public function removeFromCart($id)
    {
        $cart = session()->get('cart');
        
        if(isset($cart[$id])) {
            unset($cart[$id]);
            session()->put('cart', $cart);
            
            // Also remove from database if user is logged in
            if(Auth::check()) {
                Cart::where('product_id', $id)
                    ->where('user_id', Auth::id())
                    ->delete();
            }
            
            return redirect()->back()->with('success', 'Item removed from cart!');
        }
        
        return redirect()->back()->with('error', 'Item not found in cart!');
    }
}