<?php

namespace App\Http\Controllers;

use App\Http\Requests\Member\Cart\MemberCartRequest;
use App\Http\Requests\Member\Cart\UpdateMemberCartRequest;
use App\Models\Cart;
use App\Repositories\Member\Cart\MemberCartRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CartController extends Controller
{
    public function count(Request $request, MemberCartRepository $repository)
    {
        $count = $repository->getCount($request->input('location_id'));
 
        return response()->json([
            'count' => $count,
        ]);
    }

    public function index(Request $request, MemberCartRepository $repository)
    {

        $request->merge(['location_id' => $request->input('location_id', session('location_id', 22))]);

        $carts = $repository->getList($request);

        // Log::info($items);
        return view('checkout.v1-cart',[
            'carts' => $carts
        ]);
    }

    public function add(MemberCartRequest $request, MemberCartRepository $repository)
    {
        // Log::info($request->all());
        $data = $request->validated();
        $item = $repository->create($data);

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Item added to cart successfully',
                'item' => $item
            ]);
        }

        return redirect()->route('cart.index');
    }

    public function update($cart_id, UpdateMemberCartRequest $request, MemberCartRepository $repository)
    {
        $data = $request->validated();
        $item = $repository->update($cart_id, $data);

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Cart updated successfully',
                'item' => $item
            ]);
        }

        return redirect()->route('cart.index');
    }

    public function delete($cart_id, MemberCartRepository $repository)
    {
        $repository->delete($cart_id);

        if (request()->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Item removed from cart successfully'
            ]);
        }

        return redirect()->route('cart.index');
    }

    public function clear(MemberCartRepository $repository)
    {
        $repository->clearAll();

        if (request()->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Cart cleared successfully'
            ]);
        }

        return redirect()->route('cart.index');
    }
}
