/**
  * Edit Dailyspecail And Campaign Action
  * @param Request $request
  * @param $did
  * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
  * @throws \Exception
  * @author: Vini Dubey<*****@*****.**>
  * @since: xx-xx-xxxx
  */
 public function editDailyspecial(Request $request, $did)
 {
     $objProductCategory = ProductCategory::getInstance();
     $objCampaignModel = Campaigns::getInstance();
     $objProductModel = Products::getInstance();
     $supplierId = Session::get('fs_supplier')['id'];
     if ($request->isMethod('post')) {
         $rules = array('campaign_name' => 'unique:campaigns,campaign_name,' . $did . ',campaign_id', 'dailyspecial_image' => 'image');
         $validator = Validator::make($request->all(), $rules);
         if ($validator->fails()) {
             return Redirect::back()->withErrors($validator)->withInput();
         }
         $postData = $request->all();
         if (sizeof($postData['product']) >= 10) {
             if (Input::hasFile('dailyspecial_image')) {
                 $filePath = uploadImageToStoragePath(Input::file('dailyspecial_image'), 'flashsale', 'flashsale_' . $supplierId . '_' . time() . ".jpg");
                 $data['campaign_banner'] = $filePath;
             }
             $data['campaign_name'] = $postData['campaign_name'];
             $data['campaign_type'] = 2;
             $data['discount_type'] = '2';
             //            if ($data['discount_type'] == '1') {
             //                $data['discount_value'] = $postData['flatdiscount'];
             //            } else {
             $data['discount_value'] = $postData['percentagediscount'];
             //            }
             $validFrom = strtotime(str_replace("-", "", $postData['availablefromdate']));
             $validTo = strtotime(str_replace("-", "", $postData['availableuptodate']));
             $data['available_from'] = $validFrom;
             $data['available_upto'] = $validTo;
             $categ = $postData['productcategories'];
             if (isset($postData['productsubcategories'])) {
                 $subcat = $postData['productsubcategories'];
             } else {
                 $subcat = [];
             }
             $tmp = [];
             foreach ($categ as $index => $item) {
                 $tmp[$item] = array_values(array_filter(array_map(function ($cat) use($item) {
                     if (explode('_', $cat)[0] == $item) {
                         return explode('_', $cat)[1];
                     }
                 }, $subcat)));
             }
             $data['for_category_ids'] = json_encode($tmp);
             $data['by_user_id'] = $supplierId;
             //                $product = $postData['product'];
             $data['for_product_ids'] = implode(",", $postData['product']);
             $where = ['rawQuery' => 'campaign_id = ?', 'bindParams' => [$did]];
             $campaigns = 'Flashsale';
             //                print_a($data);
         } else {
             if (Input::hasFile('dailyspecial_image')) {
                 $filePath = uploadImageToStoragePath(Input::file('dailyspecial_image'), 'dailyspecial', 'dailyspecial_' . $supplierId . '_' . time() . ".jpg");
                 $data['campaign_banner'] = $filePath;
             }
             $data['campaign_name'] = $postData['campaign_name'];
             $data['campaign_type'] = $postData['campaign_type'];
             $data['discount_type'] = '2';
             $data['discount_value'] = $postData['percentagediscount'];
             $validFrom = strtotime(str_replace("-", "", $postData['availablefromdate']));
             $validTo = strtotime(str_replace("-", "", $postData['availableuptodate']));
             $data['available_from'] = $validFrom;
             $data['available_upto'] = $validTo;
             $categ = $postData['productcategories'];
             if (isset($postData['productsubcategories'])) {
                 $subcat = $postData['productsubcategories'];
             } else {
                 $subcat = [];
             }
             //                print_r($categ);
             //                print_a($subcat);
             $tmp = [];
             foreach ($categ as $index => $item) {
                 $tmp[$item] = array_values(array_filter(array_map(function ($cat) use($item) {
                     if (explode('_', $cat)[0] == $item) {
                         return explode('_', $cat)[1];
                     }
                 }, $subcat)));
             }
             //                print_a(json_encode($tmp));
             $data['for_category_ids'] = json_encode($tmp);
             $data['by_user_id'] = $supplierId;
             //                $product = $postData['product'];
             $data['for_product_ids'] = implode(",", $postData['product']);
             //                $data['for_product_ids'] = $postData['product'][0];
             $where = ['rawQuery' => 'campaign_id = ?', 'bindParams' => [$did]];
             $campaigns = 'Dailyspecial';
             //                print_a($data);
         }
         $campaignUpdate = $objCampaignModel->updateFlashsaleStatus($data, $where);
         if ($campaignUpdate) {
             if (isset($filePath)) {
                 deleteImageFromStoragePath($postData['oldImage']);
             }
             return Redirect::back()->with(['status' => 'success', 'msg' => $campaigns . ' ' . 'Updated Successfully.']);
         } else {
             return Redirect::back()->with(['status' => 'error', 'msg' => $campaigns . ' ' . 'Some Error try again.']);
         }
     }
     $where = ['rawQuery' => 'campaign_id = ? AND by_user_id = ?', 'bindParams' => [$did, $supplierId]];
     $selectedColumn = ['campaigns.*', 'users.username'];
     $dailyspecialInfo = $objCampaignModel->getAllFlashsaleDetails($where, $selectedColumn);
     //        print_a($dailyspecialInfo);
     if (isset($dailyspecialInfo) && !empty($dailyspecialInfo)) {
         foreach ($dailyspecialInfo as $flashkey => $flashval) {
             $categoryIds = json_decode($flashval->for_category_ids, true);
             $categoryMerg = array_merge(array_keys($categoryIds));
             $categoryMergee = array_merge(array_flatten($categoryIds));
             $categoryMerge = array_merge(array_keys($categoryIds), array_flatten($categoryIds));
             //                echo'<pre>';print_r($categoryMerg);
             //                echo'<pre>';print_r($categoryMergee);
             //                print_a($categoryMerge);
             $where = ['rawQuery' => 'category_id IN(' . implode(",", $categoryMerge) . ')'];
             $selectedColumn = [DB::raw('GROUP_CONCAT(DISTINCT category_name) AS category_name'), DB::raw('GROUP_CONCAT(DISTINCT category_id) AS category_id')];
             $getcategory = $objProductCategory->getCategoryNameById($where, $selectedColumn);
             foreach ($getcategory as $catkey => $catval) {
                 $dailyspecialInfo[$flashkey]->category = $catval->category_name;
                 $dailyspecialInfo[$flashkey]->category_ids = $catval->category_id;
             }
             $whereProduct = ['rawQuery' => 'product_id IN(' . $flashval->for_product_ids . ')'];
             $selectedColumn = [DB::raw('GROUP_CONCAT(DISTINCT product_name) AS product_name'), DB::raw('GROUP_CONCAT(DISTINCT product_id) AS product_id')];
             $getproduct = $objProductModel->getProductNameById($whereProduct, $selectedColumn);
             foreach ($getproduct as $prodkey => $prodval) {
                 $dailyspecialInfo[$flashkey]->product_name = $prodval->product_name;
                 $dailyspecialInfo[$flashkey]->product_id = $prodval->product_id;
             }
         }
         $where = ['rawQuery' => 'category_status = ? AND parent_category_id = ?', 'bindParams' => [1, 0]];
         $selectedColumn = ['category_id', 'category_name', 'category_status', 'for_shop_id'];
         $allactivecategories = $objProductCategory->getAllMainCategories($where, $selectedColumn);
         $where = ['rawQuery' => 'category_status = ?', 'bindParams' => [1]];
         $selectedColumn = ['product_categories.*', DB::raw('GROUP_CONCAT(category_id)AS main_category_id'), DB::raw('GROUP_CONCAT(category_name)AS main_category_name')];
         $allActiveSubcategories = $objProductCategory->getSubCategoriesForMaincategory($where, $selectedColumn);
         $mainCategory = array_filter(array_map(function ($category) {
             if ($category->parent_category_id == 0) {
                 return $category;
             }
         }, $allActiveSubcategories))[0];
         $finalCatData = [];
         foreach (explode(',', $mainCategory->main_category_id) as $index => $mainCatID) {
             foreach ($allActiveSubcategories as $subCatKey => $allActiveSubcategory) {
                 if ($allActiveSubcategory->parent_category_id == $mainCatID) {
                     $allActiveSubcategory->main_cat_name = explode(',', $mainCategory->main_category_name)[$index];
                     $finalCatData[$mainCatID] = $allActiveSubcategory;
                 }
             }
         }
         $where = ['rawQuery' => 'added_by = ? AND product_type = ?', 'bindParams' => [$supplierId, 0]];
         $selectedColumn = ['product_id', 'product_name'];
         $allproducts = $objProductModel->getAllSupplierProducts($where, $selectedColumn);
         return view('Supplier/Views/dailyspecial/editDailySpecial', ['dailyspecialInfo' => $dailyspecialInfo[0], 'activeCategory' => $allactivecategories, 'allProducts' => $allproducts, 'allcategories' => $finalCatData]);
     } else {
         return view('Supplier/Views/dailyspecial/editDailySpecial');
     }
 }
 /**
  * Edit category action
  * @param Request $request
  * @param $id Category id
  * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
  * @throws \FlashSale\Http\Modules\Admin\Models\Exception
  * @since 20-12-2015
  * @author Dinanath Thakur <*****@*****.**>
  */
 public function editCategory(Request $request, $id)
 {
     $objCategoryModel = ProductCategory::getInstance();
     if ($request->isMethod('post')) {
         Validator::extend('word_count', function ($field, $value, $parameters) {
             if (count(explode(' ', $value)) > 10) {
                 return false;
             }
             return true;
         }, 'Meta keywords should not contain more than 10 words.');
         $rules = array('category_name' => 'required|max:50|unique:product_categories,category_name,' . $id . ',category_id', 'category_desc' => 'max:255', 'status' => 'required', 'seo_name' => 'max:100', 'page_title' => 'max:70', 'meta_desc' => 'max:160', 'meta_keywords' => 'word_count');
         $validator = Validator::make($request->all(), $rules);
         if ($validator->fails()) {
             return Redirect::back()->with(["status" => 'error', 'msg' => 'Please correct the following errors.'])->withErrors($validator)->withInput();
         } else {
             if (Input::hasFile('category_image')) {
                 $filePath = uploadImageToStoragePath(Input::file('category_image'), 'category');
                 if ($filePath) {
                     $dataToUpdate['category_banner_url'] = $filePath;
                 }
             }
             $dataToUpdate['category_name'] = $request->input('category_name');
             $dataToUpdate['category_desc'] = $request->input('category_desc');
             $dataToUpdate['category_status'] = $request->input('status');
             $dataToUpdate['is_visible'] = $request->input('is_visible');
             $dataToUpdate['parent_category_id'] = $request->input('parent_category');
             $dataToUpdate['page_title'] = $request->input('page_title');
             $dataToUpdate['meta_description'] = $request->input('meta_desc');
             $dataToUpdate['meta_keywords'] = $request->input('meta_keywords');
             $whereForUpdate = ['rawQuery' => 'category_id =?', 'bindParams' => [$id]];
             $updateResult = $objCategoryModel->updateCategoryWhere($dataToUpdate, $whereForUpdate);
             if ($updateResult > 0) {
                 if (isset($filePath)) {
                     deleteImageFromStoragePath($request->input('old_image'));
                 }
                 return Redirect::back()->with(['status' => 'success', 'msg' => 'Category details has been updated.']);
             } else {
                 return Redirect::back()->with(['status' => 'info', 'msg' => 'Nothing to update.']);
             }
         }
     }
     $where = ['rawQuery' => 'category_id =?', 'bindParams' => [$id]];
     $categoryDetails = $objCategoryModel->getCategoryDetailsWhere($where);
     $allCategories = '';
     if ($categoryDetails) {
         //            $where = ['rawQuery' => 'category_status =?', 'bindParams' => [1]];
         $where = ['rawQuery' => '1'];
         $allCategories = $objCategoryModel->getAllCategoriesWhere($where);
         //            foreach ($allCategories as $key => $value) {
         //                $allCategories[$key]->display_name = $this->getCategoryDisplayName($value->category_id);
         //            }
     }
     return view('Admin/Views/category/editCategory', ['categoryDetails' => $categoryDetails, 'allCategories' => $allCategories]);
 }
 /**
  * Ajax handler
  * @param Request $request
  * @throws \FlashSale\Http\Modules\Supplier\Models\Exception
  * @since 09-12-2015
  * @author Dinanath Thakur <*****@*****.**>
  */
 public function ajaxHandler(Request $request)
 {
     $objModelUser = User::getInstance();
     $objModelUsersmeta = Usersmeta::getInstance();
     $userId = Session::get('fs_supplier')['id'];
     $where['user_id'] = $userId;
     $usersMetaDetails = $objModelUsersmeta->getUsersMetaDetailsWhere($where);
     $field = $request->input('name');
     if ($field) {
         $formEditableMethod = explode('/', $field);
         $method = $formEditableMethod[0];
     } else {
         $method = $request->input('method');
     }
     $objLocationModel = Location::getInstance();
     $objshopModal = Shop::getInstance();
     $objshopMetadataModal = ShopMetadata::getInstance();
     switch ($method) {
         case 'checkContactNumber':
             $validator = Validator::make($request->all(), ['contact_number' => 'required|unique:usersmeta,phone,' . $usersMetaDetails->id]);
             if ($validator->fails()) {
                 echo json_encode(false);
             } else {
                 echo json_encode(true);
             }
             break;
         case 'updateProfileInfo':
             //NOT YET COMPLETE, NEED COUNTRY DETAILS
             $rules = array('first_name' => 'required|max:255', 'last_name' => 'required|max:255', 'city' => 'required', 'state' => 'required', 'zipcode' => 'required', 'country' => 'required', 'contact_number' => 'required|unique:usersmeta,phone,' . $usersMetaDetails->id);
             $validator = Validator::make($request->all(), $rules);
             if ($validator->fails()) {
                 echo json_encode(array('status' => 2, 'message' => $validator->messages()->all()));
             } else {
                 $whereForUpdate['id'] = $userId;
                 $updateData['name'] = $request->input('first_name');
                 $updateData['last_name'] = $request->input('last_name');
                 $updatedResult = $objModelUser->updateUserWhere($updateData, $whereForUpdate);
                 $updateMetaData['addressline1'] = $request->input('address_line_1');
                 $updateMetaData['addressline2'] = $request->input('address_line_2');
                 $updateMetaData['city'] = $request->input('city');
                 $updateMetaData['state'] = $request->input('state');
                 $updateMetaData['country'] = $request->input('country');
                 //COUNTRY DETAILS IN DATABASE
                 $updateMetaData['zipcode'] = $request->input('zipcode');
                 $updateMetaData['phone'] = $request->input('contact_number');
                 $whereForUpdateMetaData['id'] = $usersMetaDetails->id;
                 $updatedMetaDataResult = $objModelUsersmeta->updateUsersMetaDetailsWhere($updateMetaData, $whereForUpdateMetaData);
                 if ($updatedResult || $updatedMetaDataResult) {
                     echo json_encode(array('status' => 1, 'message' => 'Successfully updated profile data.'));
                 } else {
                     echo json_encode(array('status' => 0, 'message' => 'Nothing to update.'));
                 }
             }
             break;
         case 'updateAvatar':
             if (Input::hasFile('file')) {
                 $validator = Validator::make($request->all(), ['file' => 'image']);
                 if ($validator->fails()) {
                     echo json_encode(array('status' => 2, 'message' => $validator->messages()->all()));
                 } else {
                     $filePath = uploadImageToStoragePath(Input::file('file'), 'useravatar', 'useravatar_' . $userId . '_' . time() . ".jpg");
                     if ($filePath) {
                         $updateData['profilepic'] = $filePath;
                         $whereForUpdate['id'] = $userId;
                         $updatedResult = $objModelUser->updateUserWhere($updateData, $whereForUpdate);
                         if ($updatedResult) {
                             if (!strpos(Session::get('fs_supplier')['profilepic'], 'placeholder')) {
                                 deleteImageFromStoragePath(Session::get('fs_supplier')['profilepic']);
                             }
                             Session::put('fs_supplier.profilepic', $filePath);
                             echo json_encode(array('status' => 1, 'message' => 'Successfully updated profile image . '));
                         } else {
                             echo json_encode(array('status' => 0, 'message' => 'Something went wrong, please reload the page and try again.'));
                         }
                     } else {
                         echo json_encode(array('status' => 0, 'message' => 'Something went wrong, please reload the page and try again.'));
                     }
                 }
             } else {
                 echo json_encode(array('status' => 2, 'message' => 'Please select file first.'));
             }
             break;
         case 'updatePassword':
             Validator::extend('passwordCheck', function ($attribute, $value, $parameters) {
                 return Hash::check($value, Auth::user()->getAuthPassword());
             }, 'Your current password is incorrect . ');
             $passwordRules = array('current_password' => 'required | passwordCheck', 'new_password' => 'required', 'confirm_password' => 'required | same:new_password');
             $passwordValidator = Validator::make($request->all(), $passwordRules);
             if ($passwordValidator->fails()) {
                 echo json_encode(array('status' => 2, 'message' => $passwordValidator->messages()->all()));
             } else {
                 $user = Auth::user();
                 $user->password = Hash::make($request->input('new_password'));
                 $user->save();
                 echo json_encode(array('status' => 1, 'message' => 'Your password has been successfully updated . '));
             }
             break;
         case 'getState':
             $countryId = $request->input('countryId');
             $where = ['rawQuery' => 'is_visible =? and location_type =? and parent_id =?', 'bindParams' => [0, 1, $countryId]];
             $allstates = $objLocationModel->getAllLocationsWhere($where);
             echo json_encode($allstates);
             break;
         case 'getCity':
             $stateId = $request->input('stateId');
             $where = ['rawQuery' => 'is_visible =? and location_type =? and parent_id =?', 'bindParams' => [0, 2, $stateId]];
             $allcities = $objLocationModel->getAllLocationsWhere($where);
             echo json_encode($allcities);
             break;
         case 'available_Shop':
             $available_Shops = $objshopModal->getAvailableShopDetails($userId);
             //echo "<pre>";print_r($available_Shops);die;
             return Datatables::of($available_Shops)->addColumn('action', function ($available_Shops) {
                 return '<span class="tooltips" title="Edit Shop Details." data-placement="top"> <a href="/supplier/editShop/' . $available_Shops->shop_id . '" class="btn btn-sm grey-cascade">
                                                 <i class="fa fa-pencil-square-o"></i>
                                             </a>
                                         </span> &nbsp;&nbsp;
                                         ';
             })->addColumn('status', function ($available_Shops) {
                 $button = '<td style="text-align: center">';
                 $button .= '<button class="btn ' . ($available_Shops->shop_status == "1" || $available_Shops->shop_status == "2" ? $available_Shops->shop_status == "1" ? "btn-success" : "btn-danger" : "btn-default") . ' customer-status" data-id="' . $available_Shops->shop_id . '"' . ($available_Shops->shop_status == "0" || $available_Shops->shop_status == "3" ? "disabled" : "") . '>' . ($available_Shops->shop_status == "1" || $available_Shops->shop_status == "2" ? $available_Shops->shop_status == "1" ? "Active" : "Inactive" : ($available_Shops->shop_status == "0" ? "Pending" : "Rejected")) . ' </button>';
                 $button .= '</td>';
                 return $button;
             })->removeColumn('shop_status')->make();
             break;
         case 'changeShopStatus':
             $Shop_Id = $request->input('ShopId');
             $Status = $request->input('status');
             $data1['shop_status'] = $Status;
             $where1 = ['rawQuery' => 'shop_id =? ', 'bindParams' => [$Shop_Id]];
             $updateResult = $objshopModal->updateShopWhere($data1, $where1);
             if ($updateResult) {
                 echo json_encode(['status' => 'success', 'msg' => 'Status has been changed.']);
             } else {
                 echo json_encode(['status' => 'error', 'msg' => 'Something went wrong, please reload the page and try again.']);
             }
             break;
         case 'updateStoreDetails':
             $field = $request->input('name');
             $field = explode('/', $field);
             $fieldName = $field[1];
             $store_metadata_id = $request->input('pk');
             $value = $request->input('value');
             $shopFlag = true;
             $data = array($fieldName => $value);
             //                echo "<pre>";print_r($store_metadata_id);die;
             if ($fieldName == 'shop_type' && $value == '0') {
                 //change shop_type to main
                 $merchantId = $field[2];
                 $shopId = $field[3];
                 $whereforShop = ['rawQuery' => 'shop_id =?', 'bindParams' => [$shopId]];
                 $data1 = array('shop_type' => 1);
                 $updateStoreType = $objshopMetadataModal->updateShopMetadataWhere($data1, $whereforShop);
             }
             if ($fieldName == 'shop_type' && $value == '1') {
                 //change shop_type to secondary
                 $merchantId = $field[2];
                 $shopId = $field[3];
                 $whereforShop = ['rawQuery' => 'shop_id =? and shop_metadata_id != ?', 'bindParams' => [$shopId, $store_metadata_id]];
                 $merchantStoreDetails = $objshopMetadataModal->getAllshopsMetadataWhere($whereforShop);
                 if (!empty($merchantStoreDetails)) {
                     $dataforstype = array('shop_type' => 0);
                     $whereforShopt = ['rawQuery' => 'shop_id =? and shop_metadata_id = ?', 'bindParams' => [$merchantStoreDetails[0]->shop_id, $merchantStoreDetails[0]->shop_metadata_id]];
                     $merchantStoreDetails = $objshopMetadataModal->updateShopMetadataWhere($dataforstype, $whereforShopt);
                 } else {
                     $shopFlag = false;
                     echo json_encode("You cant change main shop to secondary");
                     break;
                 }
             }
             if ($shopFlag) {
                 $whereforShopMeta = ['rawQuery' => 'shop_metadata_id =?', 'bindParams' => [$store_metadata_id]];
                 $updateResult = $objshopMetadataModal->updateShopMetadataWhere($data, $whereforShopMeta);
                 if ($updateResult) {
                     echo json_encode($updateResult);
                 }
             }
             break;
         case 'updateShopBanner':
             $shop_id = $request->input('shop_id');
             $whereforShop = ['rawQuery' => 'shop_id =? ', 'bindParams' => [$shop_id]];
             $selectedColumns = array('shop_id', 'shop_banner');
             $shopDetails = $objshopModal->getAllshopsWhere($whereforShop, $selectedColumns);
             if (isset($_FILES["shop_banner"]["name"]) && !empty($_FILES["shop_banner"]["name"])) {
                 $bannerFilePath = uploadImageToStoragePath(Input::file('shop_banner'), 'shopbanner', 'shopbanner_' . $userId . '_' . time() . ".jpg");
             } else {
                 $bannerFilePath = uploadImageToStoragePath($_SERVER['DOCUMENT_ROOT'] . "/assets/images/no-image.png", 'shopbanner', 'shopbanner_' . $userId . '_' . time() . ".jpg");
             }
             $shopdata = array('shop_banner' => $bannerFilePath);
             $updateBanner = $objshopModal->updateShopWhere($shopdata, $whereforShop);
             if ($updateBanner) {
                 deleteImageFromStoragePath($shopDetails[0]->shop_banner);
                 echo json_encode($updateBanner);
             }
             break;
         case 'updateShopLogo':
             $shop_id = $request->input('shop_id');
             $whereforShop = ['rawQuery' => 'shop_id =? ', 'bindParams' => [$shop_id]];
             $selectedColumns = array('shop_id', 'shop_logo');
             $shopDetails = $objshopModal->getAllshopsWhere($whereforShop, $selectedColumns);
             if (isset($_FILES["shop_logo"]["name"]) && !empty($_FILES["shop_logo"]["name"])) {
                 $logoFilePath = uploadImageToStoragePath(Input::file('shop_logo'), 'shoplogo', 'shoplogo_' . $userId . '_' . time() . ".jpg");
             } else {
                 $logoFilePath = uploadImageToStoragePath($_SERVER['DOCUMENT_ROOT'] . "/assets/images/no-image.png", 'shoplogo', 'shoplogo_' . $userId . '_' . time() . ".jpg");
             }
             $shopdata = array('shop_logo' => $logoFilePath);
             $updatelogo = $objshopModal->updateShopWhere($shopdata, $whereforShop);
             if ($updatelogo) {
                 deleteImageFromStoragePath($shopDetails[0]->shop_logo);
                 echo json_encode($updatelogo);
             }
             break;
         case 'updateSellerShop':
             $field = $request->input('name');
             $fieldName = explode('/', $field);
             $fieldName = $fieldName[1];
             $shop_id = $request->input('pk');
             $value = $request->input('value');
             $data = array($fieldName => $value);
             $whereforShop = ['rawQuery' => 'shop_id =? ', 'bindParams' => [$shop_id]];
             $updateResult = $objshopModal->updateShopWhere($data, $whereforShop);
             if ($updateResult) {
                 echo json_encode($updateResult);
             }
             break;
         case 'updateShopStatus':
             $shopMetaId = $request->input('shopMetaId');
             $status = $request->input('value');
             $supplierId = $request->input('supplierId');
             $data = array('sm_status_set_by' => $supplierId, 'shop_metadata_status' => $status);
             $whereforShopMeta = ['rawQuery' => 'shop_metadata_id =? ', 'bindParams' => [$shopMetaId]];
             $updateResult = $objshopMetadataModal->updateShopMetadataWhere($data, $whereforShopMeta);
             if ($updateResult) {
                 echo json_encode($updateResult);
             }
             break;
         default:
             break;
     }
 }
 /**
  * Edit category action
  * @param Request $request
  * @param $id Category id
  * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
  * @throws \FlashSale\Http\Modules\Supplier\Models\Exception
  * @since 29-01-2016
  * @author Dinanath Thakur <*****@*****.**>
  */
 public function editCategory(Request $request, $id)
 {
     $objCategoryModel = ProductCategory::getInstance();
     $userId = Session::get('fs_supplier')['id'];
     if ($request->isMethod('post')) {
         Validator::extend('word_count', function ($field, $value, $parameters) {
             if (count(explode(' ', $value)) > 10) {
                 return false;
             }
             return true;
         }, 'Meta keywords should not contain more than 10 words.');
         $rules = array('category_name' => 'required|max:50|unique:product_categories,category_name,' . $id . ',category_id', 'category_desc' => 'max:255', 'status' => 'required', 'seo_name' => 'max:100', 'page_title' => 'max:70', 'meta_desc' => 'max:160', 'meta_keywords' => 'word_count');
         $validator = Validator::make($request->all(), $rules);
         if ($validator->fails()) {
             return Redirect::back()->with(["status" => 'error', 'msg' => 'Please correct the following errors.'])->withErrors($validator)->withInput();
         } else {
             if (Input::hasFile('category_image')) {
                 $filePath = uploadImageToStoragePath(Input::file('category_image'), 'category');
                 if ($filePath) {
                     $dataToUpdate['category_banner_url'] = $filePath;
                 }
             }
             $dataToUpdate['category_name'] = $request->input('category_name');
             $dataToUpdate['category_desc'] = $request->input('category_desc');
             $dataToUpdate['category_status'] = $request->input('status');
             $dataToUpdate['parent_category_id'] = $request->input('parent_category');
             $dataToUpdate['page_title'] = $request->input('page_title');
             $dataToUpdate['meta_description'] = $request->input('meta_desc');
             $dataToUpdate['meta_keywords'] = $request->input('meta_keywords');
             $whereForUpdate = ['rawQuery' => 'category_id =?', 'bindParams' => [$id]];
             $updateResult = $objCategoryModel->updateCategoryWhere($dataToUpdate, $whereForUpdate);
             if ($updateResult > 0) {
                 if (isset($filePath)) {
                     deleteImageFromStoragePath($request->input('old_image'));
                 }
                 return Redirect::back()->with(['status' => 'success', 'msg' => 'Category details has been updated.']);
             } else {
                 return Redirect::back()->with(['status' => 'info', 'msg' => 'Nothing to update.']);
             }
         }
     }
     $where = ['rawQuery' => 'category_id =? AND category_status IN(0,1,2) AND created_by=?', 'bindParams' => [$id, $userId]];
     $categoryDetails = $objCategoryModel->getCategoryDetailsWhere($where);
     $allCategories = '';
     if ($categoryDetails) {
         $allCategories = $objCategoryModel->getAllCategoriesWhere(['rawQuery' => 'created_by IN (' . DB::raw("SELECT `id` FROM `users` WHERE `role` IN(4,5)") . ') OR created_by=? AND  category_status IN(0,1,2)', 'bindParams' => [$userId]]);
     }
     return view('Supplier/Views/category/editCategory', ['categoryDetails' => $categoryDetails, 'allCategories' => $allCategories]);
 }
 /**
  * @param Request $request
  * @throws \FlashSale\Http\Modules\Admin\Models\Exception
  */
 public function shopAjaxHandler(Request $request)
 {
     $inputData = $request->input();
     $field = $request->input('name');
     if ($field) {
         $formEditableMethod = explode('/', $field);
         $method = $formEditableMethod[0];
     } else {
         $method = $request->input('method');
     }
     //        $method = $request->input('method');
     $ObjShop = Shops::getInstance();
     $objshopMetadataModal = ShopMetadata::getInstance();
     $objLocationModel = Location::getInstance();
     $mainId = Session::get('fs_admin')['id'];
     if ($method) {
         switch ($method) {
             case 'pendingShop':
                 $where = array('rawQuery' => 'shop_status = ?', 'bindParams' => [0]);
                 $pending_Shop = $ObjShop->getShopDetails($where);
                 return Datatables::of($pending_Shop)->addColumn('ownedBy', function ($shop_details) {
                     return '' . $shop_details->name . '&nbsp;' . $shop_details->last_name . '';
                 })->addColumn('status', function ($shop_details) {
                     return ' <td style = "text-align: center" >
                                         <button class="btn btn-primary shop-status"
                                                 data-id = ' . $shop_details->shop_id . ' >Pending
                                         </button >
                                 </td > ';
                 })->removeColumn('name')->removeColumn('last_name')->removeColumn('shop_status')->make();
                 break;
             case 'AvailableShop':
                 $where = array('rawQuery' => 'shop_status = ? || shop_status = ?', 'bindParams' => [1, 2]);
                 $available_Shop = $ObjShop->getShopDetails($where);
                 //                    echo "<pre>"; print_r($available_Shop);die;
                 return Datatables::of($available_Shop)->addColumn('ownedBy', function ($shop_details) {
                     return '' . $shop_details->name . '&nbsp;' . $shop_details->last_name . '';
                 })->addColumn('action', function ($shop_details) {
                     $action = '<span class="tooltips" title="Edit Shop Details." data-placement="top"> <a href="/admin/edit-shop/' . $shop_details->shop_id . '" class="btn btn-sm grey-cascade " style="margin-left: 10%;">';
                     $action .= '<i class="fa fa-pencil-square-o"></i></a>';
                     $action .= '</span> &nbsp;&nbsp;';
                     $action .= '<span class="tooltips" title="Delete Shop" data-placement="top"> <a href="#" data-cid="' . $shop_details->shop_id . '" class="btn btn-danger delete-shop" style="margin-left: 10%;">';
                     $action .= '<i class="fa fa-trash-o"></i>';
                     $action .= '</a></span>';
                     return $action;
                 })->addColumn('status', function ($shop_details) use($mainId) {
                     $button = '<td style="text-align: center">';
                     $button .= '<button class="btn ' . ($shop_details->shop_status == 1 ? "btn-success" : "btn-danger") . ' supplier-status" data-id="' . $shop_details->shop_id . '"  data-set-by="' . $mainId . '">' . ($shop_details->shop_status == 1 ? "Active" : "Inactive") . ' </button>';
                     $button .= '<td>';
                     return $button;
                 })->removeColumn('name')->removeColumn('last_name')->removeColumn('shop_status')->make();
                 break;
             case 'updateSellerShop':
                 $field = $request->input('name');
                 $fieldName = explode('/', $field);
                 $fieldName = $fieldName[1];
                 $shop_id = $request->input('pk');
                 $value = $request->input('value');
                 $data = array($fieldName => $value);
                 $whereforShop = ['rawQuery' => 'shop_id =? ', 'bindParams' => [$shop_id]];
                 $updateResult = $ObjShop->updateShopWhere($data, $whereforShop);
                 if ($updateResult) {
                     echo json_encode($updateResult);
                 }
                 break;
             case 'updateStoreDetails':
                 $field = $request->input('name');
                 $field = explode('/', $field);
                 $fieldName = $field[1];
                 $store_metadata_id = $request->input('pk');
                 $value = $request->input('value');
                 $shopFlag = true;
                 $data = array($fieldName => $value);
                 if ($fieldName == 'shop_type' && $value == '0') {
                     //change shop_type to main
                     $merchantId = $field[2];
                     $shopId = $field[3];
                     $whereforShop = ['rawQuery' => 'shop_id =?', 'bindParams' => [$shopId]];
                     $data1 = array('shop_type' => 1);
                     $updateStoreType = $objshopMetadataModal->updateShopMetadataWhere($data1, $whereforShop);
                 }
                 if ($fieldName == 'shop_type' && $value == '1') {
                     //change shop_type to secondary
                     $merchantId = $field[2];
                     $shopId = $field[3];
                     $whereforShop = ['rawQuery' => 'shop_id =? and shop_metadata_id != ?', 'bindParams' => [$shopId, $store_metadata_id]];
                     $merchantStoreDetails = $objshopMetadataModal->getAllshopsMetadataWhere($whereforShop);
                     if (!empty($merchantStoreDetails)) {
                         $dataforstype = array('shop_type' => 0);
                         $whereforShopt = ['rawQuery' => 'shop_id =? and shop_metadata_id = ?', 'bindParams' => [$merchantStoreDetails[0]->shop_id, $merchantStoreDetails[0]->shop_metadata_id]];
                         $merchantStoreDetails = $objshopMetadataModal->updateShopMetadataWhere($dataforstype, $whereforShopt);
                     } else {
                         $shopFlag = false;
                         echo json_encode("You cant change main shop to secondary");
                         break;
                     }
                 }
                 if ($shopFlag) {
                     $whereforShopMeta = ['rawQuery' => 'shop_metadata_id =?', 'bindParams' => [$store_metadata_id]];
                     $updateResult = $objshopMetadataModal->updateShopMetadataWhere($data, $whereforShopMeta);
                     if ($updateResult) {
                         echo json_encode($updateResult);
                     }
                 }
                 break;
             case 'updateShopBanner':
                 $shop_id = $request->input('shop_id');
                 $whereforShop = ['rawQuery' => 'shop_id =? ', 'bindParams' => [$shop_id]];
                 $selectedColumns = array('shop_id', 'shop_banner', 'user_id');
                 $shopDetails = $ObjShop->getAllshopsWhere($whereforShop, $selectedColumns);
                 if (isset($_FILES["shop_banner"]["name"]) && !empty($_FILES["shop_banner"]["name"])) {
                     $bannerFilePath = uploadImageToStoragePath(Input::file('shop_banner'), 'shopbanner', 'shopbanner_' . $shopDetails[0]['user_id'] . '_' . time() . ".jpg");
                 } else {
                     $bannerFilePath = uploadImageToStoragePath($_SERVER['DOCUMENT_ROOT'] . "/assets/images/no-image.png", 'shopbanner', 'shopbanner_' . $shopDetails[0]['user_id'] . '_' . time() . ".jpg");
                 }
                 $shopdata = array('shop_banner' => $bannerFilePath);
                 $updateBanner = $ObjShop->updateShopWhere($shopdata, $whereforShop);
                 if ($updateBanner) {
                     deleteImageFromStoragePath($shopDetails[0]->shop_banner);
                     echo json_encode($updateBanner);
                 }
                 break;
             case 'updateShopLogo':
                 $shop_id = $request->input('shop_id');
                 $whereforShop = ['rawQuery' => 'shop_id =? ', 'bindParams' => [$shop_id]];
                 $selectedColumns = array('shop_id', 'shop_logo');
                 $shopDetails = $ObjShop->getAllshopsWhere($whereforShop, $selectedColumns);
                 if (isset($_FILES["shop_logo"]["name"]) && !empty($_FILES["shop_logo"]["name"])) {
                     $logoFilePath = uploadImageToStoragePath(Input::file('shop_logo'), 'shoplogo', 'shoplogo_' . $mainId . '_' . time() . ".jpg");
                 } else {
                     $logoFilePath = uploadImageToStoragePath($_SERVER['DOCUMENT_ROOT'] . "/assets/images/no-image.png", 'shoplogo', 'shoplogo_' . $mainId . '_' . time() . ".jpg");
                 }
                 $shopdata = array('shop_logo' => $logoFilePath);
                 $updatelogo = $ObjShop->updateShopWhere($shopdata, $whereforShop);
                 if ($updatelogo) {
                     deleteImageFromStoragePath($shopDetails[0]->shop_logo);
                     echo json_encode($updatelogo);
                 }
                 break;
             case 'updateShopStatus':
                 $shopMetaId = $request->input('shopMetaId');
                 $status = $request->input('value');
                 $supplierId = $request->input('supplierId');
                 $data = array('sm_status_set_by' => $supplierId, 'shop_metadata_status' => $status);
                 $whereforShopMeta = ['rawQuery' => 'shop_metadata_id =? ', 'bindParams' => [$shopMetaId]];
                 $updateResult = $objshopMetadataModal->updateShopMetadataWhere($data, $whereforShopMeta);
                 if ($updateResult) {
                     echo json_encode($updateResult);
                 }
                 break;
             case 'changeShopStatus':
                 $Shop_Id = $request->input('ShopId');
                 $Status = $request->input('status');
                 $data1['shop_status'] = $Status;
                 $where1 = ['rawQuery' => 'shop_id =? ', 'bindParams' => [$Shop_Id]];
                 $updateResult = $ObjShop->updateShopWhere($data1, $where1);
                 if ($updateResult) {
                     echo json_encode(['status' => 'success', 'msg' => 'Status has been changed.']);
                 } else {
                     echo json_encode(['status' => 'error', 'msg' => 'Something went wrong, please reload the page and try again.']);
                 }
                 break;
             case 'getState':
                 $countryId = $request->input('countryId');
                 $where = ['rawQuery' => 'is_visible =? and location_type =? and parent_id =?', 'bindParams' => [0, 1, $countryId]];
                 $allstates = $objLocationModel->getAllLocationsWhere($where);
                 echo json_encode($allstates);
                 break;
             case 'getCity':
                 $stateId = $request->input('stateId');
                 $where = ['rawQuery' => 'is_visible =? and location_type =? and parent_id =?', 'bindParams' => [0, 2, $stateId]];
                 $allcities = $objLocationModel->getAllLocationsWhere($where);
                 echo json_encode($allcities);
                 break;
         }
     }
 }
 public function editFlashsale(Request $request, $fid)
 {
     $objCategoryModel = ProductCategory::getInstance();
     $objCampaignModel = Campaigns::getInstance();
     $postData = $request->all();
     $supplierId = Session::get('fs_supplier')['id'];
     if ($request->isMethod('POST')) {
         $rules = array('campaign_name' => 'unique:campaigns,campaign_name,' . $fid . ',campaign_id', 'flashsale_image' => 'image');
         $validator = Validator::make($request->all(), $rules);
         if ($validator->fails()) {
             return Redirect::back()->withErrors($validator)->withInput();
         } else {
             if (Input::hasFile('flashsale_image')) {
                 $filePath = uploadImageToStoragePath(Input::file('flashsale_image'), 'flashsale', 'flashsale_' . $supplierId . '_' . time() . ".jpg");
                 $data['campaign_banner'] = $filePath;
             }
             $postData = $request->all();
             $data['campaign_name'] = $postData['campaign_name'];
             $data['for_shop_id'] = $postData['suppliershop'];
             $data['discount_type'] = $postData['discounttype'];
             if ($postData['discounttype'] == 1) {
                 $data['discount_value'] = $postData['flatdiscount'];
             } else {
                 $data['discount_value'] = $postData['percentagediscount'];
             }
             $validFrom = strtotime(str_replace("-", "", $postData['availablefromdate']));
             $validTo = strtotime(str_replace("-", "", $postData['availableuptodate']));
             $data['available_from'] = $validFrom;
             $data['available_upto'] = $validTo;
             $categ = $postData['productcategories'];
             $data['for_category_ids'] = implode(",", $categ);
             $where = ['rawQuery' => 'campaign_id = ?', 'bindParams' => [$fid]];
             $campaignUpdate = $objCampaignModel->updateFlashsaleStatus($data, $where);
             if ($campaignUpdate) {
                 if (isset($filePath)) {
                     deleteImageFromStoragePath($postData['oldImage']);
                 }
                 return Redirect::back()->with(['status' => 'success', 'msg' => 'FlashSale Added Successfully.']);
             } else {
                 return Redirect::back()->with(['status' => 'error', 'msg' => 'Some Error try again.']);
             }
         }
     }
     $where = ['rawQuery' => 'campaign_id = ?', 'bindParams' => [$fid]];
     $selectedColumn = ['campaigns.*', 'users.username'];
     $flashsaleInfo = $objCampaignModel->getAllFlashsaleDetails($where, $selectedColumn);
     if (isset($flashsaleInfo) && !empty($flashsaleInfo)) {
         foreach ($flashsaleInfo as $flashkey => $flashval) {
             $categoryIds = $flashval->for_category_ids;
             $where = ['rawQuery' => 'category_id IN(' . $categoryIds . ')'];
             $getcategory = $objCategoryModel->getCategoryNameById($where);
             foreach ($getcategory as $catkey => $catval) {
                 $flashsaleInfo[$flashkey]->category = $catval->category_name;
             }
         }
         //            echo'<pre>';print_r($flashsaleInfo);die("dxv");
         $where = ['rawQuery' => 'category_status = ? AND parent_category_id = ?', 'bindParams' => [1, 0]];
         $selectedColumn = ['category_id', 'category_name', 'category_status', 'for_shop_id'];
         $allactivecategories = $objCategoryModel->getAllMainCategories($where, $selectedColumn);
         return view('Supplier/Views/flashsale/editFlashsale', ['flashsaleDetails' => $flashsaleInfo[0], 'activeflashsale' => $allactivecategories]);
     } else {
         return view('Supplier/Views/flashsale/editFlashsale');
     }
 }
 /**
  *  This service is use to handle profile it has 4 methods changegeneralinfo, changeshippinginfo, changepassword and changeavtar
  * @param changegeneralinfo : method, user_id, firstname, lastname, contact_no, api_token, secondary_email
  * @return $updategeneralinfo
  * @param changeshippinginfo : method, user_id,  mytoken, city, state, zipcode, api_token, address_line_1, address_line_2
  * @return $updateshippinginfo
  * @param changepassword : method, user_id, oldPassword, newPassword, reNewPassword, api_token
  * @return $Updatepassword
  * @param changeavtar : method, user_id, api_token, input_file_preview
  * @return $url
  */
 public function profileAjaxHandler(Request $request)
 {
     $response = new stdClass();
     if ($request->isMethod("POST")) {
         $postData = $request->all();
         $API_TOKEN = env('API_TOKEN');
         $method = "";
         if (isset($postData['method'])) {
             $method = $postData['method'];
         }
         $objuser = new User();
         $objusermetamodel = new Usersmeta();
         switch ($method) {
             case "changegeneralinfo":
                 $userId = "";
                 if (isset($postData['user_id'])) {
                     $userId = $postData['user_id'];
                 }
                 $firstname = "";
                 if (isset($postData['firstname'])) {
                     $firstname = $postData['firstname'];
                 }
                 $lastname = "";
                 if (isset($postData['lastname'])) {
                     $lastname = $postData['lastname'];
                 }
                 $contact_no = "";
                 if (isset($postData['contact_no'])) {
                     $contact_no = $postData['contact_no'];
                 }
                 $email = "";
                 if (isset($postData['email'])) {
                     $email = $postData['email'];
                 }
                 $username = "";
                 if (isset($postData['username'])) {
                     $username = $postData['username'];
                 }
                 $authFlag = false;
                 if (isset($postData['api_token'])) {
                     $apitoken = $postData['api_token'];
                     if ($apitoken == $API_TOKEN) {
                         $authFlag = true;
                     } else {
                         if ($userId != '') {
                             $whereForUpdate = ['rawQuery' => 'id =?', 'bindParams' => [$userId]];
                             $Userscredentials = $objuser->getUsercredsWhere($whereForUpdate);
                             if ($apitoken == $Userscredentials->login_token) {
                                 $authFlag = true;
                             }
                         }
                     }
                 }
                 if ($authFlag) {
                     $rules = array('firstname' => 'required|regex:/^[A-Za-z\\s]+$/|max:255', 'lastname' => 'required|regex:/^[A-Za-z\\s]+$/|max:255', 'username' => 'required|regex:/^[A-Za-z0-9._\\s]+$/|max:255', 'email' => 'required|email|max:255', 'user_id' => 'required');
                     $messages = ['firstname.regex' => 'The :attribute cannot contain special characters.', 'lastname.regex' => 'The :attribute cannot contain special characters.', 'username.regex' => 'The :attribute cannot contain special characters.'];
                     $validator = Validator::make($request->all(), $rules, $messages);
                     if ($validator->fails()) {
                         $response->code = 100;
                         $response->message = $validator->messages();
                         $response->data = null;
                         echo json_encode($response, true);
                     } else {
                         $whereForUpdate = ['rawQuery' => 'id =?', 'bindParams' => [$userId]];
                         $currentUserDetails = $objuser->getUsercredsWhere($whereForUpdate);
                         $uniqueflag = false;
                         if ($currentUserDetails->username == $username && $currentUserDetails->username == $email) {
                             $uniqueflag = true;
                         } else {
                             if ($currentUserDetails->username != $username && $currentUserDetails->username == $email) {
                                 $uniqueflag = true;
                             } else {
                                 if ($currentUserDetails->username == $username && $currentUserDetails->username != $email) {
                                     $uniqueflag = true;
                                 } else {
                                     $rules = array('username' => 'unique:users', 'email' => 'unique:users');
                                     $validator = Validator::make($request->all(), $rules);
                                     if ($validator->fails()) {
                                         $response->code = 100;
                                         $response->message = $validator->messages();
                                         $response->data = null;
                                         echo json_encode($response, true);
                                     } else {
                                         $uniqueflag = true;
                                     }
                                 }
                             }
                         }
                         if ($uniqueflag) {
                             $whereForId = ['rawQuery' => 'id =?', 'bindParams' => [$userId]];
                             $data = array('name' => $firstname, 'last_name' => $lastname, 'username' => $username, 'email' => $email);
                             $updategeneralinfo = $objuser->UpdateUserDetailsbyId($whereForId, $data);
                             $whereForUserId = ['rawQuery' => 'user_id =?', 'bindParams' => [$userId]];
                             $Isuseravailable = $objusermetamodel->getUsermetaWhere($whereForUserId);
                             if ($Isuseravailable) {
                                 $dataupdate = array('phone' => "{$contact_no}");
                                 $UpdateUsermeta = $objusermetamodel->UpdateUsermetawhere($whereForUserId, $dataupdate);
                             } else {
                                 $dataadd = array('user_id' => $userId, 'phone' => $contact_no);
                                 $Addusermeta = $objusermetamodel->addUsermeta($dataadd);
                             }
                             if ($updategeneralinfo) {
                                 $response->code = 200;
                                 $response->message = "Update Successful";
                                 $response->data = $updategeneralinfo;
                                 echo json_encode($response, true);
                             } else {
                                 $response->code = 400;
                                 $response->message = "Something went wrong";
                                 $response->data = 1;
                                 echo json_encode($response, true);
                             }
                         }
                     }
                 } else {
                     $response->code = 401;
                     $response->message = "Access Denied";
                     $response->data = null;
                     echo json_encode($response, true);
                 }
                 break;
             case "changeshippinginfo":
                 $userId = "";
                 if (isset($postData['user_id'])) {
                     $userId = $postData['user_id'];
                 }
                 $City = "";
                 if (isset($postData['city'])) {
                     $City = $postData['city'];
                 }
                 $State = "";
                 if (isset($postData['state'])) {
                     $State = $postData['state'];
                 }
                 $Zip_code = "";
                 if (isset($postData['zipcode'])) {
                     $Zip_code = $postData['zipcode'];
                 }
                 //                    $country = "";
                 //                    if (isset($postData['country'])) {
                 //                        $country = $postData['country'];
                 //                    }
                 $Address1 = "";
                 if (isset($postData['address_line_1'])) {
                     $Address1 = $postData['address_line_1'];
                 }
                 $Address2 = "";
                 if (isset($postData['address_line_2'])) {
                     $Address2 = $postData['address_line_2'];
                 }
                 $authFlag = false;
                 if (isset($postData['api_token'])) {
                     $apitoken = $postData['api_token'];
                     if ($apitoken == $API_TOKEN) {
                         $authFlag = true;
                     } else {
                         if ($userId != '') {
                             $whereForUpdate = ['rawQuery' => 'id =?', 'bindParams' => [$userId]];
                             $Userscredentials = $objuser->getUsercredsWhere($whereForUpdate);
                             if ($apitoken == $Userscredentials->login_token) {
                                 $authFlag = true;
                             }
                         }
                     }
                 }
                 if ($authFlag) {
                     $rules = array('city' => 'required', 'state' => 'required', 'zipcode' => 'required', 'address_line_1' => 'required');
                     $validator = Validator::make($request->all(), $rules);
                     if ($validator->fails()) {
                         $response->code = 100;
                         $response->message = $validator->messages();
                         $response->data = null;
                         echo json_encode($response);
                     } else {
                         $whereForUserId = ['rawQuery' => 'user_id =?', 'bindParams' => [$userId]];
                         $Isuseravailable = $objusermetamodel->getUsermetaWhere($whereForUserId);
                         if ($Isuseravailable) {
                             $data = array('city' => $City, 'state' => $State, 'zipcode' => $Zip_code, 'addressline1' => $Address1, 'addressline2' => $Address2);
                             $updateshippinginfo = $objusermetamodel->UpdateUsermetawhere($whereForUserId, $data);
                         } else {
                             $dataadd = array('user_id' => $userId, 'city' => $City, 'state' => $State, 'zipcode' => $Zip_code, 'addressline1' => $Address1, 'addressline2' => $Address2);
                             $Addusermeta = $objusermetamodel->addUsermeta($dataadd);
                         }
                         if ($updateshippinginfo || $Addusermeta) {
                             $response->code = 200;
                             $response->message = "Update Successful";
                             $response->data = 1;
                             echo json_encode($response, true);
                         } else {
                             $response->code = 400;
                             $response->message = "Something went Wrong";
                             $response->data = null;
                             echo json_encode($response, true);
                         }
                     }
                 } else {
                     $response->code = 401;
                     $response->message = "Access Denied";
                     $response->data = null;
                     echo json_encode($response, true);
                 }
                 break;
             case "changepassword":
                 $userId = "";
                 if (isset($postData['user_id'])) {
                     $userId = $postData['user_id'];
                 }
                 $oldpassword = "";
                 if (isset($postData['oldPassword'])) {
                     $oldpassword = $postData['oldPassword'];
                 }
                 $newpassword = "";
                 if (isset($postData['newPassword'])) {
                     $newpassword = $postData['newPassword'];
                 }
                 $renewpassword = "";
                 if (isset($postData['reNewPassword'])) {
                     $renewpassword = $postData['reNewPassword'];
                 }
                 $authFlag = false;
                 if (isset($postData['api_token'])) {
                     $apitoken = $postData['api_token'];
                     if ($apitoken == $API_TOKEN) {
                         $authFlag = true;
                     } else {
                         if ($userId != '') {
                             $whereForUpdate = ['rawQuery' => 'id =?', 'bindParams' => [$userId]];
                             $Userscredentials = $objuser->getUsercredsWhere($whereForUpdate);
                             if ($apitoken == $Userscredentials->login_token) {
                                 $authFlag = true;
                             }
                         }
                     }
                 }
                 if ($authFlag) {
                     $rules = array('oldPassword' => 'required', 'newPassword' => 'required', 'reNewPassword' => 'required', 'user_id' => 'required');
                     $validator = Validator::make($request->all(), $rules);
                     if ($validator->fails()) {
                         $response->code = 100;
                         $response->message = $validator->messages();
                         $response->data = null;
                         echo json_encode($response);
                     } else {
                         if ($newpassword != $oldpassword) {
                             if ($newpassword == $renewpassword) {
                                 $where = ['rawQuery' => 'id =?', 'bindParams' => [$userId]];
                                 $currentUserDetails = $objuser->getUsercredsWhere($where);
                                 if (Hash::check($oldpassword, $currentUserDetails->password)) {
                                     $newpassword = Hash::make($newpassword);
                                     $data = array('password' => $newpassword);
                                     $Updatepassword = $objuser->UpdateUserDetailsbyId($where, $data);
                                     $response->code = 200;
                                     $response->message = "Password Changed Successfully";
                                     $response->data = 1;
                                     echo json_encode($response, true);
                                 } else {
                                     $response->code = 400;
                                     $response->message = "Invalid Password";
                                     $response->data = null;
                                     echo json_encode($response, true);
                                 }
                             } else {
                                 $response->code = 400;
                                 $response->message = "Both New password should be same";
                                 $response->data = null;
                                 echo json_encode($response, true);
                             }
                         } else {
                             $response->code = 400;
                             $response->message = "New and old password should not be same";
                             $response->data = null;
                             echo json_encode($response, true);
                         }
                     }
                 } else {
                     $response->code = 401;
                     $response->message = "Access Denied";
                     $response->data = null;
                     echo json_encode($response, true);
                 }
                 break;
             case "changeavtar":
                 //This method is directly called from Ajax call of profile-setting.blade.php page
                 $userId = "";
                 if (isset($postData['user_id'])) {
                     $userId = $postData['user_id'];
                 }
                 $authFlag = false;
                 if (isset($postData['api_token'])) {
                     $apitoken = $postData['api_token'];
                     if ($apitoken == $API_TOKEN) {
                         $authFlag = true;
                     } else {
                         if ($userId != '') {
                             $whereForUpdate = ['rawQuery' => 'id =?', 'bindParams' => [$userId]];
                             $Userscredentials = $objuser->getUsercredsWhere($whereForUpdate);
                             if ($apitoken == $Userscredentials->login_token) {
                                 $authFlag = true;
                             }
                         }
                     }
                 }
                 if ($authFlag) {
                     if ($userId != '') {
                         if (Input::hasFile('file')) {
                             $validator = Validator::make($request->all(), ['file' => 'image']);
                             if ($validator->fails()) {
                                 $response->code = 100;
                                 $response->message = $validator->messages();
                                 $response->data = null;
                                 echo json_encode($response);
                             } else {
                                 $filePath = uploadImageToStoragePath(Input::file('file'), 'profileavatar', 'profileavatar_' . $userId . '_' . time() . ".jpg");
                                 if ($filePath) {
                                     $updateData['profilepic'] = $filePath;
                                     $where = ['rawQuery' => 'id =?', 'bindParams' => [$userId]];
                                     $UserData = $objuser->getUsercredsWhere($where);
                                     $updatedResult = $objuser->UpdateUserDetailsbyId($where, $updateData);
                                     if ($updatedResult) {
                                         if ($UserData->profilepic != '') {
                                             if (!strpos($UserData->profilepic, 'placeholder')) {
                                                 deleteImageFromStoragePath($UserData->profilepic);
                                             }
                                         }
                                         //
                                         $response->code = 200;
                                         $response->message = "Successfully updated profile image.";
                                         $response->data = $filePath;
                                         echo json_encode($response);
                                     } else {
                                         $response->code = 400;
                                         $response->message = "Something went wrong, please try again.";
                                         $response->data = null;
                                         echo json_encode($response);
                                     }
                                 } else {
                                     $response->code = 400;
                                     $response->message = "Something went wrong, please reload the page and try again..";
                                     $response->data = null;
                                     echo json_encode($response);
                                 }
                             }
                         } else {
                             $response->code = 400;
                             $response->message = "Give correct input and Input Image files should be(jpg,gif,png,jpeg)only";
                             $response->data = null;
                             echo json_encode($response, true);
                         }
                     } else {
                         $response->code = 400;
                         $response->message = "You need to login to change Avtar.";
                         $response->data = null;
                         echo json_encode($response, true);
                     }
                 } else {
                     $response->code = 401;
                     $response->message = "Access Denied";
                     $response->data = null;
                     echo json_encode($response, true);
                 }
                 break;
             default:
                 break;
         }
     } else {
         $response->code = 401;
         $response->message = "Invalid request";
         $response->data = null;
         echo json_encode($response, true);
     }
 }