public function checkout(Request $request)
 {
     $response = new stdClass();
     if ($request->isMethod('post')) {
         $postData = $request->all();
         $userId = $postData['id'];
         $token = $postData['token'];
         $amount = $postData['money'];
         $name = $postData['name'];
         $addrLine1 = $postData['addrLine1'];
         $city = $postData['city'];
         $state = $postData['state'];
         $country = $postData['country'];
         $email = $postData['email'];
         $zipCode = $postData['zipCode'];
         $phoneNumber = $postData['phoneNumber'];
         $authFlag = false;
         if (isset($postData['api_token'])) {
             $apiToken = $postData['api_token'];
             if ($apiToken == $this->API_TOKEN) {
                 $authFlag = true;
             } else {
                 $authFlag = false;
             }
         }
         if ($authFlag) {
             $rules = array('money' => 'required|regex:/^[0-9]+([.][0-9]{0,2}+)?$/', 'name' => 'required', 'addrLine1' => 'required', 'city' => 'required', 'state' => 'required', 'zipCode' => 'required', 'country' => 'required', 'email' => 'required', 'phoneNumber' => 'required');
             $message = array('money.required' => 'Please Enter Amount that you want to add to your wallet', 'money.regex' => 'Please Enter a valid Amount i.e. number or decimal value ', 'name.required' => 'please enter your name', 'addrLine1.required' => 'please enter address', 'city.required' => 'please enter city', 'state.required' => 'please enter state', 'zipCode.required' => 'please provide zip code', 'country.required' => 'please specify country name', 'email.required' => 'please enter your email', 'phoneNumber.required' => 'please enter your phone number');
             $validator = Validator::make($request->all(), $rules, $message);
             if (!$validator->fails()) {
                 \Twocheckout::privateKey('1768AF13-92B6-4B9D-8493-66E884E98FEF');
                 \Twocheckout::sellerId('901311477');
                 \Twocheckout::sandbox(true);
                 #Uncomment to use Sandbox
                 \Twocheckout::verifySSL(false);
                 try {
                     $charge = \Twocheckout_Charge::auth(array("merchantOrderId" => "123", "token" => $token, "currency" => 'USD', "total" => $amount, "billingAddr" => array("name" => $name, "addrLine1" => $addrLine1, "city" => $city, "state" => $state, "zipCode" => $zipCode, "country" => $country, "email" => $email, "phoneNumber" => $phoneNumber)));
                     //                        echo json_encode($charge,true);die;
                     //                        echo '<pre>';
                     //            print_r($charge);die;
                     if ($charge['response']['responseCode'] == 'APPROVED') {
                         //                            echo "Thanks for your Order!";
                         //                            echo "<h3>Return Parameters:</h3>";
                         //                            echo "<pre>";
                         //                            print_r($charge);
                         //                            echo "</pre>";
                         //                            echo die;
                         $transactionId = $charge['response']['transactionId'];
                         $objModelTransaction = new Transaction();
                         $input = array('tx_id' => '', 'tx_type' => '1', 'tx_mode' => '1', 'tx_code' => ' ', 'transaction_id' => $transactionId, 'user_id' => $userId, 'amount' => $amount, 'payment_time' => time() + 19800);
                         $result = $objModelTransaction->addNewTransaction($input);
                         //code for increasing the amount (updating the account bal)
                         // first checking that user has details in usersmeta table or not, if not then acc_bal will be 0 & add users with amount
                         // or if yes then update accountbalance
                         $objModelUsermeta = new Usersmeta();
                         $whereForUpdateUser = array('rawQuery' => 'user_id = ?', 'bindParams' => [$userId]);
                         $isUserAvailable = $objModelUsermeta->getUsermetaWhere($whereForUpdateUser);
                         if ($isUserAvailable) {
                             $accountBal = $isUserAvailable->account_bal;
                             $totalBalance = $accountBal + $amount;
                             $dataForUpdateUser = array('account_bal' => $totalBalance);
                             //                        return $dataForUpdateUser;
                             $updated = $objModelUsermeta->updateUsermetaWhere($dataForUpdateUser, $whereForUpdateUser);
                         } else {
                             $accountBal = 0;
                             $totalBalance = $accountBal + $amount;
                             $addData = array('user_id' => $userId, 'account_bal' => $totalBalance);
                             $addUsermeta = $objModelUsermeta->addUsermeta($addData);
                         }
                         // code for generating NOTIFICATION
                         $objModelNotification = Notification::getInstance();
                         $input = array('notification_id' => '', 'user_id' => $userId, 'notifications_txt' => '$ ' . $amount . ' is successfully credited to your account through 2CO credit card payment');
                         $addNotification = $objModelNotification->addNewNotification($input);
                         $response->code = 200;
                         $response->message = "Payment Approved";
                         $response->data = $totalBalance;
                         echo json_encode($response, true);
                     }
                 } catch (\Twocheckout_Error $e) {
                     echo json_encode($e->getMessage(), true);
                     //                        print_r($e->getMessage());
                 }
             }
         }
     }
 }
 public function updateProfileInfo(Request $request)
 {
     $response = new stdClass();
     if ($request->isMethod('post')) {
         $postData = $request->all();
         $objUserModel = new User();
         $objUsermetaModel = new Usersmeta();
         $userId = isset($postData['user_id']) ? $postData['user_id'] : '';
         $firstname = isset($postData['firstname']) ? $postData['firstname'] : '';
         $lastname = isset($postData['lastname']) ? $postData['lastname'] : '';
         $email = isset($postData['email']) ? $postData['email'] : '';
         $username = isset($postData['username']) ? $postData['username'] : '';
         $skypeUsername = isset($postData['skypeUsername']) ? $postData['skypeUsername'] : '';
         $addressline1 = "";
         if (isset($postData['addressline1'])) {
             $addressline1 = $postData['addressline1'];
         }
         $addressline2 = "";
         if (isset($postData['addressline2'])) {
             $addressline2 = $postData['addressline2'];
         }
         $city = "";
         if (isset($postData['city'])) {
             $city = $postData['city'];
         }
         $state = "";
         if (isset($postData['state'])) {
             $state = $postData['state'];
         }
         $country_id = "";
         if (isset($postData['country_id'])) {
             $country_id = $postData['country_id'];
         }
         $contact_no = "";
         if (isset($postData['contact_no'])) {
             $contact_no = $postData['contact_no'];
         }
         $authFlag = false;
         if (isset($postData['api_token'])) {
             if ($userId != '') {
                 $where = ['rawQuery' => 'id=?', 'bindParams' => [$userId]];
                 $selectColumn = array('login_token');
                 $userCredentials = $objUserModel->getUsercredsWhere($where, $selectColumn);
                 if ($userCredentials) {
                     $apiToken = $postData['api_token'];
                     if ($apiToken == $this->API_TOKEN) {
                         $authFlag = true;
                     } else {
                         if ($apiToken == $userCredentials->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()) {
                 $where = ['rawQuery' => 'id =?', 'bindParams' => [$userId]];
                 $currentUserDetails = $objUserModel->getUsercredsWhere($where);
                 $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();
                             $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) {
                     $updateUserWhereId = ['rawQuery' => 'id =?', 'bindParams' => [$userId]];
                     $data = array('name' => $firstname, 'lastname' => $lastname, 'username' => $username, 'skype_username' => $skypeUsername, 'email' => $email);
                     $updategeneralinfo = $objUserModel->UpdateUserDetailsbyId($updateUserWhereId, $data);
                     $updateUsermetaWhereUserId = ['rawQuery' => 'user_id =?', 'bindParams' => [$userId]];
                     $updateUsermeta = "";
                     $addUsermeta = "";
                     $isUserAvailable = $objUsermetaModel->getUsermetaWhere($updateUsermetaWhereUserId);
                     if ($isUserAvailable) {
                         $dataUpdate = array('addressline1' => $addressline1, 'addressline2' => $addressline2, 'city' => $city, 'state' => $state, 'country_id' => $country_id, 'contact_no' => $contact_no);
                         $updateUsermeta = $objUsermetaModel->updateUsermetaWhere($updateUsermetaWhereUserId, $dataUpdate);
                     } else {
                         $addData = array('user_id' => $userId, 'addressline1' => $addressline1, 'addressline2' => $addressline2, 'city' => $city, 'state' => $state, 'country_id' => $country_id, 'contact_no' => $contact_no, 'account_bal' => 0.0);
                         $addUsermeta = $objUsermetaModel->addUsermeta($addData);
                     }
                     if ($updategeneralinfo || $updateUsermeta || $addUsermeta) {
                         $response->code = 200;
                         $response->message = "Update Successful";
                         $response->data = $updategeneralinfo;
                         echo json_encode($response, true);
                     } else {
                         $response->code = 400;
                         $response->message = "Information Already updated";
                         $response->data = 1;
                         echo json_encode($response, true);
                     }
                 }
             } else {
                 $response->code = 400;
                 $response->message = $validator->messages();
                 $response->data = null;
                 echo json_encode($response, true);
             }
         } else {
             $response->code = 401;
             $response->message = "Access Denied";
             $response->data = null;
             echo json_encode($response, true);
         }
     } else {
         $response->code = 400;
         $response->message = "Request not allowed";
         $response->data = null;
         echo json_encode($response, true);
     }
 }
 public function testCronFunction()
 {
     $objInstagramScrape = new API\InstagramAPI\Instagram_scrape();
     $instagramUsername = "******";
     $startIndex = 1;
     $endIndex = 2;
     $res = $objInstagramScrape->getDetailsByStartAndLastSpreadIndex($instagramUsername, $startIndex, $endIndex);
     dd($res);
     $objInstagramUserModel = new Instagram_User();
     $insUsersId = [161, 40];
     $messages = array();
     foreach ($insUsersId as $key => $insUserId) {
         $queryResult = $objInstagramUserModel->updateUserDetails(['rawQuery' => 'ins_user_id=?', 'bindParams' => [$insUserId]], ['pics_fetch_count' => 0, 'pics_done' => 0, 'daily_post_done' => 0, 'reset_counter_time' => time()]);
         $instagramUserDetails = $objInstagramUserModel->getUserDetails(['rawQuery' => 'ins_user_id=?', 'bindParams' => [$insUserId]], ['ins_username', 'pics_limit']);
         if ($queryResult) {
             $messages[$key] = 'Done! We have reset the post done count for # ' . $instagramUserDetails[0]->ins_username . ' .Autolikes script can process ' . $instagramUserDetails[0]->pics_limit . ' more new posts.';
         } else {
             $messages[$key] = 'Sorry! Some Problem Occurred. Please reload the page and try again.';
         }
         //                                    $response->code = 200;
         //                                    $response->message = "Success";
         //                                    $response->data = $instagramUserDetails[0]->ins_username;
         //                                    echo json_encode($response, true);die;
     }
     $records["customActionStatus"] = "OK";
     // pass custom message(useful for getting status of group actions)
     $records["customActionMessage"] = $messages;
     dd($records["customActionMessage"]);
     foreach ($insUsersId as $key => $insUserId) {
         //code modified by saurabh //just use the autolikesscript() function here.
         $instagramUserDetails = $objInstagramUserModel->getUserDetails(['rawQuery' => 'ins_user_id=?', 'bindParams' => [$insUserId]]);
         //                                    dd($instagramUserDetails[0]->pics_fetch_count);
         $userExists = $objInstagramScrape->isUsernameExists($instagramUserDetails[0]->ins_username);
         if (is_numeric($userExists)) {
             $oldPicsFetchCount = $instagramUserDetails[0]->pics_fetch_count;
             //            dd($oldPicsFetchCount);
             if (($instagramUserDetails[0]->ig_user_status == 2 || $instagramUserDetails[0]->ig_user_status == 3) && $instagramUserDetails[0]->cronjob_status == 0) {
                 //                                        if (!empty($instagramUserDetails[0]) || $instagramUserDetails[0] != 0) {
                 //                                            $this->checkUserProfile($instagramUserDetails[0]);
                 //                                            $messages[$key] = 'hahahsfashash';
                 //                                        }
                 $this->checkUserProfile($instagramUserDetails);
                 //                dd($user);
                 $instagramUserDetails = $objInstagramUserModel->getUserDetails(['rawQuery' => 'ins_user_id=?', 'bindParams' => [$insUserId]], ['pics_fetch_count', 'ins_username']);
                 //                dd($instagramUserDetails[0]->pics_fetch_count);
                 $picsFetchCount = $instagramUserDetails[0]->pics_fetch_count - $oldPicsFetchCount;
                 //                dd($picsFetchCount);
                 if ($picsFetchCount != 0) {
                     $messages[$key] = 'Done! We got ' . $picsFetchCount . ' new posts and added for processing. Please check your order history.';
                 } else {
                     $messages[$key] = 'There is no any new post for this profile ' . $instagramUserDetails[0]->ins_username . ' .';
                 }
             } else {
                 $messages[$key] = '#' . $instagramUserDetails[0]->ins_username . ' has been finished or failed';
             }
         } else {
             $messages[$key] = $instagramUserDetails[0]->ins_username . ' does not exists OR may be private';
         }
     }
     dd($messages);
     $endIndex = 11;
     $link = "https://www.instagram.com/p/BE8Z1Iwq1Ss/?taken-by=saurabh_bond";
     //        $res = $objScrapeWebsta->instagram_scrape($username, $lastPostCreatedTime = 123);
     //        $res = $objScrapeWebsta->instagramScrape($username, $lastPostCreatedTime = 123, 'image');
     //        $res = $objScrapeWebsta->instagramScrapeOfDirectLink($username, $lastPostCreatedTime = 123);
     //        $res = $objScrapeWebsta->isUsernameExists($username);
     //        $res = $objScrapeWebsta->isVideoPost($username);
     //        $res = $objScrapeWebsta->instagramScrapeOfDirectLink($link);
     $res = $objScrapeWebsta->getProfilePicUrl($username);
     //        $res = $objScrapeWebsta->instagramScrapeByEndIndex($username, $endIndex);
     //       dd(intval(str_replace(",", "",$res)));
     dd($res);
     $res = "{\"code\":200,\"Message\":\"Your requested information has been processed.\"}";
     $res = json_decode($res, true);
     dd($res['code']);
     //        $objModelSocialNator=new API\SocialNator();
     //        $order_details = [];
     //        $order_details['instagramprofileurl'] = 'https://www.instagram.com/p/BE8Z1IwqSs/';
     //        $order_details['amount'] = 1;
     //        $order_details['method'] = "add_likes";
     //
     ////$response = $api->add_order($order_details['instagramprofileurl'], $order_details['amount'], $order_details['method']);
     //        $result=$objModelSocialNator->add_order($order_details['instagramprofileurl'], $order_details['amount'], $order_details['method']);
     //        $result=json_encode($result,true);
     $objUsersmeta = new Usersmeta();
     $objUsersmeta->updateUsermetaWhere(['rawQuery' => 'id=?', 'bindParams' => [7]], ['invite_id' => time() - 1459233158]);
 }
 public function expressCallback(Request $request)
 {
     //        return 23;
     $response = new stdClass();
     $postData = $request->all();
     $userId = $postData['id'];
     $amount = $postData['amount'];
     $payerid = $postData['PayerID'];
     $token = $postData['token'];
     //        print_r($token);print_r($payerid);die;
     $authFlag = false;
     if (isset($postData['api_token'])) {
         $apiToken = $postData['api_token'];
         if ($apiToken == $this->API_TOKEN) {
             $authFlag = true;
         }
     }
     if ($authFlag) {
         $objpaypal = Paypal::getInstance();
         $result = $objpaypal->ConfirmPayment($amount, $token, $payerid);
         //                echo"<pre>";print_r($result);die;
         //            echo json_encode($result, true);
         if ($result) {
             //                $function_result=$this->myCurlFunction();
             //                return $function_result;
             if ($result['ACK'] == "Success") {
                 //                    $response->code = 200;
                 //                    $response->message = "Amount added to your Wallet Successfully.";
                 $data['transactionId'] = $result['PAYMENTINFO_0_TRANSACTIONID'];
                 $data['acknowledgement'] = $result['ACK'];
                 $data['amount'] = $amount;
                 $data['paymentTime'] = date('Y-m-d H:i:s');
                 $transactionId = $data['transactionId'];
                 $amount = $data['amount'];
                 $paymentTime = $data['paymentTime'];
                 $objModelTransaction = new Transaction();
                 $input = array('tx_id' => '', 'tx_type' => '1', 'tx_mode' => '0', 'tx_code' => ' ', 'transaction_id' => $transactionId, 'user_id' => $userId, 'amount' => $amount, 'payment_time' => strtotime($paymentTime));
                 $result = $objModelTransaction->addNewTransaction($input);
                 //code for increasing the amount (updating the account bal)
                 // first checking that user has details in usersmeta table or not, if not then acc_bal will be 0 & add users with amount
                 // or if yes then update accountbalance
                 $objModelUsermeta = new Usersmeta();
                 $whereForUpdateUser = array('rawQuery' => 'user_id = ?', 'bindParams' => [$userId]);
                 $isUserAvailable = $objModelUsermeta->getUsermetaWhere($whereForUpdateUser);
                 if ($isUserAvailable) {
                     $accountBal = $isUserAvailable->account_bal;
                     $totalBalance = $accountBal + $amount;
                     $dataForUpdateUser = array('account_bal' => $totalBalance);
                     //                        return $dataForUpdateUser;
                     $updated = $objModelUsermeta->updateUsermetaWhere($whereForUpdateUser, $dataForUpdateUser);
                 } else {
                     $accountBal = 0;
                     $totalBalance = $accountBal + $amount;
                     $addData = array('user_id' => $userId, 'account_bal' => $totalBalance);
                     $addUsermeta = $objModelUsermeta->addUsermeta($addData);
                 }
                 // code for generating NOTIFICATION
                 $objModelNotification = Notification::getInstance();
                 $input = array('notification_id' => '', 'user_id' => $userId, 'notifications_txt' => '$ ' . $amount . ' is successfully credited to your account');
                 $addNotification = $objModelNotification->addNewNotification($input);
                 $response->code = 200;
                 $response->message = "Amount added to your Wallet Successfully.";
                 //                    $response->notification="Your Account is Successfully Credited.";
                 $response->data = $totalBalance;
                 //                    echo '<pre>';print_r($response);die;
                 //                    return $response;
                 echo json_encode($response, true);
             } else {
                 if ($result['ACK'] == "SuccessWithWarning") {
                     //                        return 6;
                     $response->code = 07;
                     $response->message = "Amount added to your Wallet Successfully.";
                     $data['transactionId'] = $result['PAYMENTINFO_0_TRANSACTIONID'];
                     $data['acknowledgement'] = $result['ACK'];
                     $data['amount'] = $amount;
                     $data['paymentTime'] = date('Y-m-d H:i:s');
                     $response->data = $data;
                     echo json_encode($response, true);
                     //                        echo'<pre>';print_r($data);die;
                     //                        return $response->data = $data;
                     //                        echo "<pre>";
                     //                        print_r($result);
                     //                        die;
                     //                        return 7;
                 } else {
                     $response->code = 400;
                     $response->message = "Some ERROR OCCURRED.";
                     echo "<pre>";
                     print_r($result);
                     die;
                 }
             }
         }
         //                if ($result['ACK'] == "Success") {
         //                    $response->code = 200;
         //                    $response->message = "Payment model created successfully.";
         //                    $data['transactionId'] = $result['PAYMENTINFO_0_TRANSACTIONID'];
         //                    $data['acknowledgement'] = $result['ACK'];
         //                    $data['amount'] = $amount;
         //                    $data['paymentTime'] = date('Y-m-d H:i:s');
         //                    $response->data = $data;
         //                }
         //                if ($result) {
         //                    $response->code = 200;
         //                    $response->message = "Payment model created successfully.";
         //                    $response->data = 1;
         //                    echo json_encode($response, true);
     } else {
         $response->code = 400;
         $response->message = "Error in getting callback results. auth flag is not set";
         $response->data = null;
         echo json_encode($response, true);
     }
     //
     //        $payerid = $request->input('PayerID');
     //        $token = $request->input('token');
     //
     //        $objpaypal = paypal::getInstance();
     //        $result = $objpaypal->ConfirmPayment($amount, $token, $payerid);
     //
     ////        echo "<pre>";print_r($result);
     ////        die;
     //        if ($result['ACK'] == "Success") {
     //            $data['transactionId'] = $result['PAYMENTINFO_0_TRANSACTIONID'];
     //            $data['acknowledgement'] = $result['ACK'];
     //            $data['amount'] = $amount;
     //            $data['paymentTime'] = date('Y-m-d H:i:s');
     //        } else {
     //            echo "<pre>";
     //            print_r($result);
     //            die;
     //        }
     //        echo "<pre>";
     //        print_r($data);
     //        die;
 }
 public function sendScheduleEmails($userDetails)
 {
     $objUsersmetaModel = new Usersmeta();
     $objInstagramUserModel = new Instagram_User();
     foreach ($userDetails as $user) {
         $where = ['rawQuery' => 'user_id=?', 'bindParams' => [$user->user_id]];
         $queryResult = $objUsersmetaModel->updateUsermetaWhere($where, ['cronjob_status' => 0]);
         // replace with 1
     }
     foreach ($userDetails as $user) {
         // code for notify balance
         if ($user->notify_bal != 0) {
             if ($user->account_bal <= $user->notify_bal) {
                 $html = '<div>
                             <h3>Alert Message</h3><br>
                             <span>Your account balance is less than $' . $user->notify_bal . ' Please add balance in your account to continue autolikes service. </span><br>
                          </div>';
                 $subject = 'Less Balance Notification';
                 $toEmail = $user->email;
                 $result = $this->sendEmailNotification($html, $subject, $toEmail);
             }
         }
         $where = ['rawQuery' => 'instagram_users.by_user_id=?', 'bindParams' => [$user->user_id]];
         $data = ['instagram_users.ins_user_id', 'instagram_users.by_user_id', 'instagram_users.ins_username', 'instagram_users.pics_done', 'instagram_users.pics_limit', 'instagram_users.start_date_time', 'instagram_users.end_date_time'];
         $instagramUserDetails = $objInstagramUserModel->getUserDetails($where, $data);
         if ($instagramUserDetails) {
             // code for notify autolikes profile
             if ($user->notify_profile_likes != 0) {
                 $notifyUserCount = 0;
                 $tableBody = '<tbody>';
                 foreach ($instagramUserDetails as $insUser) {
                     $postLeft = $insUser->pics_limit - $insUser->pics_done;
                     if ($postLeft != 0 && $postLeft <= $user->notify_profile_likes) {
                         $tableBody = $tableBody . '<tr><td>' . $insUser->ins_username . '</td><td>' . $postLeft . '</td></tr>';
                         $notifyUserCount += 1;
                     }
                 }
                 //End of autolikes profile - Inner for loop
                 $tableBody = $tableBody . '<tbody>';
                 if ($notifyUserCount != 0) {
                     $html = '<div><h3>Alert Message</h3><br><span>The following autolikes users profile has less than ' . $user->notify_profile_likes . ' Post left. </span><br>
                               <table>
                                  <thead>
                                     <tr> <th>Instagram Username</th> <th>Autolikes Profile Post left</th>  </tr>
                                  </thead>
                                 ' . $tableBody . '
                               </table>
                           </div>';
                     $subject = 'Instagram Users Profile Notification';
                     $toEmail = $user->email;
                     $result = $this->sendEmailNotification($html, $subject, $toEmail);
                 }
             }
             // code for notify autolikes profile subscription
             if ($user->notify_daily_subscription != 0) {
                 $notifyUserCount = 0;
                 $dateTimeDiff = 0;
                 $tableBody = '<tbody>';
                 foreach ($instagramUserDetails as $insUser) {
                     if (intval($insUser->end_date_time) != 0) {
                         $endDateTime = intval($insUser->end_date_time);
                         $currentDateTime = time();
                         if ($currentDateTime <= $endDateTime) {
                             $dateTimeDiff = $endDateTime - $currentDateTime;
                             $notifyTime = intval($user->notify_daily_subscription);
                             if ($notifyTime == 3) {
                                 if ($dateTimeDiff <= 3600 * 24) {
                                     // 24 hr=3600*24
                                     $tableBody = $tableBody . '<tr><td>' . $insUser->ins_username . '</td><td>' . $this->getDateDifference($endDateTime) . ' </td></tr>';
                                     $where = ['rawQuery' => 'ins_user_id=?', 'bindParams' => [$insUser->ins_user_id]];
                                     $customMessageData['message'] = 'This instagram users Auto Likes profile subscription will expire in th next 24 hrs) or (last day of Auto Likes profile subscription. It will expire today';
                                     $queryResult = $objInstagramUserModel->updateUserDetails($where, $customMessageData);
                                     $notifyUserCount += 1;
                                 }
                             } else {
                                 if ($notifyTime == 1) {
                                     if ($dateTimeDiff >= 3600 * 24 * 1 && $dateTimeDiff <= 3600 * 24 * 2) {
                                         // 48 hr=3600*24*2
                                         $tableBody = $tableBody . '<tr><td>' . $insUser->ins_username . '</td><td>' . $this->getDateDifference($endDateTime) . ' </td></tr>';
                                         $where = ['rawQuery' => 'ins_user_id=?', 'bindParams' => [$insUser->ins_user_id]];
                                         $customMessageData['message'] = 'This instagram users Auto Likes profile subscription will expire after 1 day) or ( only 2 days remaining for Auto Likes profile subscription.';
                                         $queryResult = $objInstagramUserModel->updateUserDetails($where, $customMessageData);
                                         $notifyUserCount += 1;
                                     }
                                 } else {
                                     if ($notifyTime == 2) {
                                         if ($dateTimeDiff >= 3600 * 24 * 2 && $dateTimeDiff <= 3600 * 24 * 3) {
                                             // 72 hr=3600*24*3
                                             $tableBody = $tableBody . '<tr><td>' . $insUser->ins_username . '</td><td>' . $this->getDateDifference($endDateTime) . ' </td></tr>';
                                             $where = ['rawQuery' => 'ins_user_id=?', 'bindParams' => [$insUser->ins_user_id]];
                                             $customMessageData['message'] = 'This instagram users Auto Likes profile subscription will expire after 2 days) or ( only 3 days remaining for Auto Likes profile subscription.';
                                             $queryResult = $objInstagramUserModel->updateUserDetails($where, $customMessageData);
                                             $notifyUserCount += 1;
                                         }
                                     }
                                 }
                             }
                         } else {
                             //Code for for Autolikes subscription expired.
                             //After end date reached system will pause the auto likes and set the profile status to finished
                             $where = ['rawQuery' => 'ins_user_id=?', 'bindParams' => [$insUser->ins_user_id]];
                             $queryResult = $objInstagramUserModel->updateUserDetails($where, ['ig_user_status' => 1]);
                         }
                     }
                 }
                 //End of profile subscription - Inner for loop
                 $tableBody = $tableBody . '<tbody>';
                 if ($notifyUserCount != 0) {
                     $html = '<div><h3>Alert Message</h3><br> <span>The following Instagram Auto-Likes profile are about to expire. </span><br>
                             <table>
                                 <thead>
                                     <tr> <th>Instagram Username</th> <th>Autolikes Profile subscription Expire after </th>  </tr>
                                 </thead>
                             ' . $tableBody . '
                             </table>
                         </div>';
                     $subject = 'Instagram Users Profile daily subscription Notification';
                     $toEmail = $user->email;
                     $result = $this->sendEmailNotification($html, $subject, $toEmail);
                 }
             }
         }
         $where = ['rawQuery' => 'user_id=?', 'bindParams' => [$user->user_id]];
         $queryResult = $objUsersmetaModel->updateUsermetaWhere($where, ['cronjob_status' => 0]);
     }
     //End of Outer for loop
 }
 function login(Request $request)
 {
     $response = new stdClass();
     if ($request->isMethod("POST")) {
         $postData = $request->all();
         $apiToken = "";
         if (isset($postData['api_token'])) {
             $apiToken = $postData['api_token'];
         }
         if ($apiToken == $this->API_TOKEN) {
             $rules = array('emailOrUsername' => 'required', 'password' => 'required');
             $messages = ['emailOrUsername.required' => 'Please enter email address or username ', 'password.required' => 'Please enter a password'];
             $validator = Validator::make($request->all(), $rules, $messages);
             if (!$validator->fails()) {
                 $objUserModel = new User();
                 $objUsermetaModel = new Usersmeta();
                 $username = $postData['emailOrUsername'];
                 $password = $postData['password'];
                 $field = 'username';
                 if (strpos($username, '@') !== false) {
                     $field = 'email';
                 }
                 if (Auth::attempt([$field => $username, 'password' => $password])) {
                     $whereForUser = ['rawQuery' => 'id =?', 'bindParams' => [Auth::id()]];
                     $userDetails = $objUserModel->getUsercredsWhere($whereForUser);
                     $whereForUsermeta = ['rawQuery' => 'user_id =?', 'bindParams' => [Auth::id()]];
                     //check if user id is exist in usersmeta if not then insert data in usersmeta table.
                     $isUserAvailable = $objUsermetaModel->getUsermetaWhere($whereForUsermeta, ['account_bal', 'notify_bal', 'notify_profile_likes', 'notify_daily_subscription']);
                     if (!isset($isUserAvailable->account_bal)) {
                         $addUsermeta = $objUsermetaModel->addUsermeta(['user_id' => Auth::id(), 'account_bal' => 0]);
                     } else {
                         $userDetails->account_bal = $isUserAvailable->account_bal;
                         $userDetails->notify_bal = $isUserAvailable->notify_bal;
                         $userDetails->notify_profile_likes = $isUserAvailable->notify_profile_likes;
                         $userDetails->notify_daily_subscription = $isUserAvailable->notify_daily_subscription;
                     }
                     if ($userDetails->status == 1) {
                         if (isset($postData['device_id']) && $postData['device_id'] != "") {
                             $data['device_id'] = $postData['device_id'];
                             $string = $userDetails->id . $postData['device_id'] . $this->API_TOKEN;
                             $token = hash('sha256', $string);
                             $data['login_token'] = $token;
                             $id = $userDetails->id;
                             $whereForUpdate = ['rawQuery' => 'id =?', 'bindParams' => [$id]];
                             $objUserModel->UpdateUserDetailsbyId($whereForUpdate, $data);
                             $userDetails->login_token = $token;
                             $userDetails->device_id = $postData['device_id'];
                         }
                         //                            dd($userDetails);
                         // update the user timezone in user table
                         if (isset($postData['user_timezone'])) {
                             $whereForUpdate = ['rawQuery' => 'id =?', 'bindParams' => [$userDetails->id]];
                             $data['user_timezone'] = $postData['user_timezone'];
                             $queryResult = $objUserModel->UpdateUserDetailsbyId($whereForUpdate, $data);
                         }
                         $response->code = 200;
                         $response->message = "Login successful.";
                         $response->data = $userDetails;
                         echo json_encode($response, true);
                     } else {
                         if ($userDetails->status == 0) {
                             $response->code = 400;
                             $response->message = " Your account is currently pending approval by the site administrator";
                             $response->data = null;
                             echo json_encode($response, true);
                         } else {
                             if ($userDetails->status == 2) {
                                 $response->message = 'This account has not been activated.';
                                 $response->code = 400;
                                 $response->data = null;
                                 echo json_encode($response, true);
                             } else {
                                 if ($userDetails->status == 3) {
                                     $response->message = ' Your account is currently rejected by the site administrator.';
                                     $response->code = 400;
                                     $response->data = null;
                                     echo json_encode($response, true);
                                 } else {
                                     if ($userDetails->status == 4) {
                                         $response->message = 'This account has been deleted.';
                                         $response->code = 400;
                                         $response->data = null;
                                         echo json_encode($response, true);
                                     }
                                 }
                             }
                         }
                     }
                 } else {
                     $response->message = 'Invalid login Credentials';
                     $response->code = 400;
                     $response->data = null;
                     echo json_encode($response, true);
                 }
             } else {
                 $response->code = 100;
                 $response->message = $validator->messages();
                 echo json_encode($response, true);
             }
         } else {
             $response->code = 401;
             $response->message = "Access Denied";
             $response->data = null;
             echo json_encode($response, true);
         }
     } else {
         $response->code = 401;
         $response->message = "Request Not allowed";
         $response->data = null;
         echo json_encode($response);
     }
 }