<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\CartModifier;
use App\Models\Modifier;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Yoeunes\Toastr\Facades\Toastr;

class CartController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $userId = Auth::check() ? Auth::user()->id : null;
        $userIdMobile = $request->user_id;
        $sessionId = null;
        
        if ($request->wantsJson()) {
            $sessionId = $request->session_id;
        } else {
            $sessionId = Session::getId();
        }


        $cart_data = Cart::where(function ($query) use ($userId, $sessionId,$userIdMobile) {
            if ($userId) {
                return $query->where('user_id', $userId);
            }
            if($userIdMobile != null){
                return $query->where('user_id', $userIdMobile);
            }
            if($sessionId != null){
                return $query->where('session_id', $sessionId);
            }
        })
            ->with('dish','modifiers')
            ->get();

        if ($request->wantsJson()) {
            $modifier_sum = 0;
            
            foreach($cart_data as $cart){
                $cart['sub_total'] = $cart->price * $cart->quantity;
                $modifiers = [];
                
                if(count($cart->modifiers) > 0 ){
                    foreach($cart->modifiers as $modifier){
                        $modifier = Modifier::where('MIM_ID',$modifier->MIM_ID)->first();
                        
                        $modifier_sum += $modifier->Rate;
                        
                        $mod = new \stdClass();
                        $mod->id = $modifier->MIM_ID;
                        $mod->name = $modifier->ModifierName . ' ( £' . $modifier->Rate . ')';
                        $modifiers[] = $mod;
                    }
                    $cart['mods'] = $modifiers;
                }
            }
            $grand_total = $cart_data->sum('sub_total') + $modifier_sum;
            return response()->json(['data'=>$cart_data,'grand_total'=>$grand_total]);
        }

        return view('cart.index', compact('cart_data'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $user_id = null;
        if (Auth::user()) {
            $user_id = Auth::user()->id;
        }
        if($request->id != null){
            $user_id = $request->id;
        }

        if ($request->wantsJson()) {
            $session_id = $request->session_id;
        } else {
            $session_id = session()->getId();
        }

        $dish_id = $request->dish_id;
        $dish_name = $request->dish_name;
        $quantity = $request->quantity;
        $price = $request->price;

        if ($user_id != null) {
            Cart::updateOrCreate([
                'user_id' => $user_id,
                'dish_id' => $dish_id,
                'dish_name' => $dish_name,
                'price' => $price
            ], [
                'quantity' => $quantity,
            ]);
        } else {
            Cart::updateOrCreate([
                'session_id' => $session_id,
                'dish_id' => $dish_id,
                'dish_name' => $dish_name,
                'price' => $price
            ], [
                'quantity' => $quantity,
            ]);
        }

        Toastr::success('Item added to the cart successfully', 'Success');
        return response()->json(['message' => 'Item added to the cart successfully']);
    }

    /**
     * Display the specified resource.
     */
    public function show(Cart $cart)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Cart $cart)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request)
    {
        $cart_id = $request->id;

        $cart = Cart::where('id', $cart_id)->first();

        $cart->quantity = $request->quantity;
        $cart->save();

        return response()->json(200);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request)
    {
        $user_id = null;
        if (Auth::user()) {
            $user_id = Auth::user()->id;
        }
        if($request->id != null)
        {
            $user_id = $request->id;
        }
        $session_id = session()->getId();

        if ($user_id != null) {
            Cart::where('user_id', $user_id)->delete();
        } else {
            Cart::where('session_id', $session_id)->delete();
        }
        
        if($request->wantsJson())
        {
            return response()->json(200);
        }

        return redirect()->route('cart.index')->with('success', 'Your cart has been cleared');
    }

    public function remove(Request $request)
    {
        $user_id = null;
        if (Auth::user()) {
            $user_id = Auth::user()->id;
        }
        if($request->id != null){
            $user_id = $request->id;
        }
        $session_id = session()->getId();

        if (Auth::user()) {
            Cart::where('user_id', $user_id)->where('id', $request->id)->delete();
        } else {
            Cart::where('session_id', $session_id)->where('id', $request->id)->delete();
        }

        return redirect()->route('cart.index')->with('success', 'Your cart has been cleared');
    }

    public function removeDish(Request $request)
    {
        $dish_id = $request->dish_id;
        $user_id = $request->user_id;
        if($request->id != null){
            $user_id = $request->id;
        }
        $session_id = $request->session_id;
        
        $cart = Cart::where(function ($query) use ($user_id, $session_id) {
            return $query->where('user_id', $user_id)->orwhere('session_id', $session_id);
        })->where('dish_id', $dish_id)->first();
        
        CartModifier::where('cart_id',$cart->id)->delete();
        $cart->delete();

        return response()->json('Item removed from cart');
    }
    
    public function addModifier(Request $request){
        $modifier_ids = $request->modifier;
        
        // $modifiers = Modifier::whereIn('MIM_ID',$modifier_ids)->pluck('ModifierName');
        
        foreach($modifier_ids as $modifier){
            CartModifier::updateOrCreate([
                'cart_id' => $request->id,
                'MIM_ID' => $modifier
                ]);
            // CartModifier::where('id', $request->id)->update([
            // 'dish_name' => \DB::raw("CONCAT(dish_name, ' $modifier')")
            // ]);
        }
        
        return response()->json(200);
    }
}