<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\{Contact, Cart, User, ProductCategory, About};
use Session;

class CartController extends Controller
{
    public function index(Request $request, User $user){
        $q_name = $request->q_name;
        $q_category_id = $request->q_category_id;
        $product_category = ProductCategory::limit(5)->get();
        $contact = Contact::first();
        $about = About::first();

        if (!auth()->check()) {
            return redirect()->route('login');
        }

        $cart = Cart::where('user_id', auth()->user()->id)->get();
        $cartTotal = 0;

        foreach ($cart as $item) {
            if ($item->product->is_discount) {
                $item->product->price * (1 - $item->product->discount_price / 100) * $item->amount;
            }else{
                $cartTotal += $item->product->price * $item->amount;
            }
        }

        return view('apps.web.cart')->with('cart', $cart)
                                    ->with('contact', $contact)
                                    ->with('cartTotal', $cartTotal)
                                    ->with('about', $about)
                                    ->with('product_category', $product_category)
                                    ->with('q_category_id', $q_category_id)
                                    ->with('q_name', $q_name);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function insert(Request $request)
    {
        $data = $request->all();

        if (!auth()->check()) {
            return redirect()->route('login');
        }

        $data['user_id'] = auth()->user()->id;        

        $cart = Cart::create($data);

        Session::flash('flash_message', 'Data telah ditambah');
        return redirect()->route('cart');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function delete(Request $request)
    {
        $cart = Cart::findOrFail($request->id);
        $cart->delete();
        
        return redirect()->back();
    }
}
