<?php

namespace App\Http\Controllers\inventory;


use App\Http\Controllers\Controller;
use App\Model\Inventory\Category;
use App\Model\Inventory\Banner;
use App\Model\Inventory\Whatsapp;
use App\Model\Inventory\Enquiry;
use App\Model\Inventory\Onesignal;
use App\Model\Inventory\Product;
use App\Model\Inventory\Product_meta;
use Oseintow\Shopify\Shopify;
use App\Model\Store\Store;
use App\Model\Gallery;
use App\Model\Userprofile;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ImportProduct;
use App\Imports\ImportCategory;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
use DB;
use Session;

$oneSignalDevicesArr = array();
class InventoryController extends Controller
{
    protected $shopify;
    public function __construct(Shopify $shopify)
    {
        $this->middleware('auth');
        $this->shopify = $shopify;
    }

    public function active(Request $request)
    {      
         $Channel_id_fltr = null;
        $page_fltr = 15; 
      
        $planID = Auth::user()->plan_id;
        $type = 'inventory';
        // $responce = check_plan($planID, $type);
        // if(!$responce){
        //     Session::flash('session-message', 'Sorry, You are not Permitted to access this Page!!');
        //     Session::flash('alert-class', 'alert-danger');
        //     // return Redirect::to('company');
        // }    
      
        $company_id = Auth::user()->company_id;
        $products = Product::leftJoin('product_metas', 'product_metas.product_id', '=', 'products.id')->leftJoin('stores', 'stores.id', '=', 'products.store_id')->where('products.status', 1)->where('products.company_id',$company_id)->select('products.*','product_metas.*');

         if ($request->has('AWBNo')){
            $products->where('title','LIKE','%'.$request->input('AWBNo').'%');
            $Order_id_fltr = $request->input('Order_id');
         }

         if ($request->has('Channel_id')){
            $products->where('products.store_id',$request->input('Channel_id'));
            $Channel_id_fltr = $request->input('Channel_id');
            }

         $pro_name_ro = $request->input('AWBNo');

        $orders = $products->paginate($page_fltr);
        $data = array(
                
                
                'Channel_id_fltr'=> $Channel_id_fltr,
                

            );


        
       return view('layouts.inventory.index',compact('pro_name_ro'))->with('data',$data)->with('products', $orders); 
    }   

    public function inactive(Request $request)
    {     
        $Channel_id_fltr = null;
         $page_fltr = 15; 
        $planID = Auth::user()->plan_id;
        $type = 'inventory';
        // $responce = check_plan($planID, $type);
        // if(!$responce){
        //     Session::flash('session-message', 'Sorry, You are not Permitted to access this Page!!');
        //     Session::flash('alert-class', 'alert-danger');
        //     return Redirect::to('company');
        // } 
        $company_id = Auth::user()->company_id; 
        $products = Product::leftJoin('product_metas', 'product_metas.product_id', '=', 'products.id')->leftJoin('stores', 'stores.id', '=', 'products.store_id')->where('products.status', 0)->where('products.company_id',$company_id); 
         if ($request->has('AWBNo')){
            $products->where('title','LIKE','%'.$request->input('AWBNo').'%');
            $Order_id_fltr = $request->input('Order_id');
         }

         if ($request->has('Channel_id')){
            $products->where('products.store_id',$request->input('Channel_id'));
            $Channel_id_fltr = $request->input('Channel_id');
            }

        $pro_name_ro = $request->input('AWBNo');

        $orders = $products->paginate($page_fltr);

        $data = array(
                
                
                'Channel_id_fltr'=> $Channel_id_fltr,
                

            );
        return view('layouts.inventory.inactive',compact('pro_name_ro'))->with('data',$data)->with('products', $orders);
    }
    public function allInventory(Request $request)
    {   
      $Channel_id_fltr = null;
         $page_fltr = 15; 
        $planID = Auth::user()->plan_id;
        $type = 'inventory';
        // $responce = check_plan($planID, $type);
        // if(!$responce){
        //     Session::flash('session-message', 'Sorry, You are not Permitted to access this Page!!');
        //     Session::flash('alert-class', 'alert-danger');
        //     return Redirect::to('company');
        // }   
        $company_id = Auth::user()->company_id; 
        $products = Product::leftJoin('product_metas', 'product_metas.product_id', '=', 'products.id')->leftJoin('stores', 'stores.id', '=', 'products.store_id')->where('products.company_id',$company_id);
         if ($request->has('AWBNo')){
            $products->where('title','LIKE','%'.$request->input('AWBNo').'%');
            $Order_id_fltr = $request->input('Order_id');
         }

         if ($request->has('Channel_id')){
            $products->where('products.store_id',$request->input('Channel_id'));
            $Channel_id_fltr = $request->input('Channel_id');
            }
         $orders = $products->paginate($page_fltr);
         $pro_name_ro = $request->input('AWBNo');

         $data = array(
                
                
                'Channel_id_fltr'=> $Channel_id_fltr,
                

            );
        return view('layouts.inventory.all_inventory',compact('pro_name_ro'))->with('data',$data)->with('products', $orders); 
    }
    public function new_product()
    {   
        $planID = Auth::user()->plan_id;
        $type = 'inventory';
        // $responce = check_plan($planID, $type);
        // if(!$responce){
        //     Session::flash('session-message', 'Sorry, You are not Permitted to access this Page!!');
        //     Session::flash('alert-class', 'alert-danger');
        //     return back();
        // }    
        $company_id = Auth::user()->company_id;
        $cat = Category::where('company_id',$company_id)->get();
        return view('layouts.inventory.newproduct')->with('categorys',$cat);
    }

    public function category()
    {   
        $planID = Auth::user()->plan_id;
        $type = 'inventory';
        // $responce = check_plan($planID, $type);
        // if(!$responce){
        //     Session::flash('session-message', 'Sorry, You are not Permitted to access this Page!!');
        //     Session::flash('alert-class', 'alert-danger');
        //     return Redirect::to('company');
        // }      
        $company_id = Auth::user()->company_id;
        $cat = Category::where('company_id',$company_id)->get();
        return view('layouts.inventory.category_list')->with('categorys',$cat);
    }
    public function categoryAdd(Request $request)
    {  
        $request->validate([
                'category_name' => 'required',
                'category_sku' => 'required',
                //'categ_image' => 'max:5000',
                //'categ_image' => 'image|mimes:jpeg,png,jpg',
                'categ_image' =>  'required|image|mimes:jpeg,png,jpg|max:5000', 
               
            ],[
            'category_name.required' => 'The category name field is required.',
            'category_sku.required' => 'The category slug field is required.',
            'categ_image.max' => 'The category image must be less than 5MB',
            'categ_image.image' => 'The category image must be in prescribed formate',
            
        ]);

        $company_id = Auth::user()->company_id;
        $category_name = $request->input('category_name');
        $category_sku = $request->input('category_sku');
        $category_desc = $request->input('category_desc');
        
        if ($request->hasFile('categ_image')) {
           $image = $request->file('categ_image');
           $name = time().'.'.$image->getClientOriginalExtension();
           $destinationPath = public_path('/uploads/categoryimage');
           $imagePath = $destinationPath. "/".  $name;
           $path = URL::to('/uploads/categoryimage/'.  $name);
           $image->move($destinationPath, $name);
           $Gallery =  Gallery::create([
               'path' => $path,
           ]);
           
                   function compressImage($source, $destination, $quality) {
                
                $info = getimagesize($source);
                
                if ($info['mime'] == 'image/jpeg') 
                $image = imagecreatefromjpeg($source);
                
                elseif ($info['mime'] == 'image/gif') 
                $image = imagecreatefromgif($source);
                
                elseif ($info['mime'] == 'image/png') 
                $image = imagecreatefrompng($source);
                
                imagejpeg($image, $destination, $quality);
                }
                compressImage($imagePath,$imagePath,60);
           
            $attach_data = $Gallery->id;
        }
        else{
           $attach_data = 0;
        }    
        $category = Category::create([
            'company_id' => $company_id,
            'name' => $category_name, 
            'sku' => $category_sku,
            'description' => $category_desc, 
            'images' => $attach_data
        ]);

        if($category->id){           
            Session::flash('session-message', 'Successfully, Category added!!.');
            Session::flash('alert-class', 'alert-success');
            return back();
         
        }else{
            Session::flash('session-message', '!!Try again');
            Session::flash('alert-class', 'alert-danger');
            return back();
        }


        
    }

    public function categoryedit($id)
    {
        $planID = Auth::user()->plan_id;
        $type = 'inventory';
        // $responce = check_plan($planID, $type);
        // if(!$responce){
        //     Session::flash('session-message', 'Sorry, You are not Permitted to access this Page!!');
        //     Session::flash('alert-class', 'alert-danger');
        //     return back();
        // }       
        // $Category = Category::where('id', $id)->first();
        
        $Category = Category::leftJoin('galleries', 'category.images', '=', 'galleries.id')->select('category.*','galleries.path')
            ->where('category.id', $id)->first();
        return view('layouts.inventory.category_edit')->with('Category', $Category);
    }

    public function update(Request $request)
    {
        $request->validate([
                'category_name' => 'required',
                'category_sku' => 'required',
                'categ_image' => 'max:5000',
                
            ],[
            'category_name.required' => 'The category name field is required.',
            'category_sku.required' => 'The category slug field is required.',
            'categ_image.max' => 'The category image must be less than 5MB',
            
        ]);
        if ($request->hasFile('categ_image')) {
           $image = $request->file('categ_image');
           $name = time().'.'.$image->getClientOriginalExtension();
           $destinationPath = public_path('/uploads/categoryimage');
           $imagePath = $destinationPath. "/".  $name;
           $path = URL::to('/uploads/categoryimage/'.  $name);
           $image->move($destinationPath, $name);
           $Gallery =  Gallery::create([
               'path' => $path,
           ]);
            $attach_data = $Gallery->id;
        }
        else{
           $attach_data = 0;
        }  
        $Category = Category::where('id', $request->input('cat_id'))->first();
        $Category->name = $request->input('category_name');
        $Category->sku = $request->input('category_sku');
        $Category->description = $request->input('category_desc');  
        if ($request->hasFile('categ_image')) {
            $Category->images = $attach_data;
        }
        // $Category->images = $attach_data;        
        $Category->save();
        

        Session::flash('session-message', 'Category Successfully Updated.');
        Session::flash('alert-class', 'alert-success');
        return back();

    }

    public function destroy($id)
    {
        $Category = Category::findOrFail($id);
        $Category->delete();
        Session::flash('session-message', 'Category Successfully Deleted.');
        Session::flash('alert-class', 'alert-success');
       
        return back();
    }

    
    public function productAdd(Request $request)
    {       

         $request->validate([
                'prod_name' => 'required',
                
                'prod_sku' => 'required',
                'prod_quantity' => 'required',                
                'prod_image' => 'max:5000',
                'prod_image1' => 'max:5000',
                'prod_image2' => 'max:5000',
            ],[
            'prod_name.required' => 'The product name field is required.',
            
            'prod_sku.required' => 'The product sku field is required.',
            'prod_quantity.required' => 'The product quantity field is required.',
            'prod_image.max' => 'The product image must be less than 5MB',
            'prod_image1.max' => 'The product image must be less than 5MB',
            'prod_image2.max' => 'The product image must be less than 5MB',
            
            
        ]);

        $company_id = Auth::user()->company_id;       
        $prod_cat = $request->input('prod_cat');
        if ($request->has('prod_cat')){
          $prod_cat = implode(',',$prod_cat);
          }
          else{
           $prod_cat = null;
          }
        
        if ($request->hasFile('prod_image')) {
           $image = $request->file('prod_image');
           //Image optimization code
       
           //End of image optimization code   
           
           $name = 'img1'.time().'.'.$image->getClientOriginalExtension();
           $destinationPath = public_path('/uploads/productimage');
           $imagePath = $destinationPath. "/".  $name;
         
           $path = URL::to('/uploads/productimage/'.  $name);
           //$path = "https://dev.marketingmindz.com/laravel/shipjunction_updated/public/uploads/productimage/".  $name;
           $image->move($destinationPath, $name);
           $Gallery =  Gallery::create([
               'path' => $path,
           ]);
                
                     function compressImage($source, $destination, $quality) {
                
                $info = getimagesize($source);
                
                if ($info['mime'] == 'image/jpeg') 
                $image = imagecreatefromjpeg($source);
                
                elseif ($info['mime'] == 'image/gif') 
                $image = imagecreatefromgif($source);
                
                elseif ($info['mime'] == 'image/png') 
                $image = imagecreatefrompng($source);
                
                imagejpeg($image, $destination, $quality);
                }
                compressImage($imagePath,$imagePath,60);
           
           $attach_data = $Gallery->id;
        }
        else{
           $attach_data = 0;
        }
        
        //image 2
         if ($request->hasFile('prod_image1')) {
           $image = $request->file('prod_image1');
           $name = 'img2'.time().'.'.$image->getClientOriginalExtension();
           $destinationPath = public_path('/uploads/productimage');
           $imagePath = $destinationPath. "/".  $name;
           $path = URL::to('/uploads/productimage/'.  $name);
           //$path = "https://dev.marketingmindz.com/laravel/shipjunction_updated/public/uploads/productimage/".  $name;
           $image->move($destinationPath, $name);
           $imagep2 = $path;
             function compressImage($source, $destination, $quality) {
                
                $info = getimagesize($source);
                
                if ($info['mime'] == 'image/jpeg') 
                $image = imagecreatefromjpeg($source);
                
                elseif ($info['mime'] == 'image/gif') 
                $image = imagecreatefromgif($source);
                
                elseif ($info['mime'] == 'image/png') 
                $image = imagecreatefrompng($source);
                
                imagejpeg($image, $destination, $quality);
                }
                compressImage($imagePath,$imagePath,60);
           
           
        }
        else{
           $imagep2 = '';
        }
        
        //image 3
         if ($request->hasFile('prod_image2')) {
           $image = $request->file('prod_image2');
           $name = 'img3'.time().'.'.$image->getClientOriginalExtension();
           $destinationPath = public_path('/uploads/productimage');
           $imagePath = $destinationPath. "/".  $name;
           $path = URL::to('/uploads/productimage/'.  $name);
           //$path = "https://dev.marketingmindz.com/laravel/shipjunction_updated/public/uploads/productimage/".  $name;
           $image->move($destinationPath, $name);
           $imagep3 = $path;
             function compressImage($source, $destination, $quality) {
                
                $info = getimagesize($source);
                
                if ($info['mime'] == 'image/jpeg') 
                $image = imagecreatefromjpeg($source);
                
                elseif ($info['mime'] == 'image/gif') 
                $image = imagecreatefromgif($source);
                
                elseif ($info['mime'] == 'image/png') 
                $image = imagecreatefrompng($source);
                
                imagejpeg($image, $destination, $quality);
                }
                compressImage($imagePath,$imagePath,60);
        }
        else{
           $imagep3 = '';
        }
        
        //videoadd
         if ($request->hasFile('prod_video')) {
           $image = $request->file('prod_video');
           $name = 'vid'.time().'.'.$image->getClientOriginalExtension();
           $destinationPath = public_path('/uploads/productvideo');
           $imagePath = $destinationPath. "/".  $name;
           $path = URL::to('/uploads/productvideo/'.  $name);
           //$path = "https://dev.marketingmindz.com/laravel/shipjunction_updated/public/uploads/productimage/".  $name;
           $image->move($destinationPath, $name);
           $videop = $path;
        }
        else{
           $videop = '';
        } 

        $Product = Product::create([
            'company_id'=>$company_id,
              'title' => $request->input('prod_name'),
              'slug' => $request->input('prod_sku'),
              'product_type' => 'simple',
              'status' => $request->input('prod_stock'),
              'description' => $request->input('prod_desc'),
              'sku' => $request->input('prod_sku'),
              'price' =>$request->input('prod_price'),
            //   'length' =>  $request->input('length'),
            //   'width' => $request->input('width'),
            //   'height' =>  $request->input('height'),
            //   'weight' => $request->input('prod_weight'),
          ]);
        $Product_meta = Product_meta::create([
           'Product_id' => $Product->id,
        //   'tax' =>  $request->input('prod_tax'),
           'manage_stock' => 1,
           'stock_quantity' =>  $request->input('prod_quantity'),
        //   'bin_no'=>  $request->input('bin_no'),
        //   'product_location'=>  $request->input('product_location'),
        //   'upc_code'=>  $request->input('upc_code'),
           'categories' => $prod_cat,
           'images' => $attach_data,
           'image2' => $imagep2,
           'image3' => $imagep3,
           'video' => $videop
        ]);       
        if($Product_meta->id){
            Session::flash('session-message', 'Successfully, add product!!.');
            Session::flash('alert-class', 'alert-success');
            return Redirect::to('/inventory/active');       
        }else{
            Session::flash('session-message', '!!Try again');
            Session::flash('alert-class', 'alert-danger');
            return back();
        }


        
    }

    public function destroy_product($id)
   {
    $planID = Auth::user()->plan_id;
    $type = 'inventory';
    // $responce = check_plan($planID, $type);
    // if(!$responce){
    //     Session::flash('session-message', 'Sorry, You are not Permitted to access this Page!!');
    //     Session::flash('alert-class', 'alert-danger');
    //     return back();
    // }    

       $Product = Product::findOrFail($id);
       $Product->delete();
       $Product_meta = Product_meta::where('Product_id',$id)->first();
       $Product_meta->delete();
       Session::flash('session-message', 'Product Successfully Deleted.');
       Session::flash('alert-class', 'alert-success');        
       return back();
   }


   public function edit_product($id)
   {
    $planID = Auth::user()->plan_id;
    $type = 'inventory';
    // $responce = check_plan($planID, $type);
    // if(!$responce){
    //     Session::flash('session-message', 'Sorry, You are not Permitted to access this Page!!');
    //     Session::flash('alert-class', 'alert-danger');
    //     return back();
    // }    
       $company_id = Auth::user()->company_id; 
       $Category = Category::where('company_id',$company_id)->get();
       $product = Product::leftJoin('product_metas', 'product_metas.product_id', '=', 'products.id')
       ->leftjoin('galleries', 'product_metas.images', '=', 'galleries.id')
       ->select('product_metas.*', 'products.*','galleries.path')
       ->where('products.id', $id)
       ->first();
       return view('layouts.inventory.editproduct')->with('product', $product)->with('categorys', $Category);
   }

   public function update_product(Request $request)
   {
       
        $request->validate([
           'prod_name' => 'required',
           'prod_price' => 'required',
           'prod_sku' => 'required',
           'prod_quantity' => 'required',
           'prod_image' => 'max:5000',
                'prod_image1' => 'max:5000',
                'prod_image2' => 'max:5000',
        //   'prod_weight' => 'required',
        //   'length' => 'required',
        //   'width' => 'required',
        //   'height' => 'required',            
        //   'prod_tax' => 'required',   
           ],
           [
           'prod_name.required' => 'The product name field is required.',
           'prod_price.required' => 'The product price field is required.',
           'prod_sku.required' => 'The product sku field is required.',
           'prod_quantity.required' => 'The product quantity field is required.',
           'prod_image.max' => 'The product image must be less than 5MB',
            'prod_image1.max' => 'The product image must be less than 5MB',
            'prod_image2.max' => 'The product image must be less than 5MB',
        //   'prod_weight.required' => 'The product weight field is required.',
        //   'length.required' => 'The product length field is required.',
        //   'width.required' => 'The product width field is required.',
        //   'height.required' => 'The product height field is required.',
        //   'prod_tax.required' => 'The product tax field is required.',
                   ]);
       $id = $request->input('id');
       $prod_cat = $request->input('prod_cat');
       if ($request->has('prod_cat')){
        $prod_cat = implode(',',$prod_cat);
       }
       else{
       $prod_cat = null;
       }        

       $request->hasFile('prod_image');
     


       if ($request->hasFile('prod_image')) {
         
           $image = $request->file('prod_image');
           $name = time().'.'.$image->getClientOriginalExtension();
           $destinationPath = public_path('/uploads/productimage');
           $imagePath = $destinationPath. "/".  $name;
           $path = URL::to('/uploads/productimage/'.  $name);
           $image->move($destinationPath, $name);
           $Gallery =  Gallery::create([
               'path' => $path,
           ]);
           $attach_data = $Gallery->id;
       }
       else{
           $attach_data = 0;
       }
       
       //image 2
         if ($request->hasFile('prod_image1')) {
           $image = $request->file('prod_image1');
           $name = 'img2'.time().'.'.$image->getClientOriginalExtension();
           $destinationPath = public_path('/uploads/productimage');
           $imagePath = $destinationPath. "/".  $name;
           $path = URL::to('/uploads/productimage/'.  $name);
           //$path = "https://dev.marketingmindz.com/laravel/shipjunction_updated/public/uploads/productimage/".  $name;
           $image->move($destinationPath, $name);
           $imagep2 = $path;
        }
        else{
           $imagep2 = '';
        }
        
        //image 3
         if ($request->hasFile('prod_image2')) {
           $image = $request->file('prod_image2');
           $name = 'img3'.time().'.'.$image->getClientOriginalExtension();
           $destinationPath = public_path('/uploads/productimage');
           $imagePath = $destinationPath. "/".  $name;
           $path = URL::to('/uploads/productimage/'.  $name);
           //$path = "https://dev.marketingmindz.com/laravel/shipjunction_updated/public/uploads/productimage/".  $name;
           $image->move($destinationPath, $name);
           $imagep3 = $path;
        }
        else{
           $imagep3 = '';
        }
        
        //videoadd
         if ($request->hasFile('prod_video')) {
           $image = $request->file('prod_video');
           $name = 'vid'.time().'.'.$image->getClientOriginalExtension();
           $destinationPath = public_path('/uploads/productvideo');
           $imagePath = $destinationPath. "/".  $name;
           $path = URL::to('/uploads/productvideo/'.  $name);
           //$path = "https://dev.marketingmindz.com/laravel/shipjunction_updated/public/uploads/productimage/".  $name;
           $image->move($destinationPath, $name);
           $videop = $path;
        }
        else{
           $videop = '';
        } 
        
       $Product = Product::where('id', $id)->first();
       $Product->title = $request->input('prod_name');
       $Product->slug = $request->input('prod_sku');
       $Product->product_type = 'simple';
       $Product->status = $request->input('prod_stock');
       $Product->description = $request->input('prod_desc');
       $Product->sku = $request->input('prod_sku');
       $Product->price = $request->input('prod_price');
    //   $Product->length = $request->input('length');
    //   $Product->width =  $request->input('width');
    //   $Product->height = $request->input('height');
    //   $Product->weight = $request->input('prod_weight');
       $Product->save();        

       $Product_meta = Product_meta::where('Product_id', $id)->first();
    //   $Product_meta->tax = $request->input('prod_tax');
       $Product_meta->manage_stock = 1;
       $Product_meta->stock_quantity = $request->input('prod_quantity');
    //   $Product_meta->bin_no = $request->input('bin_no');
    //   $Product_meta->product_location = $request->input('product_location');
    //   $Product_meta->upc_code = $request->input('upc_code');
       $Product_meta->categories = $prod_cat;
       if ($request->hasFile('prod_image')) {
            $Product_meta->images = $attach_data;
       }
       if ($request->hasFile('prod_image1')) {
            $Product_meta->image2 = $imagep2;
       }
       if ($request->hasFile('prod_image2')) {
            $Product_meta->image3 = $imagep3;
       }
       if ($request->hasFile('prod_video')) {
            $Product_meta->video = $videop;
       }
               

       if($Product_meta->save()){
          Session::flash('session-message', 'Product Successfully Updated.');
          Session::flash('alert-class', 'alert-success');          
           return back();
       }else{
           Session::flash('session-message', '!!Try again');
           Session::flash('alert-class', 'alert-danger');
           return back();
       }    }

    
     public function importExcel(Request $request){
       
        try {
             Excel::import(new ImportProduct, request()->file('import_file'));
        
             Session::flash('session-message', 'Product successfully imported !!');
             Session::flash('alert-class', 'alert-success');
             return back();
         } catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
              $failures = $e->failures();
              $err = null;
              $row = null; 
              foreach ($failures as $failure) {
                 
                  $row = $row.$failure->row();
                  $err = $err.$failure->errors()[0].' ROW : '.$row; // Actual error messages from Laravel 
              }
             $err = str_replace('.', ', ', $err);
            Session::flash('session-message', $err);
            Session::flash('alert-class', 'alert-danger');  
             return back();
         }
 
        
     }
     
        public function importCatExcel(Request $request){
       
        try {
             Excel::import(new ImportCategory, request()->file('import_file'));
        
             Session::flash('session-message', 'Category successfully imported !!');
             Session::flash('alert-class', 'alert-success');
             return back();
         } catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
              $failures = $e->failures();
              $err = null;
              $row = null; 
              foreach ($failures as $failure) {
                 
                  $row = $row.$failure->row();
                  $err = $err.$failure->errors()[0].' ROW : '.$row; // Actual error messages from Laravel 
              }
             $err = str_replace('.', ', ', $err);
            Session::flash('session-message', $err);
            Session::flash('alert-class', 'alert-danger');  
             return back();
         }
 
        
     }
     


     /*--------------------Shopify inventory sync-------------------*/

    public function Shopify_inventory_sync(){
      $fetch_stores = $this->fetchStoreDetails();
      $ordersCount = '';

      foreach ($fetch_stores as $value) {
          $filterDate = $this->fetchProductLastdate($value->id);
          $filter = $this->countfilterCondition($filterDate);

         $ordersCount = $this->shopify->setShopUrl($value->store_url)->setAccessToken($value->api_password)
              ->get('admin/products/count.json', $filter);
            
          $ordersCounts = $ordersCount - 1;
          $loopSize = ceil($ordersCounts /100);
           
          for ($x = 1; $x <= $loopSize; $x++) {
              $filterId = $this->fetchProductLastId($value->id);
              $storeData = array(
                              'store_id' => $value->id,
                              'shop_url' => $value->store_url,
                              'filter_Id' => $filterId,
                              'acessToken' => $value->api_password,
                          );

              $syncProduct = $this->getProducts($storeData);
          }

          if($ordersCounts == 0){
              $store = array(
                'store_id' => $value->id,
                'shop_url' => $value->store_url,
                'acessToken' => $value->api_password,
              );

             $quantity_res = $this->update_shopify_inventory($store);
          }
      }
     
      
      
      if($ordersCounts != 0){
          Session::flash('session-message', 'Products Successfully Sync.');
          Session::flash('alert-class', 'alert-success');          
          return back();
       }else{
        
          if($quantity_res) {
            Session::flash('session-message', 'Products Quantity Updated.');
            Session::flash('alert-class', 'alert-success');          
            return back();
          }else{
            Session::flash('session-message', '!!Products Already Sync');
            Session::flash('alert-class', 'alert-danger');
            return back();
          }         
          
       }  

      

     
      
    }

    /*---------------------------Update current product inventory--------------------------*/
    private function update_shopify_inventory($store){
        $response = '';
        $products = $this->shopify->setShopUrl($store['shop_url'])
        ->setAccessToken($store['acessToken'])
        ->get('admin/products.json');
        $store_id = $store['store_id'];
        $companyId = Auth::user()->company_id;
        
                 
        foreach ($products as $value) {
            
            if(!empty($value->variants)){
                foreach ($value->variants as $variants) { 
                    if($variants->inventory_quantity > 0){
                      $product = Product::join('product_metas', 'products.id', '=', 'product_metas.id')->where('product_metas.stock_quantity', '!=', $variants->inventory_quantity)->where('products.product_number', $variants->id)->first();
                        
                        if($product){
                            $products = Product_meta::where('id',$product->id)->first();         
                            $products->stock_quantity = $variants->inventory_quantity;
                            $products->save();
                            return true;
                        }
                    }
                }
            }
        };

        
        
       
    }

    /*
    * returns Collection
    */
    private function getProducts($storeData)
    {

        $filter = $this->filterCondition($storeData['filter_Id']);
        $store_id = $storeData['store_id'];
        
      try{
          $products = $this->shopify->setShopUrl($storeData['shop_url'])
            ->setAccessToken($storeData['acessToken'])
            ->get('admin/products.json', $filter);

           
          $companyId = Auth::user()->company_id;

          $products->each(function($value) use ($store_id, $companyId){            
            
            if(!empty($value->variants)){

                foreach ($value->variants as $variants) { 
                  if($variants->inventory_quantity > 0){
                      
                      
                      if($value->image){
                        $image = $value->image->src;
                      }else{
                        $image = '';
                      }
                      

                      $Gallery =  Gallery::create([
                         'path' => $image,
                      ]);
                      $attach_data = $Gallery->id;

                      $Product = Product::create([
                            'store_id' => $store_id,
                            'store_type' => 'SP',
                            'product_number' => $variants->id,
                            'product_parent_number' => $variants->product_id,
                            'company_id'=>$companyId,
                            'title' => $value->title.'('.$variants->title.')',
                            'slug' => '',
                            'product_type' => 'simple',
                            'status' => 1,
                            'description' => $variants->title,
                            'sku' => $variants->sku,
                            'price' => $variants->price,
                            'length' =>  0,
                            'width' => 0,
                            'height' =>  0,
                            'weight' => $variants->weight,
                            'product_filter_date' => $variants->created_at
                      ]);
                      $Product_meta = Product_meta::create([
                         'Product_id' => $Product->id,
                         'tax' =>  0,
                         'manage_stock' => 1,
                         'stock_quantity' =>  $variants->inventory_quantity,
                         'categories' => '',
                         'images' => $attach_data,
                      ]); 



                  }                 
                  
                  
                }

            }
            
            

          });
           
      }catch (exception $e) {
        echo $e->getMessage();
            return false;
      }
    }

    private function fetchProductLastdate($storeId){
      $productDetail = Product::where('store_id' , $storeId)->select('product_filter_date')->orderBy('id', 'DESC')->first();
      if ($productDetail) {
            return $productDetail->product_filter_date;
        }else{
            return false;
        }
        
    }   

    private function fetchProductLastId($storeId){
      $orderDetail = Product::where('store_id' , $storeId)->select('product_parent_number')->orderBy('id', 'DESC')->first();
      if ($orderDetail) {
            return $orderDetail->product_parent_number;
        }else{
            return false;
        }
        
    } 

    private function countfilterCondition($date){
        if($date){
            $filter = ['order' => 'created_at ASC', 'created_at_min' => $date];
            return $filter;
        }else{
            $filter = ['order' => 'created_at ASC'];
            return $filter;
        }
        
    }

    private function filterCondition($productId){
        if($productId){
            $filter = ['order' => 'created_at ASC', 'since_id' => $productId, 'limit' => 100];
            return $filter;
        }else{
            $filter = ['order' => 'created_at ASC', 'limit' => 100];
            return $filter;
        }
        
    }

    private function fetchStoreDetails(){
      $companyId = Auth::user()->company_id;
      $shopify_stores = Store::where([
                      ["company_id", $companyId],
                      ["store_type", 'sp'],
                                        ["status", 1],
                                        ["is_sync", 1],
                       ])->get();
      return $shopify_stores;
    }
    
    
    /*--------------------End Shopify inventory sync-------------------*/
    /*-------------------------Home Banner--------------------------------*/
    public function banner()
    {   
        $planID = Auth::user()->plan_id;
        $type = 'inventory';
        // $responce = check_plan($planID, $type);
        // if(!$responce){
        //     Session::flash('session-message', 'Sorry, You are not Permitted to access this Page!!');
        //     Session::flash('alert-class', 'alert-danger');
        //     return Redirect::to('company');
        // }      
        $company_id = Auth::user()->company_id;
        $ban = Banner::where('company_id',$company_id)->get();
        // echo "<pre>";
        // print_r($ban); die();
        return view('layouts.inventory.banner_list')->with('banners',$ban);
    }
    public function bannerAdd(Request $request)
    {  $request->validate([
                'banner_name' => 'required',
            ],[
            'banner_name.required' => 'The banner name field is required.',
        ]);

        $company_id = Auth::user()->company_id;
        $category_name = $request->input('banner_name');
        $category_desc = $request->input('banner_desc');
        
        if ($request->hasFile('ban_image')) {
           $image = $request->file('ban_image');
           $name = time().'.'.$image->getClientOriginalExtension();
           $destinationPath = public_path('/uploads/bannerimage');
           $imagePath = $destinationPath. "/".  $name;
           $path = URL::to('/uploads/bannerimage/'.  $name);
           $image->move($destinationPath, $name);
           $Gallery =  Gallery::create([
               'path' => $path,
           ]);
            $attach_data = $Gallery->id;
        }
        else{
           $attach_data = 0;
        }    
        $category = Banner::create([
            'company_id' => $company_id,
            'name' => $category_name, 
            'description' => $category_desc, 
            'images' => $attach_data
        ]);

        if($category->id){           
            Session::flash('session-message', 'Successfully, Banner added!!.');
            Session::flash('alert-class', 'alert-success');
            return back();
         
        }else{
            Session::flash('session-message', '!!Try again');
            Session::flash('alert-class', 'alert-danger');
            return back();
        }
    }

    public function banneredit($id)
    {
        $planID = Auth::user()->plan_id;
        $type = 'inventory';
        // $responce = check_plan($planID, $type);
        // if(!$responce){
        //     Session::flash('session-message', 'Sorry, You are not Permitted to access this Page!!');
        //     Session::flash('alert-class', 'alert-danger');
        //     return back();
        // }       
        // $Category = Category::where('id', $id)->first();
        
        $Category = Banner::leftJoin('galleries', 'banner.images', '=', 'galleries.id')->select('banner.*','galleries.path')
            ->where('banner.id', $id)->first();
        return view('layouts.inventory.banner_edit')->with('banner', $Category);
    }

    public function bannerupdate(Request $request)
    {
        $request->validate([
                'banner_name' => 'required',
            ],[
            'banner_name.required' => 'The banner name field is required.',
        ]);
        $Category = Banner::where('id', $request->input('cat_id'))->first();
        // echo "<pre>";print_r($request->input('banner_imagepath'));die();
        if($request->input('banner_imagepath') == ''){
            if ($request->hasFile('ban_image')) {
               $image = $request->file('ban_image');
               $name = time().'.'.$image->getClientOriginalExtension();
               $destinationPath = public_path('/uploads/bannerimage');
               $imagePath = $destinationPath. "/".  $name;
               $path = URL::to('/uploads/bannerimage/'.  $name);
               $image->move($destinationPath, $name);
               $Gallery =  Gallery::create([
                   'path' => $path,
               ]);
                $attach_data = $Gallery->id;
            }
            else{
               $attach_data = 0;
            }
            $Category->images = $attach_data;        
        }
        $Category->name = $request->input('banner_name');
        $Category->description = $request->input('banner_desc');   
        $Category->save();

        Session::flash('session-message', 'Banner Successfully Updated.');
        Session::flash('alert-class', 'alert-success');
        return back();
    }

    public function bannerdestroy($id)
    {
        $Category = Banner::findOrFail($id);
        $Category->delete();
        Session::flash('session-message', 'Category Successfully Deleted.');
        Session::flash('alert-class', 'alert-success');
       
        return back();
    }
    
    public function appbranding()
    {
        $planID = Auth::user()->plan_id;
        $type = 'inventory';
        // $responce = check_plan($planID, $type);
        // if(!$responce){
        //     Session::flash('session-message', 'Sorry, You are not Permitted to access this Page!!');
        //     Session::flash('alert-class', 'alert-danger');
        //     return back();
        // }       
        // $Category = Category::where('id', $id)->first();
        $company_id = Auth::user()->company_id;

        $branding = Userprofile::leftJoin('users', 'userprofiles.id', '=', 'users.id')->select('userprofiles.*')
            ->where('users.company_id', $company_id)->first();
        return view('layouts.inventory.branding')->with('branding', $branding);
    }


    public function appbrandingUpdate(Request $request)
   {
       $company_id = Auth::user()->company_id;
       if ($request->hasFile('app_logo')) {
         
           $image = $request->file('app_logo');
           $name = time().'.'.$image->getClientOriginalExtension();
           $destinationPath = public_path('/uploads/branding');
           $imagePath = $destinationPath. "/".  $name;
           $path = URL::to('/uploads/branding/'.  $name);
           $image->move($destinationPath, $name);
        //   $Gallery =  Gallery::create([
        //       'path' => $path,
        //   ]);
        //   $attach_data = $Gallery->id;
       }
       else{
           $path = '';
       }
       
       //image 2
        if ($request->hasFile('splash_screen')) {
           $image = $request->file('splash_screen');
           $name = 'img2'.time().'.'.$image->getClientOriginalExtension();
           $destinationPath = public_path('/uploads/branding');
           $imagePath = $destinationPath. "/".  $name;
           $sp_path = URL::to('/uploads/branding/'.  $name);
           $image->move($destinationPath, $name);
           //$path = "https://dev.marketingmindz.com/laravel/shipjunction_updated/public/uploads/productimage/".  $name;
        }
        else{
           $sp_path = '';
        }
        $branding = Userprofile::leftJoin('users', 'userprofiles.id', '=', 'users.id')->select('userprofiles.*')
            ->where('users.company_id', $company_id)->first();

       $branding->appname = $request->input('branding_name');
       if ($request->hasFile('app_logo')) {
            $branding->logo = $path;
       }
       if ($request->hasFile('splash_screen')) {
            $branding->splash_screen = $sp_path;
       }
       $branding->save();        


       if($branding->save()){
          Session::flash('session-message', 'Branding Successfully Updated.');
          Session::flash('alert-class', 'alert-success');          
           return back();
       }else{
           Session::flash('session-message', '!!Try again');
           Session::flash('alert-class', 'alert-danger');
           return back();
       }    
   }
   
   public function enquirylist()
    {
        // $planID = Auth::user()->plan_id;
        $type = 'inventory';
        // $responce = check_plan($planID, $type);
        // if(!$responce){
        //     Session::flash('session-message', 'Sorry, You are not Permitted to access this Page!!');
        //     Session::flash('alert-class', 'alert-danger');
        //     return back();
        // }       
        // $Category = Category::where('id', $id)->first();
        $company_id = Auth::user()->company_id;

        $enquiryData = Enquiry::leftJoin('products', 'enquiry.product_id', '=', 'products.id')->select('enquiry.*','products.title')
            ->where('enquiry.company_id', $company_id)->get();
        // dd($enquiryData);
        // print_r($enquiryData);die();
        return view('layouts.inventory.enquirylist')->with('enquiry', $enquiryData);
    }
    
    public function checkonesignalCred()
    {
        $company_id = Auth::user()->company_id;
        $getkeys = Onesignal::where('company_id', $company_id)->first();
        if($getkeys['app_id'] == '' || $getkeys['api_key'] == ''){
            return view('layouts.inventory.onesignalconfig');
        }else{
            return view('layouts.inventory.pushnotifyform')->with('notifymsg', '');
        }
    }
    public function saveOnesignalConfig(Request $request)
    {   
        $request->validate([
                'app_id' => 'required',
                'api_key' => 'required',
            ],[
            'app_id.required' => 'The app_id field is required.',
            'api_key.required' => 'The api_key field is required.',
        ]);
        $app_id = $request->input('app_id');
        $api_key = $request->input('api_key');
        $company_id = Auth::user()->company_id;
        
        $config = Onesignal::create([
            'company_id' => $company_id,
            'app_id' => $app_id, 
            'api_key' => $api_key, 
        ]);

        if($config->id){           
            Session::flash('session-message', 'Successfully, configuration Saved!!.');
            Session::flash('alert-class', 'alert-success');
            return back();
         
        }else{
            Session::flash('session-message', '!!Try again');
            Session::flash('alert-class', 'alert-danger');
            return back();
        }
    }
    
    public function sendPushNotification(Request $request)
    {   
        $title = $request->input('notification_title');
        $message = $request->input('notification_msg');
        $ann_id = '';
        $player_ids = array();
        $company_id = Auth::user()->company_id;
        $getkeys = Onesignal::where('company_id', $company_id)->first();
        $ONE_SIGNAL_APP_ID = $getkeys['app_id'];
        $ONE_SIGNAL_REST_API_KEY = $getkeys['api_key'];
        $player_ids = $this->viewOneSignalDevices(0,array(),$ONE_SIGNAL_APP_ID,$ONE_SIGNAL_REST_API_KEY);
        $response = $this->sendMessage($title,$message,$player_ids,$ann_id,$ONE_SIGNAL_APP_ID,$ONE_SIGNAL_REST_API_KEY);
        if(array_key_exists('recipients',$response)){           
            Session::flash('session-message', 'Successfull, Sent notification to '.$response['recipients'].' devices.');
            Session::flash('alert-class', 'alert-success');
            return back();
        }else{
            Session::flash('session-message', '!!Error Ocurred! Try again');
            Session::flash('alert-class', 'alert-danger');
            return back();
        }
    }
    public function sendMessage($title,$msg,$player_ids,$ann_id,$ONE_SIGNAL_APP_ID,$ONE_SIGNAL_REST_API_KEY){
        $res = array();
        $max_limit = 2000;
        $msg = str_replace('\n', "\n", $msg );
        $msg = str_replace('\r', "\r", $msg );
        $content = array(
            "en" => $msg
        );
    
        $count = count($player_ids);
        // echo $count; die;
        if($count > $max_limit) {
            $new_pids=array();
            $d=0;
            foreach($player_ids as $key => $val) {
                $new_pids[] = $val['id'];
                if($key%$max_limit == 0) {
                    $this->curl_OneSignal($title,$content,$new_pids,$ann_id,$ONE_SIGNAL_APP_ID,$ONE_SIGNAL_REST_API_KEY); // creating batches of 200 when total users > 200
                    $new_uids=array();
                } else {
                    if($key==$count) {
                        $this->curl_OneSignal($title,$content,$new_pids,$ann_id,$ONE_SIGNAL_APP_ID,$ONE_SIGNAL_REST_API_KEY);
                    }
                }
            }
        }else{
            $news_pids=array();
            foreach($player_ids as $key => $val) {
                $news_pids[] = $val['id'];
            }
            $res = $this->curl_OneSignal($title,$content,$news_pids,$ann_id,$ONE_SIGNAL_APP_ID,$ONE_SIGNAL_REST_API_KEY);
        }
        return $res;
    }
    public function curl_OneSignal($title,$content,$player_ids,$ann_id,$ONE_SIGNAL_APP_ID,$ONE_SIGNAL_REST_API_KEY) {
        
        $kv_array = array();
        $count = count($player_ids);
        
        $kv_array = $player_ids;
        $fields = array(
            'app_id' => $ONE_SIGNAL_APP_ID,
            // 'filters' => $kv_array,
            'include_player_ids' => $kv_array,
            'contents' => $content,
            'headings' => array( "en" => $title),
            'data'=>array("notificationFrom"=>"admin",
                "ann_id" => $ann_id
            )
        );
        $fields = json_encode($fields);
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
            'Authorization: Basic '.$ONE_SIGNAL_REST_API_KEY));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        $response = curl_exec($ch);
        curl_close($ch);
        $response = json_decode($response,true);
        return $response;
    }
    // list of onesignal users
    public function viewOneSignalDevices($offset,$arr,$ONE_SIGNAL_APP_ID,$ONE_SIGNAL_REST_API_KEY){
        $limit = 300;
    
        global $oneSignalDevicesArr;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/players?app_id=" . $ONE_SIGNAL_APP_ID."&limit=".$limit."&offset=".$offset);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
            'Authorization: Basic '.$ONE_SIGNAL_REST_API_KEY));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        $response = curl_exec($ch);
        curl_close($ch);
        $response = json_decode($response,true);
        $subscribe_checked = array();
        foreach($response['players'] as $key => $val){
            if($val['invalid_identifier'] != 1){
                $subscribe_checked[] = $val;
            }
            
        }
        $response['players'] = $subscribe_checked;
        $tc = $response["total_count"];
    
        if($offset == 0) {
            $oneSignalDevicesArr = array();
            $arr = $response['players'];
        } else{
            $arr = array_merge($arr,$response['players']);
        }
    
        if($tc >= $offset) {
            $offset = $offset+$limit;
            $this->viewOneSignalDevices($offset,$arr,$ONE_SIGNAL_APP_ID,$ONE_SIGNAL_REST_API_KEY);
        } else{
            $oneSignalDevicesArr = $arr;
        }
        if(!empty($oneSignalDevicesArr)){
            return $oneSignalDevicesArr;
        }
    }

    public function enquirylist_view(Request $request, $enqId){
   
    $type = 'inventory';
    // url()
    // echo env("APP_URL");
    // die();

       
       $companyid = Auth::user()->company_id; 
       $enquiry_1 = DB::table('enquiry')
                ->leftJoin('product_metas', 'product_metas.Product_id', '=', 'enquiry.product_id')
                ->leftJoin('products', 'product_metas.Product_id', '=', 'products.id')
                ->leftJoin('galleries', 'product_metas.images', '=', 'galleries.id')
                
                ->where('enquiry.company_id', $companyid)
                ->where('enquiry.id', $enqId)
                ->select('enquiry.contact_name','enquiry.message','enquiry.mobile_no','enquiry.email','galleries.path as imagepath','products.title as productname','products.id as productid')
                ->get();


       return view('layouts.inventory.enquirylistview')->with('enquiry_1', $enquiry_1);

      // echo "Hello";
    }



    public function whatsapp()
    {
        // $planID = Auth::user()->plan_id;
        $type = 'inventory';
        $company_id = Auth::user()->company_id;

         //$aboutus = Aboutus::leftJoin('users', 'aboutus.id', '=', 'users.id')->select('aboutus.*');

          $whatsapp = Whatsapp::where('company_id',$company_id)->first();
         // echo "<pre>";
         // print_r($whatsapp);
         // die();
    return view ('layouts.inventory.whatsapp')->with('whatsapp', $whatsapp);

    }

    public function whatsappStore(Request $request)
    {
        // dd($request);
     // $request->validate([
     //                'name' => 'required',//product name reuire           
     //                'facebook' => 'required', //product quantity reuire               
     //                'brandingname' => 'required',
     //                'instagram' => 'required',
     //                'phone ' => 'required',
     //                'address' => 'required',
     //                'email' => 'required',
     //                'website' => 'required',
                    
     //            ],[
     //                 'name.required' => ' field is required.',
     //                 'facebook.required' => ' field is required..',
     //                 'brandingname.required' => ' field is required..',
     //                 'instagram.required' => ' field is required..',
     //                 'phone.required' => ' field is required..',
     //                 'address.required' => ' field is required..',
     //                 'email.required' => ' field is required..',
     //                 'website.required' => ' field is required..',
     //             ]);
                   $company_id = Auth::user()->company_id;
                    //here we r doing if there is no data in the data base then insert the data . and if there is already data in the data base it update it
        // $whatsapp->appname = $request->input('sid');
                     $whatsapp = new Whatsapp;
                     $whatsapp->sid=$request->get('sid');
                     $whatsapp->company_id=$company_id;
                     $whatsapp->to_w=$request->get('to_w');
                     $whatsapp->from_w=$request->get('from_w');
                     $whatsapp->client_key=$request->get('client_key');
                     $whatsapp->status=$request->get('status');
                        
                 $whatsappdb = Whatsapp::first();

                if (empty($whatsappdb)) {
                   
                   $whatsapp->save();
                  }   else{
                    
                     
            $whatsapp = Whatsapp::where('company_id',$company_id)->first();//it takes the first row of table
            $whatsapp->sid = $request->input('sid');
            $whatsapp->to_w = $request->input('to_w');
            $whatsapp->from_w = $request->input('from_w'); 
            $whatsapp->client_key = $request->input('client_key');
            $whatsapp->status = $request->input('status');  
                   
            $whatsapp->save();

                  }
                if ($whatsapp) {
                    Session::flash('session-message', 'Cred Successfully Updated.');
              Session::flash('alert-class', 'alert-success');          
               return back();
                }else{
                    Session::flash('session-message', 'Error');
              Session::flash('alert-class', 'alert-error');          
               return back();
                }
                
                    
    //save();

      // return view ('layouts.inventory.whatsapp')->with ('success','data add');
    }

}
