<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\Service;
use Darryldecode\Cart\Facades\CartFacade as Cart;

class CartController extends Controller
{
    public function addToCart(Request $request)
    {
        $request->validate([
            'item_id' => 'required|string',
            'item_type' => 'required|string|in:product,service,team',
            'quantity' => 'nullable|integer|min:1',
        ]);

        $item_id = $request->input('item_id');
        $item_type = $request->input('item_type');
        $quantity = $request->input('quantity', 1);

        $model = null;
        if ($item_type === 'product') {
            $model = Product::find($item_id);
        } elseif ($item_type === 'service') {
            $model = Service::find($item_id);
        } elseif ($item_type === 'team') {
            $teamMember = \App\Models\Team::find($item_id);
            if ($teamMember) {
                $model = new Service([
                    'id' => 'team-' . $teamMember->id,
                    'name' => 'Consultation with ' . $teamMember->name,
                    'price' => 50, // Assuming a fixed price for consultation
                    'image_urls' => [$teamMember->image_url],
                ]);
            }
        }

        if (!$model) {
            return redirect()->back()->with('error', 'Item not found.');
        }

        Cart::add([
            'id' => $model->id,
            'name' => $model->name,
            'price' => $model->price,
            'quantity' => $quantity,
            'attributes' => [
                'type' => $item_type,
                'image_urls' => $model->image_urls,
            ]
        ]);

        return redirect()->back()->with('success', 'Item added to cart.');
    }

    public function viewCart()
    {
        return inertia('Cart/View', [
            'cartItems' => Cart::getContent(),
            'cartTotal' => Cart::getTotal(),
        ]);
    }

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

        Cart::update($rowId, [
            'quantity' => [
                'relative' => false,
                'value' => $request->input('quantity'),
            ],
        ]);

        return redirect()->back()->with('success', 'Cart item quantity updated.');
    }

    public function removeItem(Request $request, $rowId)
    {
        Cart::remove($rowId);

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