<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Services\ShippingService;
use Illuminate\Http\Request;

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

        foreach ($cart as $itemKey => $cartItem) {
            // Handle both old and new cart formats
            if (is_array($cartItem)) {
                $productId = $cartItem['product_id'] ?? null;
                $type = $cartItem['type'] ?? 'wallpaper';
                $printStockId = $cartItem['print_stock_id'] ?? null;
            } else {
                // Old format: just the product ID
                $productId = $itemKey;
                $type = 'wallpaper';
                $printStockId = null;
            }

            if ($productId) {
                $product = Product::find($productId);
                if ($product) {
                    $quantity = is_array($cartItem) ? ($cartItem['quantity'] ?? 1) : $cartItem;
                    $isSample = is_array($cartItem) ? ($cartItem['is_sample'] ?? false) : false;
                    $stockCost = 0;
                    $stock = null;
                    
                    // For samples, use fixed sample cost
                    if ($isSample) {
                        $itemTotal = ShippingService::getSampleCost() * $quantity;
                    } else {
                        // Get print stock if available
                        if ($printStockId) {
                            $stock = $product->printStocks()->find($printStockId);
                            if ($stock) {
                                $stockCost = ($type === 'wallpaper') ? $stock->cost_per_meter : $stock->cost_per_m2;
                            }
                        }
                        
                        // Calculate price based on stock cost only (no base design cost)
                        $basePrice = $stockCost;
                        
                        if ($type === 'wallpaper') {
                            $length = is_array($cartItem) ? ($cartItem['length'] ?? 0) : 0;
                            $itemTotal = $basePrice * $length * $quantity;
                        } elseif ($type === 'mural') {
                            $width = is_array($cartItem) ? ($cartItem['width'] ?? 0) : 0;
                            $height = is_array($cartItem) ? ($cartItem['height'] ?? 0) : 0;
                            $m2 = $width * $height;
                            $itemTotal = $basePrice * $m2 * $quantity;
                        } else {
                            $itemTotal = $basePrice * $quantity;
                        }
                    }

                    $total += $itemTotal;
                    $items[] = [
                        'key' => $itemKey,
                        'product' => $product,
                        'stock' => $stock,
                        'quantity' => $quantity,
                        'type' => $type,
                        'is_sample' => $isSample,
                        'length' => is_array($cartItem) ? ($cartItem['length'] ?? null) : null,
                        'width' => is_array($cartItem) ? ($cartItem['width'] ?? null) : null,
                        'height' => is_array($cartItem) ? ($cartItem['height'] ?? null) : null,
                        'subtotal' => $itemTotal
                    ];
                }
            }
        }

        $shippingFee = ShippingService::calculateShippingFee($total);
        $shippingLabel = ShippingService::getShippingLabel($total);

        return view('cart', [
            'items' => $items,
            'total' => $total,
            'shippingFee' => $shippingFee,
            'shippingLabel' => $shippingLabel,
            'itemCount' => count($cart)
        ]);
    }

    public function add(Request $request, Product $product)
    {
        $request->validate([
            'print_stock_id' => 'required|exists:print_stocks,id',
            'length' => $product->type === 'wallpaper' ? 'required|numeric|min:0.5' : 'nullable',
            'width' => $product->type === 'mural' ? 'required|numeric|min:0.5' : 'nullable',
            'height' => $product->type === 'mural' ? 'required|numeric|min:0.5' : 'nullable',
        ]);

        $cart = session()->get('cart', []);
        $cartItemKey = $product->id . '_' . $request->input('print_stock_id') . '_' . uniqid();

        // Create a unique cart item with dimensions and stock
        $cartItem = [
            'product_id' => $product->id,
            'print_stock_id' => $request->input('print_stock_id'),
            'quantity' => 1,
            'type' => $product->type,
        ];

        if ($product->type === 'wallpaper') {
            $cartItem['length'] = $request->input('length');
        } elseif ($product->type === 'mural') {
            $cartItem['width'] = $request->input('width');
            $cartItem['height'] = $request->input('height');
        }

        $cart[$cartItemKey] = $cartItem;
        session()->put('cart', $cart);

        return redirect()->back()->with('success', $product->name . ' added to cart!');
    }

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

        $cart = session()->get('cart', []);
        $itemKey = $request->input('item_key');
        $quantity = $request->input('quantity');

        if (isset($cart[$itemKey])) {
            $cart[$itemKey]['quantity'] = $quantity;
        }

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

        return redirect()->back()->with('success', 'Cart updated!');
    }

    public function remove(Request $request)
    {
        $itemKey = $request->input('item_key');
        $cart = session()->get('cart', []);
        
        if (isset($cart[$itemKey])) {
            unset($cart[$itemKey]);
        }
        
        session()->put('cart', $cart);

        return redirect()->back()->with('success', 'Product removed from cart!');
    }

    public function clear()
    {
        session()->forget('cart');
        return redirect()->back()->with('success', 'Cart cleared!');
    }

    /**
     * Order a sample of a product
     */
    public function orderSample(Request $request, Product $product)
    {
        $request->validate([
            'print_stock_id' => 'required|exists:print_stocks,id',
        ]);

        // Create a sample cart item 
        $cart = session()->get('cart', []);
        $sampleSize = 0.3;

        $cartItemKey = $product->id . '_sample_' . $request->input('print_stock_id') . '_' . uniqid();

        $cartItem = [
            'product_id' => $product->id,
            'print_stock_id' => $request->input('print_stock_id'),
            'quantity' => 1,
            'type' => $product->type,
            'is_sample' => true,
        ];

        if ($product->type === 'wallpaper') {
            // For wallpaper samples: use 30cm length (0.3m) with default width
            $cartItem['width'] = 0.3;
            $cartItem['height'] = 0.3;
        } elseif ($product->type === 'mural') {
            // For mural samples: use 6cm × 5cm (0.06m × 0.05m = 0.003m²)
            $cartItem['width'] = 0.3;
            $cartItem['height'] = 0.3;
        }

        $cart[$cartItemKey] = $cartItem;
        session()->put('cart', $cart);

        return redirect()->route('cart')->with('success', 'Sample added to cart!');
    }
}
