public function checkUserProfileViews($userDetails)
 {
     $instagramScrape = new API\InstagramAPI\Instagram_scrape();
     //        $objInstagramAPI = new API\InstagramAPI\Instagram();
     $instagramUserModel = new Instagram_User();
     $objUsermetaModel = new Usersmeta();
     $objOrderModel = new Order();
     $whereIn = implode(',', array_unique(array_map(function ($v) {
         return $v->ins_user_id;
     }, $userDetails)));
     $insUserStatus = $instagramUserModel->updateUserDetails(['rawQuery' => 'ins_user_id IN(' . $whereIn . ')'], ['cronjob_status' => 0]);
     //replace with 1
     if (!Session::has('FE_in_checkUserProfile')) {
         //FE=Fatal_Error
         $fataErrorData['whereIn'] = $whereIn;
         $fataErrorData['modalObject'] = $instagramUserModel;
         $fataErrorData['functionName'] = 'updateUserDetails';
         $fataErrorData['params'] = 'ins_user_id';
         Session::put('FE_in_checkUserProfile', $fataErrorData);
     }
     try {
         $id = 1;
         foreach ($userDetails as $user) {
             $username = $user->ins_username;
             print_r($id . ' . ');
             print_r($username);
             echo "<br>";
             ++$id;
             $username = $user->ins_username;
             $picsFetchCount = intval($user->pics_fetch_count);
             //            $picsDone = intval($user->pics_done);
             $picLimit = intval($user->pics_limit);
             $dailyPostLimit = intval($user->daily_post_limit);
             $dailyPostDone = intval($user->daily_post_done);
             $lastPostCreatedTime = intval($user->last_post_created_time);
             $firstPost_deliveryTime_day = intval($user->firstpost_delivery_daytime);
             $orderDelay = intval($user->order_delay_flag);
             $endDateTime = intval($user->end_date_time);
             $whereInsUser = ['rawQuery' => 'ins_user_id=?', 'bindParams' => [$user->ins_user_id]];
             // code for reset daily limit every 24 hr. If daily limit cross then stop  autolikes script for next 24 hrs.
             // Daily limit will be automatically reset every 24 hours from the time the user make the first post
             if (intval($user->ig_user_status) == 2 || intval($user->ig_user_status) == 3) {
                 if ($firstPost_deliveryTime_day != 0) {
                     if (time() - $firstPost_deliveryTime_day >= 86400) {
                         //24 hr = 86400 seconds
                         $updatedData23 = ['last_post_created_time' => time(), 'firstpost_delivery_daytime' => time(), 'daily_post_done' => 0, 'ig_user_status' => 2, 'cronjob_status' => 0, 'message' => 'The script is waiting for new post. Searching new post in every 5 minutes!'];
                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $updatedData23);
                     }
                 } else {
                     if (intval($user->ig_user_status) == 3) {
                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, ['cronjob_status' => 0]);
                     }
                 }
             }
             // This script will run when autolikes script was stopped due to in-sufficient balance,
             // This code will automatically reset autolikes running script when user add balance in account.
             if (intval($user->ig_user_status) == 3) {
                 if ($user->last_order_total_price != 0) {
                     $accountBalanceDetails = $objUsermetaModel->getUsermetaWhere(['rawQuery' => 'user_id=?', 'bindParams' => [$user->by_user_id]], ['account_bal']);
                     $accountBalance = $accountBalanceDetails->account_bal;
                     if ($accountBalance >= $user->last_order_total_price) {
                         $updatedData3 = ['ig_user_status' => 2, 'cronjob_status' => 0, 'message' => 'The script is waiting for new post. Searching new post in every 5 minutes!'];
                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $updatedData3);
                     }
                 } else {
                     $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, ['cronjob_status' => 0]);
                 }
             }
             $expiredFlag = false;
             if ($endDateTime != 0 && $endDateTime < time()) {
                 if ($user->ig_user_status != 4) {
                     $updatedData = ['ig_user_status' => 4, 'cronjob_status' => 0, 'message' => 'This profile #' . $username . ' has expired. If you wish to continue, increase the end date in edit option. '];
                     $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $updatedData);
                 } else {
                     $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, ['cronjob_status' => 0]);
                 }
                 $expiredFlag = true;
             } else {
                 if ($user->ig_user_status == 4) {
                     $updatedData = ['ig_user_status' => 2, 'cronjob_status' => 0, 'message' => 'The script is waiting for new post. Searching new post in every 5 minutes!'];
                     $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $updatedData);
                 }
             }
             if (!$expiredFlag) {
                 if (intval($user->ig_user_status) == 2) {
                     if ($lastPostCreatedTime == 0) {
                         $lastPostCreatedTime = time();
                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, ['last_post_created_time' => time()]);
                     }
                     if ($dailyPostLimit > 0) {
                         if ($picsFetchCount < $picLimit) {
                             if ($dailyPostDone < $dailyPostLimit) {
                                 //scrap all the latest post created after the last post created time
                                 $userDetails = [];
                                 //                                    if (intval($user->plan_type) == 0) {// for likes
                                 ////                                        print_r($username); echo"<br>";
                                 //                                        $username = strtolower($username);
                                 ////                                        $userDetails = $objInstagramAPI->UserDetailsByUsernameWithLastPostCreatedTime($username, $user->last_post_created_time);
                                 //                                        $userDetails = $instagramScrape->instagramScrape($username, $lastPostCreatedTime, 'image');
                                 //
                                 ////                                        $userProfileData = $instagramScrape->getInsUserLatestPostDetails($username, $lastPostCreatedTime, $dailyPostLimit, 'image');
                                 //                                    } else if (intval($user->plan_type) == 4) { // for video
                                 $username = strtolower($username);
                                 $userDetails = $instagramScrape->instagramScrape($username, $lastPostCreatedTime, 'video');
                                 //                                        $userProfileData = $instagramScrape->getInsUserLatestPostDetails($username, $lastPostCreatedTime, $dailyPostLimit, 'video');
                                 //                                    }
                                 //                                dd($userProfileData);
                                 if ($userDetails != null) {
                                     // && $userDetails != "Username does not exist" && $userDetails != "user is private"
                                     $latestPostCreatedTime = 0;
                                     $latestPostCreatedTimeFlag = false;
                                     $latestDeliveryLink = '';
                                     $startTime = time();
                                     $userDetails = array_reverse($userDetails, true);
                                     foreach ($userDetails as $key => $value) {
                                         $startTime = time();
                                         $startTime = $orderDelay == 1 ? $startTime + 600 : $startTime;
                                         //600= 10 minutes delay in next order
                                         // get the latest post link and place that link  for autolikes order
                                         if ($dailyPostDone < $dailyPostLimit && $picsFetchCount < $picLimit) {
                                             //add order in order table and then in order-process table
                                             // This code is for placing  autolikes order only (likes orders)
                                             // check if auto comment is set or not
                                             $autoCommentsPrice = 0;
                                             $autoCommentsData = array();
                                             if ($user->autoComments == "YES") {
                                                 $autoCommentsPrice = $user->price_for_autoComments / 1000 * $user->comments_amount;
                                                 $autoCommentsData['plan_id'] = $user->plan_id_for_autoComments;
                                                 $autoCommentsData['by_user_id'] = $user->by_user_id;
                                                 $autoCommentsData['for_user_id'] = $user->ins_user_id;
                                                 $autoCommentsData['ins_url'] = "https://www.instagram.com/p/" . $value['link'] . "/";
                                                 $autoCommentsData['quantity_total'] = $user->comments_amount;
                                                 $autoCommentsData['comment_id'] = $user->custom_comment_id;
                                                 $autoCommentsData['start_time'] = $startTime;
                                                 $autoCommentsData['added_time'] = time();
                                                 $autoCommentsData['updated_time'] = time();
                                                 $autoCommentsData['auto_order_status'] = 1;
                                                 // 1=autolikes order
                                                 $autoCommentsData['status'] = 0;
                                                 // order is in pending state
                                                 $autoCommentsData['price'] = $autoCommentsPrice;
                                                 $autoCommentsData['orders_per_run'] = 0;
                                                 $autoCommentsData['time_interval'] = 0;
                                                 $autoCommentsData['url_type'] = 0;
                                                 // 0=postLink
                                                 $autoCommentsData['order_message'] = 'Order has inserted! This order has a schedule time and it will start after (' . $this->getDateDifference($startTime) . ').Please wait to get it started!';
                                                 // 0=postLink
                                             }
                                             $autoLikesPrice = $user->charge_per_unit / 1000 * $user->likes_per_pic;
                                             $accountBalanceDetails = $objUsermetaModel->getUsermetaWhere(['rawQuery' => 'user_id=?', 'bindParams' => [$user->by_user_id]], ['account_bal']);
                                             $accountBalance = $accountBalanceDetails->account_bal;
                                             $totalPrice = $autoLikesPrice + $autoCommentsPrice;
                                             if ($accountBalance >= $totalPrice) {
                                                 $autoLikesData['plan_id'] = $user->plan_id;
                                                 $autoLikesData['by_user_id'] = $user->by_user_id;
                                                 $autoLikesData['for_user_id'] = $user->ins_user_id;
                                                 //code added and modified by Saurabh
                                                 $autoLikesData['ins_url'] = "https://www.instagram.com/p/" . $value['link'] . "/";
                                                 $autoLikesData['initial_likes_count'] = $value['likes_count'];
                                                 $autoLikesData['initial_followers_count'] = $value['followers_count'];
                                                 $autoLikesData['initial_comments_count'] = $value['comments_count'];
                                                 $autoLikesData['initial_views_count'] = $value['views_count'];
                                                 $autoLikesData['quantity_total'] = $user->likes_per_pic;
                                                 $autoLikesData['start_time'] = $startTime;
                                                 $autoLikesData['added_time'] = time();
                                                 $autoLikesData['updated_time'] = time();
                                                 $autoLikesData['auto_order_status'] = 1;
                                                 // 1=autolikes order
                                                 $autoLikesData['status'] = 0;
                                                 // order is in pending state
                                                 $autoLikesData['price'] = $autoLikesPrice;
                                                 $autoLikesData['orders_per_run'] = 0;
                                                 $autoLikesData['time_interval'] = 0;
                                                 $autoLikesData['url_type'] = 0;
                                                 // 0=postLink
                                                 $autoLikesData['order_message'] = 'Order has inserted! This order has a schedule time and it will start after (' . $this->getDateDifference($startTime) . ').Please wait to get it started!';
                                                 // 0=postLink
                                                 $rollback = false;
                                                 DB::beginTransaction();
                                                 DB::table('usersmeta')->where('user_id', '=', $user->by_user_id)->lockForUpdate()->get();
                                                 $autoLikesOrderInsertedStatus = $objOrderModel->insertOrder($autoLikesData);
                                                 $autoCommentsOrderInsertedStatus = 1;
                                                 if ($user->autoComments == "YES") {
                                                     $autoCommentsOrderInsertedStatus = $objOrderModel->insertOrder($autoCommentsData);
                                                 }
                                                 if ($autoLikesOrderInsertedStatus && $autoCommentsOrderInsertedStatus) {
                                                     $current_bal['account_bal'] = $accountBalance - $totalPrice;
                                                     $orderUpdateBalanceStatus = $objUsermetaModel->updateUsermetaWhere(['rawQuery' => 'user_id=?', 'bindParams' => [$user->by_user_id]], $current_bal);
                                                     if ($orderUpdateBalanceStatus) {
                                                         DB::commit();
                                                     } else {
                                                         $rollback = true;
                                                         DB::rollBack();
                                                     }
                                                 } else {
                                                     $rollback = true;
                                                     DB::rollBack();
                                                 }
                                                 if (!$rollback) {
                                                     //this code runs only when user make the first post (first order is placed).
                                                     if ($firstPost_deliveryTime_day == 0) {
                                                         $data4['firstpost_delivery_daytime'] = time();
                                                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $data4);
                                                     }
                                                     ++$picsFetchCount;
                                                     ++$dailyPostDone;
                                                     $latestPostCreatedTime = $value['created_time'];
                                                     $latestDeliveryLink = "https://www.instagram.com/p/" . $value['link'] . "/";
                                                     $latestPostCreatedTimeFlag = true;
                                                     //modified by saurabh
                                                     $startTime = $orderDelay == 1 ? $startTime + 600 : $startTime;
                                                     // for adding 10 MORE minutes delay in next order // if flag is not set than order will place at instant
                                                     //                                                $startTime += 600;//600= 10 minutes delay in next order placing
                                                 }
                                             } else {
                                                 $data5 = ['cronjob_status' => 0, 'ig_user_status' => 3, 'last_order_total_price' => $totalPrice, 'message' => 'Autolikes script has been stopped for # ' . $user->ins_username . ' due to insufficient balance.'];
                                                 $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $data5);
                                                 break;
                                             }
                                         }
                                     }
                                     //End of inner foreach loop
                                     // Update details in instagram_users table
                                     if ($latestPostCreatedTimeFlag) {
                                         $data6['pics_fetch_count'] = $picsFetchCount;
                                         $data6['daily_post_done'] = $dailyPostDone;
                                         $data6['last_post_created_time'] = $latestPostCreatedTime;
                                         $data6['last_delivery_link'] = $latestDeliveryLink;
                                         //                                            print_r($data6);
                                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $data6);
                                     }
                                 }
                             }
                         }
                     } else {
                         if ($dailyPostLimit == 0) {
                             if ($picsFetchCount < $picLimit) {
                                 //scrap all the latest post created after the first post created time
                                 $userDetails = [];
                                 //                                if ($user->plan_type == 0) {// for likes
                                 ////                                    $objInstagramAPI = new API\InstagramAPI\Instagram();
                                 ////                                    print_r($username); echo "<br>";
                                 //                                    $username = strtolower($username);
                                 ////                                    $userDetails = $objInstagramAPI->UserDetailsByUsernameWithLastPostCreatedTime($username, $user->last_post_created_time);
                                 //                                    $userDetails = $instagramScrape->instagramScrape($username, $lastPostCreatedTime, "image");
                                 ////                                    dd($userDetails);
                                 ////                                    $userProfileData = (isset($userDetails['instagramUsersData'])) ? $userDetails['instagramUsersData'] : '';
                                 //
                                 //
                                 ////                                    $userDetails = $instagramScrape->getInsUserLatestPostDetails($username, $lastPostCreatedTime, 0, 'image');
                                 ////                                    dd($userDetails['instagramUsersData']);
                                 //                                } else if ($user->plan_type == 4) { // for video
                                 $username = strtolower($username);
                                 $userDetails = $instagramScrape->instagramScrape($username, $lastPostCreatedTime, "video");
                                 //                                    $userDetails = $instagramScrape->getInsUserLatestPostDetails($username, $lastPostCreatedTime, 0, 'video');
                                 //                                }
                                 if ($userDetails != null) {
                                     // && $userDetails != "Username does not exist" && $userDetails != "user is private"
                                     $latestPostCreatedTime = 0;
                                     $latestDeliveryLink = '';
                                     $latestPostCreatedTimeFlag = false;
                                     $startTime = time();
                                     $userDetails = array_reverse($userDetails, true);
                                     foreach ($userDetails as $key => $value) {
                                         $startTime = time();
                                         $startTime = $orderDelay == 1 ? $startTime + 600 : $startTime;
                                         //600= 10 minutes delay in next order
                                         // get the latest post link and place that link  for autolikes order
                                         if ($picsFetchCount < $picLimit) {
                                             //add order in order table and then in order-process table
                                             // This code is for placing  autolikes order only (likes orders)
                                             $autoCommentsPrice = 0;
                                             $autoCommentsData = array();
                                             if ($user->autoComments == "YES") {
                                                 $autoCommentsPrice = $user->price_for_autoComments / 1000 * $user->comments_amount;
                                                 $autoCommentsData['plan_id'] = $user->plan_id_for_autoComments;
                                                 $autoCommentsData['by_user_id'] = $user->by_user_id;
                                                 $autoCommentsData['for_user_id'] = $user->ins_user_id;
                                                 $autoCommentsData['ins_url'] = "https://www.instagram.com/p/" . $value['link'] . "/";
                                                 $autoCommentsData['quantity_total'] = $user->comments_amount;
                                                 $autoCommentsData['comment_id'] = $user->custom_comment_id;
                                                 $autoCommentsData['start_time'] = $startTime;
                                                 $autoCommentsData['added_time'] = time();
                                                 $autoCommentsData['updated_time'] = time();
                                                 $autoCommentsData['auto_order_status'] = 1;
                                                 // 1=autolikes order
                                                 $autoCommentsData['status'] = 0;
                                                 // order is in pending state
                                                 $autoCommentsData['price'] = $autoCommentsPrice;
                                                 $autoCommentsData['orders_per_run'] = 0;
                                                 $autoCommentsData['time_interval'] = 0;
                                                 $autoCommentsData['url_type'] = 0;
                                                 // 0=postLink
                                                 $autoCommentsData['order_message'] = 'Order has inserted! This order has a schedule time and it will start after (' . $this->getDateDifference($startTime) . ').Please wait to get it started!';
                                                 // 0=postLink
                                             }
                                             $autoLikesOrViewsPrice = $user->charge_per_unit / 1000 * $user->likes_per_pic;
                                             //likes_per_pic is same as views per pic
                                             $accountBalanceDetails = $objUsermetaModel->getUsermetaWhere(['rawQuery' => 'user_id=?', 'bindParams' => [$user->by_user_id]], ['account_bal']);
                                             $accountBalance = $accountBalanceDetails->account_bal;
                                             $totalPrice = $autoLikesOrViewsPrice + $autoCommentsPrice;
                                             if ($accountBalance >= $totalPrice) {
                                                 $autoLikesOrViewsData['plan_id'] = $user->plan_id;
                                                 $autoLikesOrViewsData['by_user_id'] = $user->by_user_id;
                                                 $autoLikesOrViewsData['for_user_id'] = $user->ins_user_id;
                                                 $autoLikesOrViewsData['ins_url'] = "https://www.instagram.com/p/" . $value['link'] . "/";
                                                 $autoLikesOrViewsData['initial_likes_count'] = $value['likes_count'];
                                                 $autoLikesOrViewsData['initial_followers_count'] = $value['followers_count'];
                                                 $autoLikesOrViewsData['initial_comments_count'] = $value['comments_count'];
                                                 $autoLikesOrViewsData['initial_views_count'] = $value['views_count'];
                                                 $autoLikesOrViewsData['quantity_total'] = $user->likes_per_pic;
                                                 //likes_per_pic is same as views per pic
                                                 $autoLikesOrViewsData['start_time'] = $startTime;
                                                 $autoLikesOrViewsData['added_time'] = time();
                                                 $autoLikesOrViewsData['updated_time'] = time();
                                                 $autoLikesOrViewsData['auto_order_status'] = 1;
                                                 // 1=autolikes order
                                                 $autoLikesOrViewsData['status'] = 0;
                                                 // order is in pending state
                                                 $autoLikesOrViewsData['price'] = $autoLikesOrViewsPrice;
                                                 $autoLikesOrViewsData['orders_per_run'] = 0;
                                                 $autoLikesOrViewsData['time_interval'] = 0;
                                                 $autoLikesOrViewsData['url_type'] = 0;
                                                 // 0=postLink
                                                 $autoLikesOrViewsData['order_message'] = 'Order has inserted! This order has a schedule time and it will start after (' . $this->getDateDifference($startTime) . ').Please wait to get it started!';
                                                 $rollback = false;
                                                 DB::beginTransaction();
                                                 DB::table('usersmeta')->where('user_id', '=', $user->by_user_id)->lockForUpdate()->get();
                                                 $orderInsertedStatus = $objOrderModel->insertOrder($autoLikesOrViewsData);
                                                 $commentsOrderInsertedStatus = 1;
                                                 if ($user->autoComments == "YES") {
                                                     $commentsOrderInsertedStatus = $objOrderModel->insertOrder($autoCommentsData);
                                                 }
                                                 if ($orderInsertedStatus && $commentsOrderInsertedStatus) {
                                                     $current_bal['account_bal'] = $accountBalance - $totalPrice;
                                                     $orderUpdateBalanceStatus = $objUsermetaModel->updateUsermetaWhere(['rawQuery' => 'user_id=?', 'bindParams' => [$user->by_user_id]], $current_bal);
                                                     if ($orderUpdateBalanceStatus) {
                                                         DB::commit();
                                                     } else {
                                                         $rollback = true;
                                                         DB::rollBack();
                                                     }
                                                 } else {
                                                     $rollback = true;
                                                     DB::rollBack();
                                                 }
                                                 if (!$rollback) {
                                                     //                                            // Update details in instagram_users table
                                                     //                                            $whereInsUser = ['rawQuery' => 'ins_user_id=?', 'bindParams' => [$user->ins_user_id]];
                                                     //                                            $updateInsUserData = [
                                                     //                                                'pics_fetch_count' => ++$picsFetchCount,
                                                     //                                                'daily_post_done' => ++$dailyPostDone,
                                                     //                                                'cronjob_status' => 0,
                                                     //                                                'last_check' => time(),
                                                     ////                                            'last_delivery' => time(),
                                                     ////                                            'last_delivery_link' => $value['link'],
                                                     //                                                'last_post_created_time' => $value['created_time']
                                                     //                                            ];
                                                     //                                            $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $updateInsUserData);
                                                     //this code is run only when user make the first post (first order is placed).
                                                     if ($firstPost_deliveryTime_day == 0) {
                                                         $data4['firstpost_delivery_daytime'] = time();
                                                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $data4);
                                                     }
                                                     ++$picsFetchCount;
                                                     ++$dailyPostDone;
                                                     $latestPostCreatedTime = $value['created_time'];
                                                     $latestDeliveryLink = "https://www.instagram.com/p/" . $value['link'] . "/";
                                                     $latestPostCreatedTimeFlag = true;
                                                     //modified by saurabh
                                                     // for adding 10 MORE minutes delay in next order, if flag is not set than order will place at instant
                                                     $startTime = $orderDelay == 1 ? $startTime + 600 : $startTime;
                                                     //$startTime += 600;//600= 10 minutes delay in next order placing
                                                 }
                                             } else {
                                                 // insert your custom message here in instagram_users table
                                                 $updateInsUserMessageData = ['cronjob_status' => 0, 'ig_user_status' => 3, 'last_order_total_price' => $totalPrice, 'message' => 'Autolikes script has been stopped for # ' . $user->ins_username . ' due to insufficient balance.'];
                                                 $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $updateInsUserMessageData);
                                                 break;
                                             }
                                         }
                                     }
                                     //End of inner foreach loop
                                     // Update details in instagram_users table
                                     if ($latestPostCreatedTimeFlag) {
                                         $data6['pics_fetch_count'] = $picsFetchCount;
                                         $data6['daily_post_done'] = $dailyPostDone;
                                         $data6['last_post_created_time'] = $latestPostCreatedTime;
                                         $data6['last_delivery_link'] = $latestDeliveryLink;
                                         //                                        print_r($data6);echo "<br>";
                                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $data6);
                                     }
                                 }
                             }
                         }
                     }
                     $updateInsUserData = ['cronjob_status' => 0, 'last_check' => time()];
                     $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $updateInsUserData);
                 }
             }
         }
         //End of Outer foreach loop
     } catch (\Exception $e) {
         echo $e->getMessage();
         $insUserStatus = $instagramUserModel->updateUserDetails(['rawQuery' => 'ins_user_id IN(' . $whereIn . ')'], ['cronjob_status' => 0]);
     }
 }