<?php

namespace App\Http\Controllers;
use anlutro\LaravelSettings\Facade as Setting;
require __DIR__.'/../../../vendor/razorpay-php/Razorpay.php';

use Illuminate\Http\Request;
use Razorpay\Api\Api;
use App\Models\CmsPages;
use App\Models\CmsPagesTranslation;
use App\Models\Contactus;
use App\Models\User;
use App\Models\DeliveryAddresses;
use App\Models\OrderProductsDelivery;
use App\Models\DeliveryAreas;
use App\Models\Order;
use App\Models\Cart;
use App\Models\Product;
use App\Models\ProductTranslation;
use App\Models\UserPayment;
use App\Models\UserCards;
use App\Models\Banners;
use App\Models\BannerTranslation;
use App\Models\Coupon;
use App\Models\CouponTranslation;
use App\Models\Timeslots;
use App\Models\TimeslotsTranslation;
use App\Models\UserWallet;
use App\Models\CardDetails;
use App\Models\OrderProduct;
use App\Models\OrderCancelRequest;
use App\Models\Partners;
use App\Models\NonWorkingDays;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Auth;

class SiteController extends Controller
{

    private $language;
    public function __construct(Request $request)
    {
        // parent::__construct();
        $this->request = $request;
        $this->language =  (isset($_COOKIE['lang_code']))?$_COOKIE['lang_code'] != '' ? $_COOKIE['lang_code'] : 'en':'en';
    }

    public function yourcallback(Request $request)
    {
        $post = $request->all();
        echo json_encode($post);exit;
    }


    public function yourpage(Request $request)
    {
        $post = $request->all();
        echo json_encode($post);exit;
    }

    public function index(Request $request)
    {
        
        $user_id = 0;
        if (Auth::check()) {
            $user_id = Auth::user()->id;
        }

        $allproducts = Product::where('status',1)->get();            
        foreach ($allproducts as $row) {
            $row['cart_info'] = Cart::where('user_id',$user_id)->where('product_id',$row['id'])->first();
            $translated_data = ProductTranslation::where('lang_code',$this->language)->where('product_id',$row['id'])->first();
            if($translated_data){
                if($translated_data->name!=''){
                    $row['name'] = $translated_data->name;
                }
                if($translated_data->description!=''){
                    $row['description'] = $translated_data->description;
                }
            }
        }
        $banners = Banners::where('status',1)->where('banner_type','website')->get();
        foreach ($banners as $bannerRow) {
            $translated_data = BannerTranslation::where('lang_code',$this->language)->where('banner_id',$bannerRow['id'])->first();
            if($translated_data){
                if($translated_data->title!=''){
                    $bannerRow['title'] = $translated_data->title;
                }
                if($translated_data->sub_title!=''){
                    $bannerRow['sub_title'] = $translated_data->sub_title;
                }
            }
        }
        return view('index')->with('products',$allproducts)->with('banners',$banners);
    }

    public function signin(Request $request)
    {
        return view('signin');
    }

    public function signup(Request $request)
    {
        return view('register');
    }

    public function cart(Request $request)
    {
        $user_id = 0;
        if (Auth::check()) {
            $user_id = Auth::user()->id;
        }
        $response = array();
        $cartData = Cart::where('user_id',$user_id)->with('product')->get();

        $total = array(
            'subtotal' => 0,
            'tax' => 0,
            'delivery_fee' => 0,
            'is_coupon_applied' => 0,
            'promotional_disount' => 0,
            'coupon_code' => '',
            'final_amount' => 0
        );

        foreach($cartData as $cart){
            if($cart->product){
                $translated_data = ProductTranslation::where('lang_code',$this->language)->where('product_id',$cart->product_id)->first();
                if($translated_data){
                    if($translated_data->name!=''){
                        $cart->product->name = $translated_data->name;
                    }
                    if($translated_data->description!=''){
                        $cart->product->description = $translated_data->description;
                    }
                }
                $total['subtotal'] = $total['subtotal'] + $cart->total_delivery_amount;
                array_push($response, $cart);
            }else{
                Cart::where('user_id',$cart->id)->delete();
            }
        }
        $total['subtotal'] = round($total['subtotal'],2);
        $total['delivery_fee'] = ($total['subtotal']<setting('minimum_order_value'))?setting('shipping_charge'):0;
        $total['tax'] = round((($total['subtotal'] * setting('default_tax')) / 100),2);
        $total['final_amount'] = round(($total['subtotal'] + $total['delivery_fee'] + $total['tax']),2);

        if(Session()->has('coupon_id')){
            $coupon_id = Session()->get('coupon_id');
            $code = Coupon::where('end_date','>=',date("Y-m-d"))->where('start_date','<=',date("Y-m-d"))->where('minimum_order_value','<=',$total['subtotal'])->where('status',1)->where('id',$coupon_id)->first();
            if($code){
                $total['is_coupon_applied'] = 1;
                $total['coupon_code'] = $code->coupon_name;
                if($code->type=='Fixed'){
                    if($code->value>$total['subtotal']){
                        $code->value = $total['subtotal'];
                    }
                    $total['promotional_disount'] = $code->value;
                }else{
                    $total['promotional_disount'] = round((($total['subtotal'] * $code->value) / 100),2);
                }
                Session::put('is_coupon_applied', $total['is_coupon_applied']);
                Session::put('coupon_code', $total['coupon_code']);
                Session::put('promotional_disount', $total['promotional_disount']);
            }
        }
        $total['final_amount'] = $total['final_amount'] - $total['promotional_disount'];

        $cartCount = Cart::where('user_id',$user_id)->count();
        Session::put('total_cart', $cartCount);

        $allcodes = Coupon::where('end_date','>=',date("Y-m-d"))->where('start_date','<=',date("Y-m-d"))->where('minimum_order_value','<=',$total['subtotal'])->where('status',1)->get();


        $holdaysDate = NonWorkingDays::where('status',1)->get();
        return view('cart')->with('data',$response)->with('coupon',$allcodes)->with('total',$total)->with('holdaysDate',$holdaysDate);
    }

    public function doCheckout(Request $request)
    {
        $post = $request->all();
        $user_id = 0;
        if (Auth::check()) {
            $user_id = Auth::user()->id;
        }

        $disabledWeekDays = array(-1);

        $holdaysDate = NonWorkingDays::where('status',1)->get();
        foreach ($holdaysDate as $rows) {
            $i = 0;
            $startDate = $rows->start_date;
            do{
                $currentDate = date("Y-m-d",strtotime($startDate.' + '.$i.' day'));
                array_push($disabledWeekDays, $currentDate);
                $i++;
            }while(strtotime($currentDate)<strtotime($rows->end_date));
        }

        for ($i=0; $i < count($post['cart_id']); $i++) {
            if($post['quantity'][$i]>0){
                $cartId = $post['cart_id'][$i];
                $cartInfo = Cart::where('id',$cartId)->first();
                if($cartInfo){
                    $order_frequency = isset($post['order_frequency_'.$cartId])?strtolower($post['order_frequency_'.$cartId]):'once';
                    $inject = array(
                        'quantity' => $post['quantity'][$i],
                        "order_frequency" => $order_frequency
                    );

                    if($order_frequency=='once'){
                        $inject['no_of_delivery'] = 1;
                        $inject['days'] = '';
                        if(!in_array(date("Y-m-d",strtotime($post['delivery_dates'][$i])), $disabledWeekDays))
                        {
                            $inject['delivery_dates'] = $post['delivery_dates'][$i];
                            $inject['per_delivery_amount'] = $cartInfo->per_item_amount * $post['quantity'][$i];
                            $inject['total_delivery_amount'] = $inject['per_delivery_amount'];
                            $inject['start_date'] = date("Y-m-d",strtotime($post['delivery_dates'][$i]));
                            $inject['end_date'] = date("Y-m-d",strtotime($post['delivery_dates'][$i]));
                            Cart::where('id',$cartId)->update($inject);
                        }
                        else
                        {
                            Session::flash('error',"We are not delivering for the selected date."); 
                            return redirect()->to('cart');
                        }
                    }
                    else if($order_frequency=='daily')
                    {
                        $dates = explode("-",$post['delivery_dates'][$i]);
                        if(isset($dates[1])){
                            $inject['start_date'] = date("Y-m-d",strtotime(trim($dates[0])));
                            $inject['end_date'] = date("Y-m-d",strtotime(trim($dates[1])));
                            $inject['days'] = '';

                            $dc = 0;
                            $currentDate = $inject['start_date'];
                            $delivery_dates = array();
                            do{
                                $addDate = date("Y-m-d",strtotime($inject['start_date'].' + '.$dc.' day'));                                
                                if(!in_array(date("Y-m-d",strtotime($addDate)), $disabledWeekDays))
                                {
                                    array_push($delivery_dates, $addDate);
                                    $currentDate = date("Y-m-d",strtotime($inject['start_date'].' + '.$dc.' day'));
                                    $dc++;
                                }else{
                                    $currentDate = date("Y-m-d",strtotime($inject['start_date'].' + '.$dc.' day'));
                                    $dc++;
                                }
                            }while(strtotime($currentDate)<strtotime($inject['end_date']));

                            $inject['no_of_delivery'] = count($delivery_dates);
                            $inject['per_delivery_amount'] = $cartInfo->per_item_amount * $post['quantity'][$i];
                            $inject['total_delivery_amount'] = $inject['per_delivery_amount'] * $inject['no_of_delivery'];
                            $inject['delivery_dates'] = implode(",",$delivery_dates);
                            Cart::where('id',$cartId)->update($inject);
                        }else{
                            Session::flash('error', __('lang.alert_select_date_range_for_daily')); 
                            return redirect()->to('cart');
                        }
                    }
                    else if($order_frequency=='weekly')
                    {
                        $dates = explode("-",$post['delivery_dates'][$i]);
                        if(isset($dates[1])){
                            $inject['start_date'] = date("Y-m-d",strtotime(trim($dates[0])));
                            $inject['end_date'] = date("Y-m-d",strtotime(trim($dates[1])));
                            $days = (isset($post['days_'.$cartId]))?$post['days_'.$cartId]:[];
                            $weekDays = array(
                                'mon' => 1,
                                'tue' => 2,
                                'wed' => 3,
                                'thu' => 4,
                                'fri' => 5,
                                'sat' => 6,
                                'sun' => 0
                            );
                            $days_array = array();
                            foreach ($days as $key => $value) {
                                array_push($days_array,$weekDays[$key]);
                            }
                            $inject['days'] = implode(",",$days_array);
                            $dc = 0;
                            $count = 0;
                            $currentDate = $inject['start_date'];
                            $delivery_dates = array();
                            do{
                                $newDate = date("Y-m-d",strtotime($inject['start_date'].' + '.$dc.' day'));
                                if(in_array(date("w",strtotime($newDate)), $days_array)){
                                    if(!in_array(date("Y-m-d",strtotime($newDate)), $disabledWeekDays))
                                    {
                                        array_push($delivery_dates, $newDate);
                                    }
                                    $count++;
                                }
                                $currentDate = date("Y-m-d",strtotime($inject['start_date'].' + '.$dc.' day'));
                                $dc++;
                            }while(strtotime($currentDate)<strtotime($inject['end_date']));
                            $inject['no_of_delivery'] = count($delivery_dates);
                            $inject['per_delivery_amount'] = $cartInfo->per_item_amount * $post['quantity'][$i];
                            $inject['total_delivery_amount'] = $inject['per_delivery_amount'] * $inject['no_of_delivery'];
                            $inject['delivery_dates'] = implode(",",$delivery_dates);
                            Cart::where('id',$cartId)->update($inject);
                        }else{
                            Session::flash('error',  __('lang.alert_select_date_range_for_weekly')); 
                            return redirect()->to('cart');
                        }
                    }
                    else if($order_frequency=='monthly')
                    {
                        $dates = explode(",",$post['delivery_dates'][$i]);
                        if(count($dates)>0){
                            $inject['start_date'] = date("Y-m-d",strtotime(trim($dates[0])));
                            $inject['end_date'] = date("Y-m-d",strtotime(trim($dates[count($dates)-1])));
                            $inject['days'] = '';
                            $inject['no_of_delivery'] = count($dates);
                            $inject['per_delivery_amount'] = $cartInfo->per_item_amount * $post['quantity'][$i];
                            $inject['total_delivery_amount'] = $inject['per_delivery_amount'] * $inject['no_of_delivery'];
                            $delivery_dates = array();
                            for ($dc=0; $dc <count($dates) ; $dc++) {
                                if(!in_array(date("Y-m-d",strtotime($dates[$dc])), $disabledWeekDays))
                                {
                                    array_push($delivery_dates, date("Y-m-d",strtotime($dates[$dc])));
                                }
                            }
                            $inject['delivery_dates'] = implode(",",$delivery_dates);
                            Cart::where('id',$cartId)->update($inject);
                        }else{
                            Session::flash('error', __('lang.alert_select_date_range_for_monthly')); 
                            return redirect()->to('cart');
                        }
                    }
                    else if($order_frequency=='alternative')
                    {
                        $dates = explode("-",$post['delivery_dates'][$i]);
                        if(isset($dates[1])){
                            $inject['start_date'] = date("Y-m-d",strtotime(trim($dates[0])));
                            $inject['end_date'] = date("Y-m-d",strtotime(trim($dates[1])));
                            $inject['days'] = '';

                            $dc = 0;
                            $currentDate = $inject['start_date'];
                            $delivery_dates = array();
                            $count = 0;
                            do{
                                $newDate = date("Y-m-d",strtotime($inject['start_date'].' + '.$dc.' day'));
                                if(strtotime($inject['end_date'])>=strtotime($newDate)){
                                    if(!in_array(date("Y-m-d",strtotime($newDate)), $disabledWeekDays))
                                    {
                                        array_push($delivery_dates, $newDate);
                                        $currentDate = $newDate;
                                        $dc = $dc+2;
                                        $count++;
                                    }else{
                                        $currentDate = $newDate;
                                        $dc = $dc+1;
                                        $count++;
                                    }
                                }else{
                                    $currentDate = $newDate;
                                    $dc = $dc+2;
                                }
                            }while(strtotime($currentDate)<=strtotime($inject['end_date']));
                            $inject['no_of_delivery'] = count($delivery_dates);;
                            $inject['per_delivery_amount'] = $cartInfo->per_item_amount * $post['quantity'][$i];
                            $inject['total_delivery_amount'] = $inject['per_delivery_amount'] * $inject['no_of_delivery'];
                            $inject['delivery_dates'] = implode(",",$delivery_dates);
                            Cart::where('id',$cartId)->update($inject);
                        }else{
                            Session::flash('error',  __('lang.alert_select_date_rang_for_alternative')); 
                            return redirect()->to('cart');
                        }
                    }
                }
            }
        }
        $btnVal = (isset($post['submit_button']))?$post['submit_button']:'next';
        if($btnVal=='next' && $inject['total_delivery_amount']>0){
            Session::flash('message', __('lang.alert_cart_updated_successfully'));
            return redirect()->to('checkout');
        }else{
            if($inject['total_delivery_amount']>0){
                Session::flash('message', __('lang.alert_cart_updated_successfully'));
                return redirect()->back()->with('message',__('lang.alert_cart_updated_successfully'));
            }
            else{
                return redirect()->back()->with('error',"There is an error, Please try again");
            }
        }
    }

    public function applyCoupon(Request $request)
    {
        $post = $request->all();
        $user_id = 0;
        if (Auth::check()) {
            $user_id = Auth::user()->id;
        }
        Session::put('coupon_id', $post['coupon_id']);
        Session::flash('message', __('lang.alert_coupon_applied_successfully'));
        return redirect()->back()->with('message',__('lang.alert_coupon_applied_successfully'));
    }

    public function addToCart(Request $request)
    {
        $post = $request->all();
        $user_id = 0;
        if (Auth::check()) {
            $user_id = Auth::user()->id;
        }

        $product =  Product::where('id',$post['product_id'])->first();
        if (!$product) {
            Session::flash('message', __('lang.alert_product_not_found')); 
            return redirect()->back()->with('message',__('lang.alert_product_not_found'));
        }

        $cartItemExist = Cart::where('user_id',$user_id)->where('product_id',$post['product_id'])->first();
        $price = ($product->discount_price>0)?$product->discount_price:$product->price;
        $total_amount = $price;
        
        $inject = array(
            "user_id" => $user_id,
            "product_id" => $post['product_id'],
            'quantity' => ($product->minimum_order_quantity>0)?$product->minimum_order_quantity:1,
            "per_item_amount" => $price,
            'per_delivery_amount' => $total_amount,
            'total_delivery_amount' => $total_amount,
            "no_of_delivery" => 1,
            "days" => '',
            "delivery_dates" => date("Y-m-d"),
            "order_frequency" => 'once'
        );

        if($cartItemExist){
            $inject['updated_at'] = date('Y-m-d h:i:s');
            Cart::where('id',$cartItemExist->id)->update($inject);
            $id = $cartItemExist->id;
        }else{
            $inject['created_at'] = date('Y-m-d h:i:s');
            $id = Cart::insertGetId($inject);
        }

        $cartCount = Cart::where('user_id',$user_id)->count();
        Session::put('total_cart', $cartCount);
        return redirect('/#populargoods')->with('message',__('lang.alert_cart_updated_successfully'));
    }

    public function deleteCartitem($id,Request $request)
    {
        $post = $request->all();
        $user_id = 0;
        if (Auth::check()) {
            $user_id = Auth::user()->id;
        }
        Cart::where('id',$id)->delete();
        $cartCount = Cart::where('user_id',$user_id)->count();
        Session::put('total_cart', $cartCount);
        Session::flash('message', __('lang.alert_cart_deleted_successfully')); 
        return redirect()->to('cart');
    }

    public function checkout(Request $request)
    {
        $addresses = DeliveryAddresses::where('user_id',Auth::user()->id)->get();
        return view('checkout')->with('data',$addresses);
    }

    public function placeOrder(Request $request)
    {
        $post = $request->all();
        request()->validate([
            'delivery_address_id' => 'required'
        ]);
        $user_id = 0;
        if (Auth::check()) {
            $user_id = Auth::user()->id;
        }

        $address = DeliveryAddresses::where('id',$post['delivery_address_id'])->first();
        // if($address){
        //     if($address->location_name!=''){
        //         $count = DeliveryAreas::where('location_name',$address->location_name)->get();
        //         if(count($count)==0){
        //             Session::flash('error', "We are not delivering in this area right now, Please contact to admin for further information"); 
        //             return redirect()->back();
        //         }
        //     }else{
        //         Session::flash('error', "We are not delivering in this area right now, Please contact to admin for further information"); 
        //         return redirect()->back();
        //     }
        // }else{
        //     Session::flash('error', "We are not delivering in this area right now, Please contact to admin for further information"); 
        //     return redirect()->back();
        // }

        $response = array();
        $response['timeslots'] = Timeslots::all();
        foreach ($response['timeslots'] as $row) {
            $translated_data = TimeslotsTranslation::where('lang_code',$this->language)->where('timeslots_id',$row->id)->first();
            if($translated_data){
                if($translated_data->name!=''){
                    $row->name = $translated_data->name;
                }
            }
        }
        $response['total_wallet'] = UserWallet::getWalletbalance($user_id);
        $response['cards'] = UserCards::where('user_id',$user_id)->orderBy('id','DESC')->get();

        $cartData = Cart::where('user_id',$user_id)->with('product')->get();
        $total = array(
            'subtotal' => 0,
            'tax' => 0,
            'delivery_fee' => 0,
            'is_coupon_applied' => 0,
            'promotional_disount' => 0,
            'coupon_code' => '',
            'final_amount' => 0
        );

        foreach($cartData as $cart){
            if($cart->product){
                $translated_data = ProductTranslation::where('lang_code',$this->language)->where('product_id',$cart->product_id)->first();
                if($translated_data){
                    if($translated_data->name!=''){
                        $cart->product->name = $translated_data->name;
                    }
                    if($translated_data->description!=''){
                        $cart->product->description = $translated_data->description;
                    }
                }
                $total['subtotal'] = $total['subtotal'] + $cart->total_delivery_amount;
                array_push($response, $cart);
            }else{
                Cart::where('user_id',$cart->id)->delete();
            }
        }
        $total['subtotal'] = round($total['subtotal'],2);
        $total['delivery_fee'] = ($total['subtotal']<setting('minimum_order_value'))?setting('shipping_charge'):0;
        $total['tax'] = round((($total['subtotal'] * setting('default_tax')) / 100),2);
        $total['final_amount'] = round(($total['subtotal'] + $total['delivery_fee'] + $total['tax']),2);
        
        if(Session()->has('is_coupon_applied')){
            $total['is_coupon_applied'] = Session()->get('is_coupon_applied');
            $total['coupon_code'] = Session()->get('coupon_code');
            $total['promotional_disount'] = Session()->get('promotional_disount');
        }
        $cartCount = Cart::where('user_id',$user_id)->count();
        Session::put('total_cart', $cartCount);
        $total['final_amount'] = $total['final_amount'] - $total['promotional_disount'];
        return view('place-order')->with('response',$response)->with('total',$total)->with('delivery_address_id',$post['delivery_address_id']);
    }

    public function doPlaceOrder(Request $request)
    {
        $post = $request->all();
        request()->validate([
            'delivery_address_id' => 'required',
            'timeslot_id' => 'required',
            'payment_method' => 'required',
        ]);

        $user_id = 0;
        if (Auth::check()) {
            $user_id = Auth::user()->id;
        }

        $address = DeliveryAddresses::where('id',$post['delivery_address_id'])->first();
        // if($address){
        //     if($address->location_name!=''){
        //         $count = DeliveryAreas::where('location_name',$address->location_name)->get();
        //         if(count($count)==0){
        //             Session::flash('message', "We are not delivering in this area right now, Please contact to admin for further information"); 
        //             return redirect()->back();
        //         }
        //     }else{
        //         Session::flash('message', "We are not delivering in this area right now, Please contact to admin for further information"); 
        //         return redirect()->back();
        //     }
        // }else{
        //     Session::flash('message', "We are not delivering in this area right now, Please contact to admin for further information"); 
        //     return redirect()->back();
        // }
        $cartData = Cart::where('user_id',$user_id)->with('product')->get();
        $orderPostData = array(
            'subtotal' => 0,
            'tax' => 0,
            'delivery_fee' => 0,
            'is_coupon_applied' => 0,
            'promotional_disount' => 0,
            'coupon_code' => '',
            'final_amount' => 0,
            'delivery_address_id' => $post['delivery_address_id'],
            'timeslot_id' => $post['timeslot_id'],
            'order_status_id' => 1
        );

        if(Session()->has('is_coupon_applied')){
            $orderPostData['is_coupon_applied'] = Session()->get('is_coupon_applied');
            $orderPostData['coupon_code'] = Session()->get('coupon_code');
            $orderPostData['promotional_disount'] = Session()->get('promotional_disount');
        }

        foreach($cartData as $cart){
            if($cart->product){
                $orderPostData['subtotal'] = $orderPostData['subtotal'] + $cart->total_delivery_amount;
            }
        }
        $orderPostData['subtotal'] = round($orderPostData['subtotal'],2);
        $orderPostData['delivery_fee'] = ($orderPostData['subtotal']<setting('minimum_order_value'))?setting('shipping_charge'):0;
        $orderPostData['tax'] = round((($orderPostData['subtotal'] * setting('default_tax')) / 100),2);
        $orderPostData['final_amount'] = round(($orderPostData['subtotal'] + $orderPostData['delivery_fee'] + $orderPostData['tax']),2);
        $orderPostData['final_amount'] = $orderPostData['final_amount'] - $orderPostData['promotional_disount'];
        $orderPostData['user_id'] = $user_id;
        $orderPostData['payment_method'] = $post['payment_method'];
        $orderPostData['created_at'] = date('Y-m-d H:i:s');
        if($post['payment_method']=='wallet'){
            $total_wallet = UserWallet::getWalletbalance($user_id);
            if($total_wallet<$orderPostData['final_amount']){
                Session::flash('error', __('lang.alert_dont_have_sufficent_balance'));
                return redirect()->back()->with('error',__('lang.alert_dont_have_sufficent_balance'));
            }
        }
        $orderId = Order::insertGetId($orderPostData);
        $amount = 0;
        
        foreach($cartData as $cart){
            if($cart->product){
                $inject = array(
                    'user_id' => $user_id,
                    'order_id' => $orderId,
                    'product_id'=> $cart->product_id,
                    'quantity' => $cart->quantity,
                    'per_item_amount' => $cart->per_item_amount,
                    'per_delivery_amount' => $cart->per_delivery_amount,
                    'total_delivery_amount' => $cart->total_delivery_amount,
                    'no_of_delivery' => $cart->no_of_delivery,
                    'order_frequency' => $cart->order_frequency,                        
                    'start_date' => $cart->start_date,
                    'end_date' => $cart->end_date,
                    'days' => $cart->days,
                    'created_at'=>date('Y-m-d H:i:s')
                );
                $orderitemId = OrderProduct::insertGetId($inject);
                $delivery_dates = explode(",",$cart->delivery_dates);
                foreach ($delivery_dates as $r) {
                    $delivery = array(
                        'user_id' => $user_id,
                        'order_id' => $orderId,
                        'product_id'=> $cart->product_id,
                        'product_order_id'=> $orderitemId,
                        'delivery_date' => date("Y-m-d",strtotime($r)),
                        'order_status_id' => $orderPostData['order_status_id'],
                        'created_at'=>date('Y-m-d H:i:s')
                    );
                    OrderProductsDelivery::insert($delivery);    
                }
            }
        }
        
        $paymentid = UserPayment::insertGetId([
            "user_id" => $orderPostData['user_id'],
            "description" => 'Waiting for Client',
            "price" => $orderPostData['final_amount'],
            "status" => 'Waiting for Client',
            "method" => $orderPostData['payment_method'],
            'created_at'=>date('Y-m-d H:i:s')
        ]);

        Order::where('id',$orderId)->update(['payment_id' => $paymentid,'updated_at'=>date("Y-m-d H:i:s")]);
        if($orderPostData['payment_method']=='wallet'){
            $wallet = [
                'user_id'=>$user_id,
                'order_id'=>$orderId,
                'type'=>'debit',
                'amount'=>-$orderPostData['final_amount'],
                'description'=> 'We have debit '.\Helpers::currency($orderPostData['final_amount']).' form your wallet for new purchase.',
                'created_at'=>date('Y-m-d H:i:s')
            ];
            UserWallet::insertGetId($wallet);
        }
        else if($post['payment_method']=='online'){
            $entityId = '8ac7a4c77d8d45bb017d8f5c7963042b';
            $url = "https://test.oppwa.com/v1/checkouts";
            $data = "entityId=" .$entityId.
                        "&amount=" .$orderPostData['final_amount'].
                        "&currency=SAR" .
                        "&paymentType=DB";

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                           'Authorization:Bearer OGFjN2E0Yzc3ZDhkNDViYjAxN2Q4ZjVjMTljNDA0MjZ8SnJIblk4cFpORA=='));
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// this should be set to true in production
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $responseData = curl_exec($ch);
            if(curl_errno($ch)) {
                return curl_error($ch);
            }
            curl_close($ch);
            $responseData = json_decode($responseData);
            if($responseData){
                Cart::where('user_id',$user_id)->delete();
                Session::put('total_cart', 0);
                Session::put('ndc_id', $responseData->ndc);
                Session()->forget('coupon_id');
                Session()->forget('is_coupon_applied');
                Session()->forget('coupon_code');
                Session()->forget('promotional_disount');
                return redirect()->to('do-online-payment/'.$orderId);
            }
        }
        else if($post['payment_method']=='razorpay'){
            $api = new Api(setting('razorpay_key'), setting('razorpay_secret'));
            $payment = $api->payment->fetch($post['razorpay_payment_id']);
            if(count($post)  && !empty($post['razorpay_payment_id'])) 
            {
                try 
                {
                    $response = $api->payment->fetch($post['razorpay_payment_id'])->capture(array('amount'=>$payment['amount'])); 

                    $orderData = Order::where('id',$orderId)->first();
                    if($orderData){
                        UserPayment::where('id',$orderData->payment_id)->update(['description' => 'Paid','status' => 'Paid','updated_at'=>date("Y-m-d H:i:s")]);
                    }
                    Session::put('total_cart', 0);
                    Session()->forget('coupon_id');
                    Session()->forget('is_coupon_applied');
                    Session()->forget('coupon_code');
                    Session()->forget('promotional_disount');
                    return redirect()->to('order-details/'.$orderId);

                } 
                catch (\Exception $e) 
                {
                    $orderData = Order::where('id',$orderId)->first();
                    if($orderData){
                        UserPayment::where('id',$orderData->payment_id)->update(['description' => 'Failed','status' => 'Failed','updated_at'=>date("Y-m-d H:i:s")]);
                        Order::where('id',$orderId)->update(['order_status_id' => 6,'updated_at'=>date("Y-m-d H:i:s")]);
                    }
                    Session::put('total_cart', 0);
                    Session()->forget('coupon_id');
                    Session()->forget('is_coupon_applied');
                    Session()->forget('coupon_code');
                    Session()->forget('promotional_disount');
                    return redirect()->to('order-details/'.$orderId);
                }            
            }
        }
        Cart::where('user_id',$user_id)->delete();
        Session::put('total_cart', 0);
        Session()->forget('coupon_id');
        Session()->forget('is_coupon_applied');
        Session()->forget('coupon_code');
        Session()->forget('promotional_disount');
        return redirect()->to('order-details/'.$orderId);
    }

    public function doOnlinePayment($id,Request $request)
    {
        return view('do-online-payment')->with('order_id',$id);
    }

    public function doConfirmPayment($orderId,Request $request)
    {
        $post = $request->all();
        $url = "https://test.oppwa.com/v1/checkouts/".$post['id']."/payment";
        $url .= "?entityId=8ac7a4c77d8d45bb017d8f5c7963042b";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                       'Authorization:Bearer OGFjN2E0Yzc3ZDhkNDViYjAxN2Q4ZjVjMTljNDA0MjZ8SnJIblk4cFpORA=='));
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// this should be set to true in production
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $responseData = curl_exec($ch);
        if(curl_errno($ch)) {
            return curl_error($ch);
        }
        curl_close($ch);
        $responseData = json_decode($responseData);
        $array = ["000.100.110","000.100.111","000.100.112"];
        if(!isset($responseData->result->code)){
            $orderData = Order::where('id',$orderId)->first();
            if($orderData){
                UserPayment::where('id',$orderData->payment_id)->update(['description' => 'Failed','status' => 'Failed','updated_at'=>date("Y-m-d H:i:s")]);
                Order::where('id',$orderId)->update(['order_status_id' => 6,'updated_at'=>date("Y-m-d H:i:s")]);
            }
            return redirect()->to('order-details/'.$orderId);
        }
        if (in_array($responseData->result->code, $array)){
            $orderData = Order::where('id',$orderId)->first();
            if($orderData){
                UserPayment::where('id',$orderData->payment_id)->update(['description' => 'Paid','status' => 'Paid','updated_at'=>date("Y-m-d H:i:s")]);
            }
            return redirect()->to('order-details/'.$orderId);
        }
        else{
            $orderData = Order::where('id',$orderId)->first();
            if($orderData){
                UserPayment::where('id',$orderData->payment_id)->update(['description' => 'Failed','status' => 'Failed','updated_at'=>date("Y-m-d H:i:s")]);
                Order::where('id',$orderId)->update(['order_status_id' => 6,'updated_at'=>date("Y-m-d H:i:s")]);
            }
            return redirect()->to('order-details/'.$orderId);
        }
    }

    public function profile(Request $request)
    {
        return view('your-account')->with('user',Auth::user());
    }

    public function addresses(Request $request)
    {
        $addresses = DeliveryAddresses::where('user_id',Auth::user()->id)->get();
        return view('saved-addresses')->with('data',$addresses);
    }

    public function orders(Request $request)
    {
        $user_id = 0;            
        if (Auth::check()) {
            $user_id = Auth::user()->id;
        }
        $orders = Order::where('user_id',$user_id)->with('product_orders')->with('order_status')->orderBy('id','DESC')->get();
        foreach($orders as $row){
            foreach($row->product_orders as $prow){
                if($prow->product){
                    $translated_data = ProductTranslation::where('lang_code',$this->language)->where('product_id',$prow->product_id)->first();
                    if($translated_data){
                        if($translated_data->name!=''){
                            $prow->product->name = $translated_data->name;
                        }
                        if($translated_data->description!=''){
                            $prow->product->description = $translated_data->description;
                        }
                    }
                }
            }
        }
        return view('your-order')->with('data',$orders);
    }

    public function orderDetail($id,Request $request)
    {
        $user_id = 0;            
        if (Auth::check()) {
            $user_id = Auth::user()->id;
        }
        $orders = $this->getOrderDetails($id,$user_id);
        if($orders){
            return view('order-details')->with('data',$orders);
        }else{
            return redirect()->to('orders');
        }
    }

    public function cancelOrderRequest($id,Request $request)
    {
        $user_id = 0;            
        if (Auth::check()) {
            $user_id = Auth::user()->id;
        }
        $postData = array(
            'order_id' => $id,
            'user_id' => $user_id,
            'refund_amount' => 0,
            'refund_status' => 0,
            'status' => 0,
            'created_at' => date("Y-m-d H:i:s"),
            'updated_at' => date("Y-m-d H:i:s")
        );


        $data = Order::find($id);
        if($data->payment_method!='cash'){
            $totalWalletAmount = 0;
            $productsDelivery = OrderProductsDelivery::where('order_status_id','<',5)->where('delivery_date','>=',date("Y-m-d"))->where('order_id',$id)->with('product_orders')->get();
            foreach ($productsDelivery as $row) {
                if($row->product_orders){
                    $totalWalletAmount = $totalWalletAmount + $row->product_orders->per_delivery_amount;
                }
            }
            $postData['refund_amount'] = $totalWalletAmount;
        }

        OrderCancelRequest::insertGetId($postData);
        Session::flash('message',  __('lang.alert_cancel_order_request_submited')); 
        return redirect()->back()->with('message', __('lang.alert_cancel_order_request_submited'));
    }

    private function getOrderDetails($id,$user_id)
    {
        $orders = Order::where('user_id',$user_id)->where('id',$id)->with('product_orders')->with('order_status')->with('payment')->with('delivery_address')->with('time_slots')->with('cancel_request')->first();
        if($orders){
            $delivered_products = OrderProductsDelivery::where('order_id',$id)->groupBy('delivery_date')->orderBy('delivery_date','ASC')->get();
            $AllDeliveryDates = array();
            foreach ($delivered_products as $delivered) {
                $temp = array(
                    'date' => $delivered->delivery_date,
                    'data' => OrderProductsDelivery::where('order_id',$id)->where('delivery_date',$delivered->delivery_date)->with('product_orders')->with('delivery_status')->get()
                );
                array_push($AllDeliveryDates,$temp);
            }
            $orders->delivered_products = $AllDeliveryDates;
            foreach($orders->product_orders as $prow){
                if($prow->product){
                    $translated_data = ProductTranslation::where('lang_code',$this->language)->where('product_id',$prow->product_id)->first();
                    if($translated_data){
                        if($translated_data->name!=''){
                            $prow->product->name = $translated_data->name;
                        }
                        if($translated_data->description!=''){
                            $prow->product->description = $translated_data->description;
                        }
                    }
                }
            } 
        }
        return $orders;
    }

    // public function payment(Request $request)
    // {
    //     $user_id = 0;            
    //     if (Auth::check()) {
    //         $user_id = Auth::user()->id;
    //     }
    //     $cards = UserCards::where('user_id',$user_id)->orderBy('id','DESC')->get();
    //     return view('payment')->with('data',$cards)->with('user_id',$user_id);
    // }

    // public function deleteMyCard($id){
    //     UserCards::where('id', $id)->delete();       
    //     Session::flash('message', __('lang.alert_card_deleted_successfully')); 
    //     return redirect()->back()->with('message',__('lang.alert_card_deleted_successfully'));
    // }

    public function contact(Request $request)
    {
        return view('contact');
    }

    public function doSubmitContactUs(Request $request)
    {
        $post = $request->all();
        $postData = array(
            'user_id' => 0,
            'name' => $post['name'],
            'email' => $post['email'],
            'message' => $post['message'],
            'mobile' => $post['mobile'],
            'created_at' => date("Y-m-d H:i:s"),
            'updated_at' => date("Y-m-d H:i:s"),
        );
        Contactus::insert($postData);
        Session::flash('message', __('lang.alert_contact_us_request_submited_successfully')); 
        return redirect()->back()->with('message',__('lang.alert_contact_us_request_submited_successfully'));
    }

    public function termsAndCondition(Request $request)
    {
        $terms = CmsPages::where('page_name','terms')->first();
        if($terms){
            $translated_data = CmsPagesTranslation::where('lang_code',$this->language)->where('cms_id',$terms->id)->first();
            if($translated_data){
                if($translated_data->page_title!=''){
                    $terms->page_title = $translated_data->page_title;
                }
                if($translated_data->description!=''){
                    $terms->description = $translated_data->description;
                }
            }
        }
        return view('term-and-conditions')->with('data',$terms);
    }

    public function privacyPolicy(Request $request)
    {
        $terms = CmsPages::where('page_name','policy')->first();
        if($terms){
            $translated_data = CmsPagesTranslation::where('lang_code',$this->language)->where('cms_id',$terms->id)->first();
            if($translated_data){
                if($translated_data->page_title!=''){
                    $terms->page_title = $translated_data->page_title;
                }
                if($translated_data->description!=''){
                    $terms->description = $translated_data->description;
                }
            }
        }
        return view('privacy-policy')->with('data',$terms);
    }

    public function about(Request $request)
    {
        $about_us = CmsPages::where('page_name','about')->first();
        $about_us_partners = Partners::where('type','partner')->get();
        $about_us_awards = Partners::where('type','awards')->get();
        if($about_us){
            $translated_data = CmsPagesTranslation::where('lang_code',$this->language)->where('cms_id',$about_us->id)->first();
            if($translated_data){
                if($translated_data->page_title!=''){
                    $about_us->page_title = $translated_data->page_title;
                }
                if($translated_data->description!=''){
                    $about_us->description = $translated_data->description;
                }
            }
        }
        return view('about')->with('data',$about_us)->with('partners',$about_us_partners)->with('awards',$about_us_awards);
    }

    public function accountDelete(Request $request)
    {
        $account = CmsPages::where('page_name','account-deletion')->first();
        if($account){
            $translated_data = CmsPagesTranslation::where('lang_code',$this->language)->where('cms_id',$account->id)->first();
            if($translated_data){
                if($translated_data->page_title!=''){
                    $account->page_title = $translated_data->page_title;
                }
                if($translated_data->description!=''){
                    $account->description = $translated_data->description;
                }
            }
        }
        return view('account-deletion')->with('data',$account);
    }

    public function wallet(Request $request)
    {
        $user_id = 0;
        if (Auth::check()) {
            $user_id = Auth::user()->id;
        }
        $total_wallet = UserWallet::getWalletbalance($user_id);
        $wallet = UserWallet::getUserWalletLists($user_id);
        return view('wallet')->with('data',$wallet)->with('total_wallet',$total_wallet);
    }

    public function submitWallet(Request $request)
    {
        $user_id = 0;
        if (Auth::check()) {
            $user_id = Auth::user()->id;
        }
        $post = $request->all();
        $paymentid = UserPayment::insertGetId([
            "user_id" => $user_id,
            "description" => 'Waiting for Client',
            "price" => $post['amount'],
            "status" => 'Waiting for Client',
            "method" => '',
            'created_at'=>date('Y-m-d H:i:s')
        ]);
        $post['paymentid'] = $paymentid;
        return view('place-wallet')->with('post',$post);
    }

    public function doConfirmWalletPayment(Request $request)
    {
        $user_id = 0;
        if (Auth::check()) {
            $user_id = Auth::user()->id;
        }

        $post = $request->all();
        $api = new Api(setting('razorpay_key'), setting('razorpay_secret'));
        $payment = $api->payment->fetch($post['razorpay_payment_id']);
        if(count($post)  && !empty($post['razorpay_payment_id'])) 
        {
            try 
            {
                $response = $api->payment->fetch($post['razorpay_payment_id'])->capture(array('amount'=>$payment['amount']));
                UserPayment::where('id',$post['paymentid'])->update(['description' => 'Paid','status' => 'Paid','method'=>'razorpay','updated_at'=>date("Y-m-d H:i:s")]);

                $wallet = [
                    'user_id'=>$user_id,
                    'order_id'=>0,
                    'type'=>'credit',
                    'amount'=>$payment['amount']/100,
                    'description'=> 'We have credit '.\Helpers::currency($payment['amount']/100).' in your wallet.',
                    'created_at'=>date('Y-m-d H:i:s')
                ];
                UserWallet::insertGetId($wallet);
                return redirect()->to('wallet');

            } 
            catch (\Exception $e) 
            {
                UserPayment::where('id',$post['paymentid'])->update(['description' => 'Failed','status' => 'Failed','method'=>'razorpay','updated_at'=>date("Y-m-d H:i:s")]);
                
                return redirect()->to('wallet');
            }            
        }
    }

    public function setLanguage(Request $request){
        $post = $request->all();
        if (array_key_exists($post['lang_code'], Config::get('languages'))) {
            if (isset($post['lang_code'])) {
                $direction = \Helpers::getLangData($post['lang_code']);
                if (auth()->user() && auth()->user()->type == 'user') {
                    User::where('id',auth()->user()->id)->update(['lang_code'=>$post['lang_code']]);
                    Session::put('locale', $post['lang_code']);
                    Session::put('direction', $direction);
                    setcookie('lang_code',$post['lang_code'],time()+60*60*24*365);
                }else{
                    Session::put('locale', $post['lang_code']);
                    Session::put('direction', $direction);
                    setcookie('lang_code',$post['lang_code'],time()+60*60*24*365);
                }
            }
        }
        return redirect()->back();
    }

    /**
     * Log the user out of the application.
     *
     * @param  \Illuminate\Http\Request  $request
     */

    public function userLogout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        return redirect('/signin')->with('success', __('lang.alert_logout_successfully'));
    }

    public function userTerminate(Request $request)
    {
        $id = Auth::user()->id;
        $user = User::find($id);
        $user->delete();
         $request->session()->invalidate();
         return redirect('/signin')->with('success', 'lang.your terminated yourself');
    }

    public function updateProfile(Request $request){
        $post = $request->all();
        if(!empty($post)){
            $input = array(
                'name' =>  isset($post['name']) ? $post['name'] : '',
                'phone' => isset($post['phone']) ? $post['phone'] : '',
                'email' => isset($post['email']) ? $post['email'] : '',
                'updated_at' => date("Y-m-d H:i:s")
            );
            $user = User::where('id',$post['id'])->update($input);
            Session::flash('message',  __('lang.alert_profile_updated_successfully')); 
            return redirect()->back()->with('message', __('lang.alert_profile_updated_successfully'));
        }else{
            return redirect()->back();
        }

    }

    public function addCard(Request $request){
        $post = $request->all();
        
        request()->validate([
            'card_holder_name' => 'required',
            'card_type' => 'required',
            'card_no' => 'required',
            'month' => 'required',
            'year' => 'required',
            'cvv' => 'required'
        ]);

        if(!empty($post)){
            $input = array(
                'user_id' =>  isset($post['user_id']) ? $post['user_id'] : '',
                'card_type' => isset($post['card_type']) ? $post['card_type'] : 'VISA',
                'card_holder_name' => isset($post['card_holder_name']) ? $post['card_holder_name'] : '',
                'card_no' => isset($post['card_no']) ? $post['card_no'] : '',
                'month' => isset($post['month']) ? $post['month'] : '',
                'year' => isset($post['year']) ? $post['year'] : '',
                'cvv' => isset($post['cvv']) ? $post['cvv'] : '',
                'set_as_default' => 0,
                'created_at' => date("Y-m-d H:i:s")
            );
            $card = UserCards::insert($input);
            Session::flash('message', __('lang.alert_card_added_successfully')); 
            return redirect()->back()->with('message',__('lang.alert_card_added_successfully'));
        }else{
            return redirect()->back();
        }
    }

    public function deleteMyAddress($id){
        DeliveryAddresses::where('id', $id)->delete();       
        Session::flash('message', __('lang.alert_address_deleted_successfully')); 
        return redirect()->back()->with('message',__('lang.alert_address_deleted_successfully'));
    }

    public function addUpdateAddress(Request $request){
        $post = $request->all();
        if(!empty($post)){
            $user_id = 0;            
            if (Auth::check()) {
                $user_id = Auth::user()->id;
            }
            $postUpdate = array(
                'type' => $post['type'],
                'address' => $post['address'],
                'google_address' => $post['google_address'],
                'location_name' => $post['location_name'],
                'note' => $post['note'],
                'city' => $post['city'],
                'state' => $post['state'],
                'country' => $post['country'],
                'zipcode' => $post['zipcode'],
                'latitude' => $post['latitude'],
                'longitude' => $post['longitude'],
                'is_default' => 0
            );
            if(isset($post['id'])){
                $postUpdate['updated_at'] = date("Y-m-d H:i:s");
                $id = DeliveryAddresses::where('id',$post['id'])->update($postUpdate);
                return redirect()->back()->with('message',__('lang.alert_address_updated_successfully'));
            }else{
                $postUpdate['user_id'] = $user_id;
                $postUpdate['created_at'] = date("Y-m-d H:i:s");
                $id = DeliveryAddresses::insertGetId($postUpdate);
                return redirect()->back()->with('message',__('lang.alert_address_added_successfully'));
            }            
        }else{
            return redirect()->back()->with('message',__('lang.alert_select_mandatory_fields'));
        }
    }
}
