<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Cookie;
use App\Models\add_to_cart;
use App\Models\Category;
use App\Models\insert_topping;
use App\Models\custregister;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Crypt;

class Controller extends BaseController
{
    public function product(Request $request, $slug)
    {
        $result['product'] =
            DB::table('products')
            ->where(['status' => 1])
            ->where(['slug' => $slug])
            ->first();

        if (!$result['product'])
            abort(404);

        $result['wings'] =
            DB::table('wings')
            ->where(['status' => 1])
            ->get();

        $result['sauces'] =
            DB::table('sauces')
            ->where(['status' => 1])
            ->get();

        $result['toppings'] =
            DB::table('toppings')
            ->where(['status' => 1])
            ->where(['toppings_type' => 'Small(4slice)'])
            ->get();

        $result['mediamtoppings'] =
            DB::table('toppings')
            ->where(['status' => 1])
            ->where(['toppings_type' => 'Medium(8slice)'])
            ->get();

        $result['largetoppings'] =
            DB::table('toppings')
            ->where(['status' => 1])
            ->where(['toppings_type' => 'Large(12slice)'])
            ->get();

        $result['partytoppings'] =
            DB::table('toppings')
            ->where(['status' => 1])
            ->where(['toppings_type' => 'Party(24slice)'])
            ->get();

        $result['pretoppings'] =
            DB::table('pretoppings')
            ->where(['status' => 1])
            ->where(['toppings_type' => 'Small(4slice)'])
            ->get();

        $result['mediam_pretoppings'] =
            DB::table('pretoppings')
            ->where(['status' => 1])
            ->where(['toppings_type' => 'Medium(8slice)'])
            ->get();

        $result['large_pretoppings'] =
            DB::table('pretoppings')
            ->where(['status' => 1])
            ->where(['toppings_type' => 'Large(12slice)'])
            ->get();

        $result['party_pretoppings'] =
            DB::table('pretoppings')
            ->where(['status' => 1])
            ->where(['toppings_type' => 'Party(24slice)'])
            ->get();

        $result['dippings'] =
            DB::table('dippings')
            ->where(['status' => 1])
            ->get();

        $result['crusts'] =
            DB::table('crusts')
            ->where(['status' => 1])
            ->get();

        $result['cookings'] =
            DB::table('cookings')
            ->where(['status' => 1])
            ->get();

        $result['sizes'] =
            DB::table('sizes')
            ->where(['status' => 1])
            ->where(['category_id' => $result["product"]->category_id])
            ->get();

        $result['sizescheck'] =
            DB::table('sizes')
            ->where(['status' => 1])
            ->first();

        // $result['sizescheck'] =
        //     DB::table('sizes')
        //     ->where(['status' => 1])
        //     ->get();
        // dd($result['sizes']);
        // foreach($result['product'] as $list1){
        //     $result['product_attr'][$list1->id]=
        //         DB::table('products_attr')
        //         ->leftJoin('sizes','sizes.id','=','products_attr.size_id')
        //         ->leftJoin('colors','colors.id','=','products_attr.color_id')
        //         ->where(['products_attr.products_id'=>$list1->id])
        //         ->get();
        // }

        // foreach($result['product'] as $list1){
        //     $result['product_images'][$list1->id]=
        //         DB::table('product_images')
        //         ->where(['product_images.products_id'=>$list1->id])
        //         ->get();
        // }


        // $result['related_product']=
        //     DB::table('products')
        //     ->where(['status'=>1])
        //     ->where('slug','!=',$slug)
        //     ->where(['category_id'=>$result['product'][0]->category_id])
        //     ->get();
        // foreach($result['related_product'] as $list1){
        //     $result['related_product_attr'][$list1->id]=
        //         DB::table('products_attr')
        //         ->leftJoin('sizes','sizes.id','=','products_attr.size_id')
        //         ->leftJoin('colors','colors.id','=','products_attr.color_id')
        //         ->where(['products_attr.products_id'=>$list1->id])
        //         ->get();
        // }

        // $result['product_review']=
        //         DB::table('product_review')
        //         ->leftJoin('customers','customers.id','=','product_review.customer_id')
        //         ->where(['product_review.products_id'=>$result['product'][0]->id])
        //         ->where(['product_review.status'=>1])
        //         ->orderBy('product_review.added_on','desc')
        //         ->select('product_review.rating','product_review.review','product_review.added_on','customers.name')
        //         ->get();
        //prx($result['product_review']);

        return view('front.singalproduct', $result);
    }

    public function shop(Request $request)
    {
        // $result['home_categories'] = DB::table('categories')
        //     ->where(['status' => 1])
        //     ->get();

        // $result['product'] =
        //     DB::table('products')
        //     ->where(['status' => 1])
        //     ->get();

        $category = Category::with('products')->get();
        // cart data 

        if ($request->session()->has('FRONT_USER_LOGIN')) {
            $uid = $request->session()->get('FRONT_USER_ID');
            $user_type = "Reg";
        } else {
            $uid = getUserTempId();
            $user_type = "Not-Reg";
        }
        $cartdatas = add_to_cart::query()->with('insert_topping')
            ->where(['user_id' => $uid])
            ->where(['user_type' => $user_type])
            ->where(['status' => null])
            ->get();

        $i = 0;
        foreach ($cartdatas as $cartdata) {
            if ($cartdata->category_id == 1) {


                $total_price = 0;
                $total_price = ($cartdata->product_price + $cartdata->ws_price + $cartdata->sauce_price + $cartdata->crust_price + $cartdata->dipping_price + $cartdata->cooking_price + $cartdata->size_price);
                foreach ($cartdata->insert_topping as $insert_topping) {
                    if ($insert_topping->sum('status') <= 3) {
                        $total_price += $insert_topping->toppings_left_id = 0 + $insert_topping->toppings_center_id = 0 + $insert_topping->toppings_right_id = 0 + $insert_topping->pretoppings_left_id = 0 + $insert_topping->pretoppings_center_id = 0 + $insert_topping->pretoppings_right_id = 0 ;
                    } else {
                        $total_price += $insert_topping->toppings_left_id + $insert_topping->toppings_center_id + $insert_topping->toppings_right_id + $insert_topping->pretoppings_left_id  + $insert_topping->pretoppings_center_id  + $insert_topping->pretoppings_right_id;
                    }
                }
            } else {
                $total_price = 0;
                $total_price = ($cartdata->product_price + $cartdata->ws_price + $cartdata->sauce_price + $cartdata->crust_price + $cartdata->dipping_price + $cartdata->cooking_price + $cartdata->size_price);
                foreach ($cartdata->insert_topping as $insert_topping) {
                    $total_price += $insert_topping->toppings_left_id + $insert_topping->toppings_center_id + $insert_topping->toppings_right_id + $insert_topping->pretoppings_left_id  + $insert_topping->pretoppings_center_id  + $insert_topping->pretoppings_right_id;
                }
            }

            $cartdatas[$i]->total_price = $total_price * $cartdata->pqty;
            $i++;
        }

        return view('front.shop', compact('category'), compact('cartdatas'));
    }

    public function add_to_cart(Request $request)
    {
        // dd(request()->all());
        if ($request->session()->has('FRONT_USER_LOGIN')) {
            $uid = $request->session()->get('FRONT_USER_ID');
            $user_type = "Reg";
        } else {
            $uid = getUserTempId();
            $user_type = "Not-Reg";
        }

        $add_to_cart = new add_to_cart;
        $add_to_cart->product_name = $request->post('product_name');
        $add_to_cart->product_price = $request->post('product_price');
        $add_to_cart->wings_name = $request->post('wings_name');
        $add_to_cart->ws_price = $request->post('ws_price');
        $add_to_cart->sauces_name = $request->post('sauces_name');
        $add_to_cart->sauce_price = $request->post('sauce_price');
        $add_to_cart->crusts_name = $request->post('crusts_name');
        $add_to_cart->crust_price = $request->post('crust_price');
        $add_to_cart->dippings_name = $request->post('dippings_name');
        $add_to_cart->dipping_price = $request->post('dipping_price');
        $add_to_cart->cookings_name = $request->post('cookings_name');
        $add_to_cart->cooking_price = $request->post('cooking_price');
        $add_to_cart->category_id = $request->post('category_id');
        $add_to_cart->ordernote = $request->post('ordernote');
        $add_to_cart->size_name = $request->post('size_name');
        $add_to_cart->size_price = $request->post('size_price');
        $add_to_cart->pqty = $request->post('pqty');
        $add_to_cart->user_id  = $uid;
        $add_to_cart->user_type = $user_type;
        $add_to_cart->save();

        $add_to_cart_id = DB::table('add_to_carts')->latest('id')->first();
        $create_dt = date("Y-m-d H:i:s", strtotime('now'));
        $update_dt = date("Y-m-d H:i:s", strtotime('now'));
        if ($add_to_cart_id->category_id === 1 || $add_to_cart_id->category_id === 2 || $add_to_cart_id->category_id === 4 || $add_to_cart_id->category_id === 6) {
            foreach ($request->toppings_left_name as $key => $insert) {


                if ($request->toppings_center_name[$key]) {
                    $status1 = 1;
                } else {
                    $status1 = 0.5;
                }

                if (isset($request->toppingsqty[$key]) && $request->toppingsqty[$key] != null && $request->toppingsqty[$key] != 0) {
                    $saverecord = [
                        'toppings_left_name' => $request->toppings_left_name[$key],
                        'toppings_left_id' => $request->toppings_left_id[$key],
                        'toppings_center_name' => $request->toppings_center_name[$key],
                        'toppings_center_id' => $request->toppings_center_id[$key],
                        'toppings_right_name' => $request->toppings_right_name[$key],
                        'toppings_right_id' => $request->toppings_right_id[$key],
                        'toppingsqty' => $request->toppingsqty[$key],
                        'add_to_cart_id' => $add_to_cart->id,
                        'status' => $status1,
                        'created_at' => $create_dt,
                        'updated_at' => $update_dt,
                    ];

                    DB::table('insert_toppings')->insert($saverecord);
                    //insert_topping::insert($saverecord);

                }
            }
        }
        if ($add_to_cart_id->category_id === 1 || $add_to_cart_id->category_id === 2 || $add_to_cart_id->category_id === 4 || $add_to_cart_id->category_id === 6) {

            foreach ($request->pretoppings_left_name as $key => $insert) {

                if ($request->pretoppings_center_name[$key]) {
                    $status2 = 2;
                } else {
                    $status2 = 1;
                }

                if (isset($request->pretoppingsqty[$key]) && $request->pretoppingsqty[$key] != null && $request->pretoppingsqty[$key] != 0) {
                    $presaverecord = [
                        'pretoppings_left_name' => $request->pretoppings_left_name[$key],
                        'pretoppings_left_id' => $request->pretoppings_left_id[$key],
                        'pretoppings_center_name' => $request->pretoppings_center_name[$key],
                        'pretoppings_center_id' => $request->pretoppings_center_id[$key],
                        'pretoppings_right_name' => $request->pretoppings_right_name[$key],
                        'pretoppings_right_id' => $request->pretoppings_right_id[$key],
                        'pretoppingsqty' => $request->pretoppingsqty[$key],
                        'add_to_cart_id' => $add_to_cart->id,
                        'status' => $status2,
                        'created_at' => $create_dt,
                        'updated_at' => $update_dt,
                    ];

                    DB::table('insert_toppings')->insert($presaverecord);
                    //insert_topping::insert($saverecord);
                }
            }
        }

        return [
            'msg' => 'Successfully added in cart.',
            'redirect' => '/shop',
        ];

        // $check=DB::table('cart')
        // ->where(['user_id'=>$uid])
        // ->where(['user_type'=>$user_type])
        // ->where(['product_name'=>$product_name])
        // ->where(['product_price'=>$product_price])
        // ->where(['wings_name'=>$wings_name])
        // ->where(['ws_price'=>$ws_price])
        // ->where(['sauces_name'=>$sauces_name])
        // ->where(['sauce_price'=>$sauce_price])
        // ->where(['toppings_left_name'=>$toppings_left_name])
        // ->where(['toppings_left_id'=>$toppings_left_id])
        // ->where(['toppings_center_name'=>$toppings_center_name])
        // ->where(['toppings_center_id'=>$toppings_center_id])
        // ->where(['toppings_right_name'=>$toppings_right_name])
        // ->where(['toppings_right_id'=>$toppings_right_id])
        // ->where(['crusts_name'=>$crusts_name])
        // ->where(['crust_price'=>$crust_price])
        // ->where(['dippings_name'=>$dippings_name])
        // ->where(['dipping_price'=>$dipping_price])
        // ->where(['cookings_name'=>$cookings_name])
        // ->where(['cooking_price'=>$cooking_price])
        // ->where(['pqty'=>$pqty])
        // ->get();

    }

    // customer controller

    public function register(Request $request)
    {

        if ($request->session()->has('FRONT_USER_LOGIN') != null) {
            return redirect('/');
        }

        $result = [];
        return view('front.register', $result);
    }

    public function register_customer(Request $request)
    {
        $valid = Validator::make($request->all(), [
            "name" => 'required|string|min:10|max:10|unique:custregisters',
            "email" => 'required|email|unique:custregisters,email',
            "password" => 'required|string|min:6|confirmed',
                        
        ]);

        if ($valid->fails()) {
            return response()->json(['status' => 'error', 'error' => $valid->errors()->toArray()]);
        } else {
            $arr = [
                "name" => $request->name,
                "email" => $request->email,
                "password" => Crypt::encrypt($request->password),
                "status" => 1,
                "created_at" => date('Y-m-d h:i:s'),
                "updated_at" => date('Y-m-d h:i:s')
            ];
            $query = DB::table('custregisters')->insert($arr);
            if ($query) {
                return response()->json(['status' => 'success', 'msg' => "Registration successfully"]);
            }
        }
    }

    // login Process

    public function login_process(Request $request)
    {

        $result = DB::table('custregisters')
            ->where(['name' => $request->str_login_name])
            ->get();

        if (isset($result[0])) {
            $db_pwd = Crypt::decrypt($result[0]->password);
            $status = $result[0]->status;
            // $is_verify=$result[0]->is_verify;

            // if($is_verify==0){
            //     return response()->json(['status'=>"error",'msg'=>'Please verify your Username']); 
            // }
            // if($status==0){
            //     return response()->json(['status'=>"error",'msg'=>'Your account has been deactivated']); 
            // }

            if ($db_pwd == $request->str_login_password) {

                if ($request->rememberme === null) {
                    setcookie('login_name', $request->str_login_name, 100);
                    setcookie('login_pwd', $request->str_login_password, 100);
                } else {
                    setcookie('login_name', $request->str_login_name, time() + 60 * 60 * 24 * 100);
                    setcookie('login_pwd', $request->str_login_password, time() + 60 * 60 * 24 * 100);
                }

                $request->session()->put('FRONT_USER_LOGIN', true);
                $request->session()->put('FRONT_USER_ID', $result[0]->id);
                $request->session()->put('FRONT_USER_NAME', $result[0]->name);
                $status = "success";
                $msg = "";

                $getUserTempId = getUserTempId();
                DB::table('add_to_carts')
                    ->where(['user_id' => $getUserTempId, 'user_type' => 'Not-Reg'])
                    ->update(['user_id' => $result[0]->id, 'user_type' => 'Reg']);
            } else {
                $status = "error";
                $msg = "Please enter valid password";
            }
        } else {
            $status = "error";
            $msg = "Please enter valid Username";
        }
        return response()->json(['status' => $status, 'msg' => $msg]);
        //$request->password
    }
}
