<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Services\CartService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class CartController extends Controller
{

    public function index()
    {
        $cart = session()->get('cart', []);
        $total = 0;
        $subtotal = 0;

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

        // Calculate total (you can add shipping, tax, etc. here)
        $total = $subtotal;

        return view('cart.index', [
            'cartItems' => $cart,
            'subtotal' => $subtotal,
            'total' => $total
        ]);
    }

    public function __construct()
    {
        $this->middleware('web');
    }

    public function add(Request $request, Product $product)
{
    $cart = Session::get('cart', []);
    $quantity = $request->input('quantity', 1);
    
    if (isset($cart[$product->id])) {
        $cart[$product->id]['quantity'] += $quantity;
    } else {
        $cart[$product->id] = [
            'id' => $product->id,
            'name' => $product->name,
            'price' => $product->sale_price ?? $product->price,
            'quantity' => $quantity,
            'image' => $product->images->first() ? $product->images->first()->path : 'placeholder.jpg'
        ];
    }
    
    Session::put('cart', $cart);
    Session::save();

    $totalItems = collect($cart)->sum('quantity');

    // Check if request is AJAX
    if ($request->ajax() || $request->wantsJson()) {
        return response()->json([
            'success' => true,
            'message' => 'Product added to cart successfully!',
            'cartCount' => $totalItems
        ]);
    }

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

    // public function add(Request $request, Product $product)
    // {
    //     $cart = Session::get('cart', []);
    //     $quantity = $request->input('quantity', 1);
        
    //     if (isset($cart[$product->id])) {
    //         $cart[$product->id]['quantity'] += $quantity;
    //     } else {
    //         $cart[$product->id] = [
    //             'id' => $product->id,
    //             'name' => $product->name,
    //             'price' => $product->sale_price ?? $product->price,
    //             'quantity' => $quantity,
    //             'image' => $product->images->first() ? $product->images->first()->path : 'placeholder.jpg'
    //         ];
    //     }
        
    //     Session::put('cart', $cart);
    //     Session::save();

    //     $totalItems = collect($cart)->sum('quantity');

    //     return response()->json([
    //         'success' => true,
    //         'message' => 'Product added to cart successfully!',
    //         'cartCount' => $totalItems
    //     ]);
    // }

    public function getCount()
    {
        $cart = Session::get('cart', []);
        return response()->json([
            'count' => collect($cart)->sum('quantity')
        ]);
    }
    
    /**
     * Show cart contents
     *
     * @return \Illuminate\View\View
     */
    public function show()
    {
        $cartItems = $this->cartService->getItems();
        $cartTotal = $this->cartService->getTotal();
        
        return view('cart.show', compact('cartItems', 'cartTotal'));
    }
    
    public function remove(Request $request, $productId)
{
    $cart = Session::get('cart', []);
    
    if (isset($cart[$productId])) {
        unset($cart[$productId]);
        Session::put('cart', $cart);
        Session::save();
        
        $totalItems = collect($cart)->sum('quantity');
        
        return response()->json([
            'success' => true,
            'message' => 'Item removed from cart successfully!',
            'cartCount' => $totalItems
        ]);
    }
    
    return response()->json([
        'success' => false,
        'message' => 'Item not found in cart'
    ], 404);
}

public function update(Request $request, $productId)
{
    $cart = Session::get('cart', []);
    $action = $request->input('action');
    
    if (isset($cart[$productId])) {
        if ($action === 'increase') {
            $cart[$productId]['quantity']++;
        } elseif ($action === 'decrease' && $cart[$productId]['quantity'] > 1) {
            $cart[$productId]['quantity']--;
        }
        
        Session::put('cart', $cart);
        Session::save();
        
        $totalItems = collect($cart)->sum('quantity');
        $subtotal = collect($cart)->sum(function($item) {
            return $item['price'] * $item['quantity'];
        });
        
        return response()->json([
            'success' => true,
            'message' => 'Cart updated successfully!',
            'cartCount' => $totalItems,
            'subtotal' => number_format($subtotal, 2),
            'total' => number_format($subtotal, 2) // Add tax/shipping if needed
        ]);
    }
    
    return response()->json([
        'success' => false,
        'message' => 'Product not found in cart'
    ], 404);
}
    
    /**
     * Get cart count for AJAX requests
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function count()
    {
        return response()->json([
            'count' => $this->cartService->getTotalQuantity(),
            'total' => $this->cartService->getTotal()
        ]);
    }

    public function empty()
    {
        session()->forget('cart');
        return response()->json(['success' => true]);
    }
    
    /**
     * Clear the cart
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function clear(Request $request)
    {
        $this->cartService->clear();
        
        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Cart cleared successfully!',
                'cartCount' => 0,
                'cartTotal' => 0.00
            ]);
        }
        
        return redirect()->back()->with('success', 'Cart cleared successfully!');
    }
}