<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use Session;
use Auth;
use Hash;
use Str;

class CartController extends Controller
{
    public function cart()
    {
        $session_id = Session::get('session_id');
        $data['count'] = DB::table('cart')->where(['session_id'=>$session_id])->count();
        $data['cartpro'] = DB::table('cart')->where(['session_id'=>$session_id])->get();
        $data['subtotal'] = DB::table('cart')->where(['session_id'=>$session_id])->sum('total');

        return view('web.cart', $data);
    }

	public function addtocart(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->all();

            $pro_data = DB::table('products')->where('id', $data['pro_id'])->first();

            $session_id = Session::get('session_id'); 
            if (empty($session_id)) {
                $session_id = Str::random(40);
                Session::put('session_id', $session_id);
            }

            $countProducts = DB::table('cart')->where(['product_id'=>$pro_data->id, 'session_id'=>$session_id])->count();

            if ($countProducts > 0) {
                toastr()->warning('Product already added into cart! Choose another products.');
                return redirect()->back();
            }else{
                $data1['product_id'] = $pro_data->id;
                $data1['title'] = $pro_data->title;
                $data1['image'] = $pro_data->image;
                $data1['price'] = $pro_data->price;
                $data1['qty'] = $data['qty'];
                $data1['total'] = $pro_data->price*$data['qty'];
                $data1['pv'] = $pro_data->point*$data['qty'];
                $data1['session_id'] = $session_id;
                $data1['status'] = 0;
                DB::table('cart')->insert($data1);

                toastr()->success('Product Added into Cart!');
                return redirect('cart');
            }

        }
    }

    public function cdelete($id)
    {
        DB::table('cart')->where('id', $id)->delete();
        return redirect()->back();
    }

    public function invoice($id)
    {
        $data['ord_data'] = DB::table('orders')->where('id', $id)->first();
        $data['user_data'] = DB::table('members')->where('username', $data['ord_data']->username)->first();
        $data['pro_data'] = DB::table('orders_products')->where('order_id', $data['ord_data']->id)->get();
        
        return view('web.invoice', $data);
    }

}