<?php
//********************************************************************************
//Title : User Controller
//Developer:Qureshi Faizan
//Email:qureshi@peerbits.com
//Company:Peerbits Solution
//Project:LPG Code
//Created By : Qureshi Faizan
//Created Date : 08-May-2018
//Updated Date :
//Updated By :
//********************************************************************************

/************************************************************************************************************************************
 *  CHANGE LOG & LATEST COMMITs : https://bitbucket.org/peerbitsrajesh/common-admin-by-rajesh/
    USER API CONTROLLER
    CREATED BY: RAJESH YADAV
    DATE : 12/06/2017

    BASE STRUCTURE FOR API COPY THIS WHENEVER WANT TO CREATE NEW API
   public function actionApiname()
    {
        /*insert all required veriables*/
        /*$required_objs = ['social_type','social_id','device_id','device_type','is_merge','is_provided_by_user'];
        /*boolean for login type to use in common function for login*/
        /*$login_type='s';


        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {

        }
        else{
            return Yii::$app->apifunction->setResponse('response_text',false,400,400);
        }*/

        /**return the result**/
        /*return $result;
    }
*************************************************************************************************************************************/

namespace app\modules\api\v2\controllers;
use Yii;
use yii\helpers\Url;
use yii\rest\ActiveController;
use yii\helpers\ArrayHelper;
use yii\filters\auth\HttpBearerAuth;
use \Exception;//to use try catch we have to import this
//use app\modules\api\v1\models\Users;
use app\models\Userdevices;
use app\models\Orderlog;
use app\models\Order;
use app\models\Notification;
use app\models\Users;
use app\models\Brand;
use app\models\Zipcode;
use app\models\OrderDetail;
use app\models\Size;
use app\models\Product;
use app\models\Reason;
use app\models\UserReview;
use app\models\Review;
use app\models\Stock;
use app\models\Promocode;
use app\models\Cart;
use app\models\Contactus;
use app\models\UserAddress;
use app\models\Setting;
use app\models\Bankdetail;
use app\models\Vendorhistory;
use app\models\Userstore;
use yii2\web\Request;
use yii\filters\AccessControl;


class UserController extends ActiveController
{
    /*MODEL CLASS THAT IS USED BY THIS CONTROLLER*/
    public $modelClass = 'app\modules\api\v1\models\Users';

    /*
     *WRAPPER OF THE RESPONSE JSON
     *HERE I USED "User" WRAPPER
    */
    public $serializer = [
        'class' => 'yii\rest\Serializer',
        'collectionEnvelope' => 'user',
    ];



    /***************************************************************************************************************************
     *MAIN CONFUGURATION FOR THE RESPONSE
     *formats ==> RESPONSE FORMATE OF YOUR RESPONSE
     *$behaviors['authenticator']['except'] classTHIS WILL CONTAIN APIS THAT ARE NOT USED TO TOKEN
     *$behaviors['authenticator']['class']==> AUTHENTICATION METHOD
     *KEEP YOURSELF UPDATED WITH YII2 METHODS ON behaviors
     *
    ****************************************************************************************************************************/


    public function behaviors()
    {
        $behaviors[] = [
            'class' => \yii\filters\ContentNegotiator::className(),
            'formats' => [
                'application/json' => \yii\web\Response::FORMAT_JSON,
            ],
        ];

        $behaviors['authenticator'] = [
            /*this are the api where we dont want to set up the header login data*/
            'except' => ['gettoken','getcms','ipayresponse',/*'login','sociallogin','register','forgotpassword' ,'resetpassword','verifyotp','resendotp','getcms','getcategories','getitems','getstores','getavailabledrivercount',*/'emailexist', 'resendemail'],
            'class' => HttpBearerAuth::className(),

        ];

        return $behaviors;
    }

     //********************************************************************************
    //Title : Get Token
    //Developer: Qureshi Faizan
    //Email:qureshi@peerbits.com
    //Company:Peerbits Solution
    //Project:LPG Code
    //Created By : Qureshi Faizan
    //Created Date : 22-02-2018
    //Updated Date :
    //Updated By :
    //********************************************************************************

    public function actionGettoken()
    {
        extract($_POST);


        if(isset($device_id) && $device_id!=null && isset($device_type) && $device_type!=null)
        {
            //check device id and device type already there
            $userlogindata = Userdevices::find()->where(['device_id' => $device_id, 'device_type' => $device_type])->one();

            if(isset($userlogindata) && $userlogindata!=array())
            {
                //merge the data
            }
            else
            {
                $userlogindata = new Userdevices();
            }
        }
        else
        {
            $userlogindata = new Userdevices();
        }

        if (isset($device_id) && $device_id!=null)
			$userlogindata->device_id = $device_id;

		if (isset($device_type) && $device_type!=null)
			$userlogindata->device_type = $device_type;

        $userlogindata->user_id = '';
        $userlogindata->access_token = \Yii::$app->security->generateRandomString();
        $userlogindata->last_login_datetime = date("Y-m-d H:i:s");
        //echo "<pre>";
        //    print_r($userlogindata);die;
		if($userlogindata->save(false))
        {

        }
        else{
            //echo "<pre>";
            //print_r($userlogindata->getErrors());die;
        }
        $result['token']['token'] = $userlogindata->access_token;
		$result['token']['type'] = 'Bearer';

        return Yii::$app->apifunction->setResponse('',true,200,200,$result);


    }

    //********************************************************************************
    //Title : Update Device
    //Developer: Qureshi Faizan
    //Email:qureshi@peerbits.com
    //Company:Peerbits Solution
    //Project:LPG Code
    //Created By : Qureshi Faizan
    //Created Date : 22-02-2018
    //Updated Date :
    //Updated By :
    //********************************************************************************

    public function actionUpdatedevice()
    {
        $required_objs = ['device_id', 'device_type'];


        /*CHECK REQUIRED POST VERIABLES WITH VALUES*/
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {
            extract($_POST);
            $token=Yii::$app->user->identity->accessToken;


            //check device id and device type already there
            $userlogindata = Userdevices::find()->where(['access_token' => $token])->one();

            if(!is_object($userlogindata)){
                $userlogindata = new Userdevices();
            }
            if (isset($user_id) && $user_id!=null )
            $userlogindata->user_id = $user_id;


            if (isset($device_id) ){
                $userlogindata->device_id = $device_id;
            }
            if (isset($device_type))
                $userlogindata->device_type = $device_type;

            $userlogindata->save(false);
            $result['token']['token'] = $userlogindata->access_token;
            $result['token']['type'] = 'Bearer';

            return Yii::$app->apifunction->setResponse('',true,200,200,$result);
        }
        else
        {
            return Yii::$app->apifunction->setResponse('response_text',false,200,400);
        }
        return $result;

    }
    /**************************************************************************************************************************************
     *
     COMMON API FOR LOGIN
     CREATED BY : RAJESH YADAV
     LAST UPDATAED : 15/06/2017
     CHANGE LOGS : https://bitbucket.org/peerbitsrajesh/common-admin-by-rajesh/commits/
     PULL THE LATEST STABLE VERSION FROM ABOVE URL
     PARAMS :email(USERS EMAIL ADDRESS),REQUIRED
            :password(USERS PASSWORD),REQUIRED
            :device_id(USERS DEVICE ID FOR UPDATING FOR NOTIFICATION POURPOSE),REQUIRED
            :device_type(USERS DEVICE TYPE FOR IOS OR ANDROID),REQUIRED
            :project_enviroment:(d,p // TO RESOLVE THE PEM FILE ISSUES ON SERVER AND AVOID THE BREAKDOWN)OPTIONAL(IF NOT SET THEN BY DEFAULT n)

    /*TO DOS:MAY WE NEED TO MODIFY THE checkIsPost FUNCTION DEPEND ON THE VERIABLE I AM CONSTANT IN TESTING MODE TO IMPROVISE

    ******************************************************************************************************************************************/

    //********************************************************************************
    //Title : Login
    //Developer: Qureshi Faizan
    //Email:qureshi@peerbits.com
    //Company:Peerbits Solution
    //Project:LPG Code
    //Created By : Qureshi Faizan
    //Created Date : 22-02-2018
    //Updated Date :
    //Updated By :
    //********************************************************************************

    public function actionLogin()
    {

        // die(var_dump("expression"));
        //insert all required veriables
        $required_objs = ['mobile_number','password', 'device_id', 'device_type'];
        $login_type='n';

        /*CHECK REQUIRED POST VERIABLES WITH VALUES*/
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {

            //convert post veriables to keynames
            extract($_POST);
            if(!isset($device_id)){$device_id=null;}
            if(!isset($device_type)){$device_type=null;}


            //$data = Users::find()->where(['is_deleted'=>'N','password'=>md5($password),'country_code'=>$country_code,'user_type'=>["U"],"contact_number"=>$contact_number])->one();
            //$data = Users::find()->where(['is_deleted'=>'N','password'=>md5($password),'email'=>$email,'user_type'=>["U"]])->one();
            $data = Yii::$app->apifunction->getUserDetailOnPasswordForLogin($mobile_number,$password,'U');


            if(isset($data) && $data != array())
            {

                switch ($data) {
                    case $data->is_active=='N':
                    $result_code = 803;
                    break;
                    default:
                    $result_code = 200;
                }

                /*if from admin panel the user is not activated then  we will show this below message*/
                if($result_code==803 || $result_code==802 || $result_code==801)
                {

                    //$result['message'] = Yii::t('app',Yii::$app->params['account_deactivate']);
                    return Yii::$app->apifunction->setResponse('account_deactivate',false,200,400);
                    //Yii::$app->getResponse()->setStatusCode(400);

                }
                // if($data->mobile_verified=="N")
                // {
                //    return Yii::$app->apifunction->setResponse('phone_verification_pending',false,200,400);
                // }
                // if($data->email_verified=="N")
                // {
                //    return Yii::$app->apifunction->setResponse('email_verification_pending',false,200,400);
                // }
                if($data->is_deleted=="Y")
                {
                   return Yii::$app->apifunction->setResponse('account_deleted_message',false,200,400);
                }
                //if(isset($data->email) && $data->email!=null)
                //{
                //    if($data->email_verified=="N")
                //    {
                //        return Yii::$app->apifunction->setResponse('email_verification_pending',false,200,400);
                //    }
                //}

                //set device and device type to access token
                $token_result = Yii::$app->apifunction->manageToken($data->id, $device_id, $device_type,Yii::$app->user->identity->accessToken);
               // die(var_dump($token_result));
                /*common code for login device updation is also there*/
                $result = Yii::$app->apifunction->apiLogin($data, $device_id, $device_type, $login_type,'',false);
                //die(var_dump( $result));
                return Yii::$app->apifunction->setResponse('welcome_login',true,200,200,$result);
               // $result["token"] = Yii::$app->apifunction->Userlogintocken($data->id, $device_id, $device_type);
                return $result;
            }else
            {
                return Yii::$app->apifunction->setResponse('invalid_login_1',false,200,400);
            }
        }
        else
        {

            return Yii::$app->apifunction->setResponse('response_text',false,200,400);
        }

        return $result;
    }

    /*=============================================================================================================================================
     Created by :
     Date : 30/06/2017
     API Name : Social signup
     TO DO :
     Tested : not yet
     RESPONSE TIME:

     PARAMS :   SOCIALID(REQUIRED),
                SOCIALTYPE(REQUIRED)(F,G),
                NAME,
                EMAIL,
                IMAGE URL,
                ISPROVIDEDBYUSER(IS EMAIL PROVIDED BY USER)(REQUIRED),
                ISMERGE(REQUIRED),
                DEVICEID,
                DEVICETYPE,



     ALGORITHM :- STEP 1 : CHECK SOCIAL ID IS EXIST OR NOT
                  STEP 2 : IF EXIST THEN LOGIN
                  STEP 3 : CHECK EMAIL IS PROVIDED OR NOT
                  STEP 4 : IF NOT EMAIL 404 EMAIL NOT FOUND(line 191,195)
                  STEP 5 : IF EMAIL FOUND AND ALREADY REGISTERED

    ================================================================================================================================================*/
    //********************************************************************************
    //Title : Social Login (MObile Mandatory)
    //Developer: Qureshi Faizan
    //Email:qureshi@peerbits.com
    //Company:Peerbits Solution
    //Project:LPG Code
    //Created By : Qureshi Faizan
    //Created Date : 22-02-2018
    //Updated Date :
    //Updated By :
    //********************************************************************************
    public function actionSocialloginmobile()
    {
        //insert all required veriables
        //$required_objs = ['social_type','social_id'/*,'device_id','device_type'*/,'is_merge','is_provided_by_user'];
        $required_objs = ['social_type','social_id','is_merge','is_provided_by_user'];
        /*boolean for login type to use in common function for login*/
        $login_type='s';//S=SOCIAL,n=normal
        /*to by pass login or send verification email*/
        $login_imidiatly = 'n';
        $result['is_mobile_required']='n';
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {
            /*extract the post veiables*/
            extract($_POST);
            $is_merge = \strtolower($is_merge);
            $is_provided_by_user = \strtolower($is_provided_by_user);
            $social_type = strtolower($social_type);
            if(!isset($device_id)){$device_id=null;}
            if(!isset($device_type)){$device_type=null;}

            /*algorith step :1,2 check social id exists or not and proceed for next*/
            $user_obj =Yii::$app->apifunction->getUserDetailFromSocialId($social_type,$social_id);


            if($user_obj != array())
            {
                $token_result = Yii::$app->apifunction->manageToken($user_obj->id, $device_id, $device_type,Yii::$app->user->identity->accessToken);
                $result = Yii::$app->apifunction->apiLogin($user_obj,$device_id,$device_type,$social_type,$is_merge,false);

                if(\strtolower($social_type) =='f' && $user_obj->is_facebook_verified =='N' ){
                    return Yii::$app->apifunction->setResponse('phone_found_but_account_not_verified',true,200,400,$result);
                }
                if (\strtolower($social_type) == 't' && $user_obj->is_twitter_verified == 'N') {
                    return Yii::$app->apifunction->setResponse('phone_found_but_account_not_verified', true, 200,400,$result);
                }
                if (\strtolower($social_type) == 'g' && $user_obj->is_google_verified == 'N') {
                    return Yii::$app->apifunction->setResponse('phone_found_but_account_not_verified', true, 200,400,$result);
                }
                return Yii::$app->apifunction->setResponse('welcome_login',true,200,200,$result);
                /*common code for login device updation is alos there*/


                return $result;
            }

            /*ALGORITHM STEP 3 BEGINS, USER IS NOT REGISTERED FIRST TIME HERE*/
            //if(isset($email) && $email != null)
            if(isset($country_code) && $country_code != null && isset($contact_number) && $contact_number != null)
            {
                /*check user obj*/
                //$user_obj_from_email = Yii::$app->apifunction->getUserDetailOnEmail($email,'u');
                $user_obj_from_phone=$data = Users::find()->where(['is_deleted'=>'N','country_code'=>$country_code,'user_type'=>["U"],"contact_number"=>$contact_number])->one();

                if($user_obj_from_phone)
                {
                    if($user_obj_from_phone->is_active =='n')
                    {
                        /*here need to check that user is deactivated or not*/
                        return Yii::$app->apifunction->setResponse('phone_foun_but_account_deactivate',false,200,400);
                    }
                    //$email_data = Users::find()->where(['is_deleted'=>'N','email'=>$email,'user_type'=>["U"]])->one();
                    //if(isset($email_data) && $email_data != array())
                    //    return Yii::$app->apifunction->setResponse('email_exist_already',false, 200, 400);

                    /*email found now check is merge*/
                    if($is_merge =='n')
                    {
                        $result['is_merge']='y';
                        return Yii::$app->apifunction->setResponse('phone_registered_want_merge',true,200,400,$result);

                    }elseif($is_merge =='y')
                    {

                        /*user want to merge the account, check email provided by user or not*/
                        if(isset($is_provided_by_user) && $is_provided_by_user == 'n')
                        {
                            $login_imidiatly = 'y';
                        }
                        if ($social_type == 'i') {
                            $user_obj_from_phone->instagram_id = $social_id;
                            $user_obj_from_phone->instagram_token=md5($social_id);
                            $token=$user_obj_from_phone->instagram_token;
                            if ($login_imidiatly == 'y') {
                                $user_obj_from_phone->is_instagram_verified = 'Y';
                                $user_obj_from_phone->mobile_verified = 'Y';
                            }

                        } else if($social_type == 't') {
                            $user_obj_from_phone->twitter_id = $social_id;
                            $user_obj_from_phone->twitter_token=md5($social_id);
                            $token=$user_obj_from_phone->twitter_token;
                            if ($login_imidiatly == 'y') {
                                $user_obj_from_phone->is_twitter_verified = 'Y';
                                $user_obj_from_phone->mobile_verified = 'Y';
                            }
                        }
                        else if($social_type == 'f') {
                            $user_obj_from_phone->facebook_id = $social_id;
                            $user_obj_from_phone->facebook_token=md5($social_id);
                            $token=$user_obj_from_phone->facebook_token;
                            if($login_imidiatly=='y')
                            {
                                $user_obj_from_phone->is_facebook_verified = 'Y';
                                $user_obj_from_phone->mobile_verified = 'Y';
                            }
                        }
                        else{
                            $user_obj_from_phone->google_id = $social_id;
                            $user_obj_from_phone->google_token=md5($social_id);
                            $token=$user_obj_from_phone->google_token;
                            if($login_imidiatly=='y')
                            {
                                $user_obj_from_phone->is_google_verified = 'Y';
                                $user_obj_from_phone->mobile_verified = 'Y';
                            }
                        }
                        //echo "<pre>";
                        //print_r($user_obj);die;
                        $user_obj_from_phone->email_verified = 'Y';
                        if(isset($email) && $email!=null)
                        {
                            $user_obj_from_phone->email = isset($email) ? $email : "";
                            $user_obj_from_phone->email_verified = 'N';
                        }
                        //if($user_obj_from_phone->first_name==null)
                        $user_obj_from_phone->first_name = isset($fullname) ? $fullname : "";

                        //if($user_obj_from_phone->image==null)
                        $user_obj_from_phone->image = isset($profile_image) ? $profile_image : "";
                        if(isset($_FILES['profile_image']['tmp_name']) && $_FILES['profile_image']['tmp_name'] != null)
                        {
                            $image = $_FILES['profile_image']['name'];
                            $tmp = $_FILES['profile_image']['tmp_name'];
                            $ext = substr(strrchr($image, "."), 1);
                            $fileName = md5(rand() * time()) . ".$ext";
                            $user_obj_from_phone->image = Yii::$app->common->Uploadimageonbucket($fileName,$tmp);
                        }

                        $user_obj_from_phone->save(false);
                        if(isset($email) && $email!=null)
                        {
                            $link=Url::to("@web/site/useremailverification?args=".$token."&type=".strtoupper($social_type),true);
                            Yii::$app->common->sendemail($user_obj_from_phone->email,$user_obj_from_phone->first_name,$link,'emailverify');
                            $user_obj_from_phone->email_verified = 'N';
                        }
                        else
                            $user_obj_from_phone->email_verified = 'Y';

                        if($login_imidiatly=='n')
                        {
                            $otp=Yii::$app->common->generate_otp_code();
                            $user_obj_from_phone->otp=$otp;

                            //Yii::$app->common->sendsms($user_obj_from_phone->country_code.$user_obj_from_phone->contact_number,'Welcome to '.Yii::$app->params['appName'].', One Time Password(OTP) to verify your phone number is :'.$otp);
                            if(isset($user_obj_from_phone->email) && $user_obj_from_phone->email!=null)
                            {
                                $content='Welcome to '.Yii::$app->params['appName'].', One Time Password(OTP) to verify your phone number is :'.$otp;
                                Yii::$app->common->otpemail($user_obj_from_phone->email,$user_obj_from_phone->user_name,$content,'otp_mail');
                            }

                            $user_obj_from_phone->mobile_verified = 'N';
                            //$user_obj_from_phone->email_verified = 'N';
                            $user_obj_from_phone->save(false);
                        }
                        //echo "here";die;
                        $token_result = Yii::$app->apifunction->manageToken($user_obj_from_phone->id, $device_id, $device_type,Yii::$app->user->identity->accessToken);
                        $result = Yii::$app->apifunction->apiLogin($user_obj_from_phone, $device_id, $device_type, $social_type,'N',false);
                        return Yii::$app->apifunction->setResponse('welcome_login',true,200,200,$result);
                        //if($login_imidiatly=='y'){
                        //    return Yii::$app->apifunction->apiLogin($user_obj_from_phone,$device_id,$device_type,$login_type,$is_merge);
                        //}
                        //$send_verification = Yii::$app->apifunction->sendVerificationEmail($user_obj_from_phone,$social_type);

                        //if($send_verification == true)
                        //{
                        //    return Yii::$app->apifunction->setResponse('email_send_verification',false,505);
                        //}else{
                        //    return Yii::$app->apifunction->setResponse('error_in_saving_data',false,500);
                        //}
                    }

                }else{

                    /*no email found create new user*/
                    $user_obj = new Users();
                    //print_r($user_obj);;exit;
                    if($social_type =='g')
                    {
                        $user_obj->google_id = $social_id;
                        $user_obj->google_token=md5($social_id);
                        $token=$user_obj->google_token;
                        if(isset($is_provided_by_user) && $is_provided_by_user == 'n')
                        {
                            $user_obj->is_google_verified = 'Y';
                            $user_obj->mobile_verified = 'Y';
                        }
                    }
                    if($social_type =='f')
                    {
                        $user_obj->facebook_id = $social_id;
                        $user_obj->facebook_token=md5($social_id);
                        $token=$user_obj->facebook_token;
                        if(isset($is_provided_by_user) && $is_provided_by_user == 'n')
                        {
                            $user_obj->is_facebook_verified = 'Y';
                            $user_obj->mobile_verified = 'Y';
                        }
                    }
                    $email_data = Users::find()->where(['is_deleted'=>'N','email'=>$email,'user_type'=>["U"]])->one();
                    if(isset($email_data) && $email_data != array())
                        return Yii::$app->apifunction->setResponse('email_exist_already',false, 200, 400);

                    $user_obj->email_verified = 'Y';
                    if(isset($email) && $email!=null)
                    {
                        $user_obj->email = isset($email) ? $email : "";
                        $user_obj->email_verified = 'N';
                    }
                    $user_obj->first_name = isset($fullname) ? $fullname : "";

                    $user_obj->image = isset($profile_image) ? $profile_image : "";
                    if(isset($_FILES['profile_image']['tmp_name']) && $_FILES['profile_image']['tmp_name'] != null)
                    {
                        $image = $_FILES['profile_image']['name'];
                        $tmp = $_FILES['profile_image']['tmp_name'];
                        $ext = substr(strrchr($image, "."), 1);
                        $fileName = md5(rand() * time()) . ".$ext";
                        $user_obj->image = Yii::$app->common->Uploadimageonbucket($fileName,$tmp);
                    }
                    $user_obj->country_code = isset($country_code) ? $country_code : "";
                    $user_obj->contact_number = isset($contact_number) ? $contact_number : "";

                    /*belo 3 lines will be automaticaly saved*/
                    $user_obj->user_type = 'U';
                    // $user_obj->i_date = date('Y-m-d H:i:s');
                    // $user_obj->u_date = date('Y-m-d H:i:s');
                    $user_obj->i_date = time();
                    $user_obj->u_date = time();

                    /*IF DATA ARE NOT SAVED THEN SEND THE IMIDIATE ERRROR*/
                    if(!$user_obj->save(false))
                    {
                        return Yii::$app->apifunction->setResponse('error_in_saving_data',false,200,400);
                    }
                    /*email is provided by user_error and merge , so email verification is required*/
                        //$send_verification = Yii::$app->apifunction->sendVerificationEmail($user_obj,$social_type);
                    if(isset($email) && $email!=null)
                    {
                        $link=Url::to("@web/site/useremailverification?args=".$token."&type=".strtoupper($social_type),true);
                        Yii::$app->common->sendemail($user_obj->email,$user_obj->first_name,$link,'emailverify');
                        $user_obj->email_verified = 'N';
                    }
                    else
                        $user_obj->email_verified = 'Y';
                    $user_obj->i_by = $user_obj->id;
                    $user_obj->u_by = $user_obj->id;
                    $user_obj->save(false);
                    if(isset($is_provided_by_user) && \strtolower($is_provided_by_user) == 'y')
                    {

                        $otp=Yii::$app->common->generate_otp_code();
                        $user_obj->otp=$otp;

                        //Yii::$app->common->sendsms($user_obj->country_code.$user_obj->contact_number,'Welcome to '.Yii::$app->params['appName'].', One Time Password(OTP) to verify your phone number is :'.$otp);
                        if(isset($user_obj->email) && $user_obj->email!=null)
                        {
                            $content='Welcome to '.Yii::$app->params['appName'].', One Time Password(OTP) to verify your phone number is :'.$otp;
                            Yii::$app->common->otpemail($user_obj->email,$user_obj->user_name,$content,'otp_mail');
                        }
                        $user_obj->mobile_verified = 'N';
                        //$user_obj->email_verified = 'N';
                        $user_obj->save(false);

                        //if($send_verification == true)
                        //{
                        //    return Yii::$app->apifunction->setResponse('email_send_verification',false,505);
                        //}else{
                        //    return Yii::$app->apifunction->setResponse('error_in_saving_data',false,500);
                        //}
                    }
                    //set device and device type to access token
                    $token_result = Yii::$app->apifunction->manageToken($user_obj->id, $device_id, $device_type,Yii::$app->user->identity->accessToken);
                    $result = Yii::$app->apifunction->apiLogin($user_obj, $device_id, $device_type, $social_type,'N',false);
                        return Yii::$app->apifunction->setResponse('welcome_login',true,200,200,$result);
                    //elseif(isset($is_provided_by_user) && \strtolower($is_provided_by_user) == 'n') {
                    //    /*email is not provided by user so merge account and login imidiatly*/
                    //    return Yii::$app->apifunction->apiLogin($user_obj,$device_id,$device_type,$login_type);
                    //}
                }
            }else{
                /*step : 4 from algo*/
                $result['is_mobile_required']='y';
                return Yii::$app->apifunction->setResponse('phone_required',true,200,200,$result);
            }
        }
        else{
            return Yii::$app->apifunction->setResponse('response_text',false,200,400);
        }
        /*return the result*/
       // return $result;
    }
    //********************************************************************************
    //Title : Social Login (Email Mandatory)
    //Developer: Qureshi Faizan
    //Email:qureshi@peerbits.com
    //Company:Peerbits Solution
    //Project:LPG Code
    //Created By : Qureshi Faizan
    //Created Date : 23-02-2018
    //Updated Date :
    //Updated By :
    //********************************************************************************
    public function actionSociallogin()
    {
        //insert all required veriables
        //$required_objs = ['social_type','social_id'/*,'device_id','device_type'*/,'is_merge','is_provided_by_user'];
        $required_objs = ['social_type','social_id','is_merge','is_provided_by_user'];
        /*boolean for login type to use in common function for login*/
        $login_type='s';//S=SOCIAL,n=normal
        /*to by pass login or send verification email*/
        $login_imidiatly = 'n';
        $result['is_email_required']='n';
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {
            /*extract the post veiables*/
            extract($_POST);
            $is_merge = \strtolower($is_merge);
            $is_provided_by_user = \strtolower($is_provided_by_user);
            $social_type = strtolower($social_type);
            if(!isset($device_id)){$device_id=null;}
            if(!isset($device_type)){$device_type=null;}

            /*algorith step :1,2 check social id exists or not and proceed for next*/
            $user_obj =Yii::$app->apifunction->getUserDetailFromSocialId($social_type,$social_id);


            if($user_obj != array())
            {
                $token_result = Yii::$app->apifunction->manageToken($user_obj->id, $device_id, $device_type,Yii::$app->user->identity->accessToken);
                $result = Yii::$app->apifunction->apiLogin($user_obj,$device_id,$device_type,$social_type,$is_merge,false);

                if(\strtolower($social_type) =='f' && $user_obj->is_facebook_verified =='N' ){
                    return Yii::$app->apifunction->setResponse('phone_found_but_account_not_verified',true,200,400,$result);
                }
                if (\strtolower($social_type) == 't' && $user_obj->is_twitter_verified == 'N') {
                    return Yii::$app->apifunction->setResponse('phone_found_but_account_not_verified', true, 200,400,$result);
                }
                if (\strtolower($social_type) == 'g' && $user_obj->is_google_verified == 'N') {
                    return Yii::$app->apifunction->setResponse('phone_found_but_account_not_verified', true, 200,400,$result);
                }
                return Yii::$app->apifunction->setResponse('welcome_login',true,200,200,$result);
                /*common code for login device updation is alos there*/


                return $result;
            }

            /*ALGORITHM STEP 3 BEGINS, USER IS NOT REGISTERED FIRST TIME HERE*/
            //if(isset($email) && $email != null)
            if(isset($email) && $email != null )
            {
                /*check user obj*/
                //$user_obj_from_email = Yii::$app->apifunction->getUserDetailOnEmail($email,'u');
                $user_obj_from_phone=$data = Users::find()->where(['is_deleted'=>'N','email'=>$email,'user_type'=>["U"]])->one();

                if($user_obj_from_phone)
                {
                    if($user_obj_from_phone->is_active =='n')
                    {
                        /*here need to check that user is deactivated or not*/
                        return Yii::$app->apifunction->setResponse('email_found_but_account_deactivate',false,200,400);
                    }
                    //$email_data = Users::find()->where(['is_deleted'=>'N','email'=>$email,'user_type'=>["U"]])->one();
                    //if(isset($email_data) && $email_data != array())
                    //    return Yii::$app->apifunction->setResponse('email_exist_already',false, 200, 400);

                    /*email found now check is merge*/
                    if($is_merge =='n')
                    {
                        $result['is_merge']='y';
                        return Yii::$app->apifunction->setResponse('email_registered_want_merge',true,200,400,$result);

                    }
					elseif($is_merge =='y')
                    {

                        /*user want to merge the account, check email provided by user or not*/
                        if(isset($is_provided_by_user) && $is_provided_by_user == 'n')
                        {
                            $login_imidiatly = 'y';
                        }
                        if ($social_type == 'i') {
                            $user_obj_from_phone->instagram_id = $social_id;
                            $user_obj_from_phone->instagram_token=md5($social_id);
                            $token=$user_obj_from_phone->instagram_token;
                            if ($login_imidiatly == 'y') {
                                $user_obj_from_phone->is_instagram_verified = 'Y';
                                $user_obj_from_phone->email_verified = 'Y';
                            }

                        } else if($social_type == 't') {
                            $user_obj_from_phone->twitter_id = $social_id;
                            $user_obj_from_phone->twitter_token=md5($social_id);
                            $token=$user_obj_from_phone->twitter_token;
                            if ($login_imidiatly == 'y') {
                                $user_obj_from_phone->is_twitter_verified = 'Y';
                                $user_obj_from_phone->email_verified = 'Y';
                            }
                        }
                        else if($social_type == 'f') {
                            $user_obj_from_phone->facebook_id = $social_id;
                            $user_obj_from_phone->facebook_token=md5($social_id);
                            $token=$user_obj_from_phone->facebook_token;
                            if($login_imidiatly=='y')
                            {
                                $user_obj_from_phone->is_facebook_verified = 'Y';
                                $user_obj_from_phone->email_verified = 'Y';
                            }
                        }
                        else{
                            $user_obj_from_phone->google_id = $social_id;
                            $user_obj_from_phone->google_token=md5($social_id);
                            $token=$user_obj_from_phone->google_token;
                            if($login_imidiatly=='y')
                            {
                                $user_obj_from_phone->is_google_verified = 'Y';
                                $user_obj_from_phone->email_verified = 'Y';
                            }
                        }
                        //echo "<pre>";
                        //print_r($user_obj);die;
                        $user_obj_from_phone->email = isset($email) ? $email : "";
                        //if($user_obj_from_phone->first_name==null)
                        $user_obj_from_phone->first_name = isset($fullname) ? $fullname : "";

                        //if($user_obj_from_phone->last_name==null)
                        //$user_obj_from_phone->last_name = isset($last_name) ? $last_name : "";
                        //if($user_obj_from_phone->image==null)
                        $user_obj_from_phone->image = isset($profile_image) ? $profile_image : "";
                        if(isset($_FILES['profile_image']['tmp_name']) && $_FILES['profile_image']['tmp_name'] != null)
                        {
                            $image = $_FILES['profile_image']['name'];
                            $tmp = $_FILES['profile_image']['tmp_name'];
                            $ext = substr(strrchr($image, "."), 1);
                            $fileName = md5(rand() * time()) . ".$ext";
                            //$user_obj_from_phone->image = Yii::$app->common->Uploadimageonbucket($fileName,$tmp);
                        }

                        $user_obj_from_phone->save(false);


                        if($login_imidiatly=='n')
                        {
                            if(isset($email) && $email!=null)
							{
								$first_name='User';
								if(isset($user_obj_from_phone->first_name) && $user_obj_from_phone->first_name!=null)
									$first_name=$user_obj_from_phone->first_name;

								$link=Url::to("@web/site/useremailverification?args=".$token."&type=".strtoupper($social_type),true);
								Yii::$app->common->sendemail($user_obj_from_phone->email,$first_name,$link,'emailverify');
								$user_obj_from_phone->email_verified = 'N';
							}
							else
								$user_obj_from_phone->email_verified = 'Y';
                            //$user_obj_from_phone->email_verified = 'N';
                            $user_obj_from_phone->save(false);
                        }
                        //echo "here";die;
                        $token_result = Yii::$app->apifunction->manageToken($user_obj_from_phone->id, $device_id, $device_type,Yii::$app->user->identity->accessToken);
                        $result = Yii::$app->apifunction->apiLogin($user_obj_from_phone, $device_id, $device_type, $social_type,'N',false);
                        return Yii::$app->apifunction->setResponse('welcome_login',true,200,200,$result);
                        //if($login_imidiatly=='y'){
                        //    return Yii::$app->apifunction->apiLogin($user_obj_from_phone,$device_id,$device_type,$login_type,$is_merge);
                        //}
                        //$send_verification = Yii::$app->apifunction->sendVerificationEmail($user_obj_from_phone,$social_type);

                        //if($send_verification == true)
                        //{
                        //    return Yii::$app->apifunction->setResponse('email_send_verification',false,505);
                        //}else{
                        //    return Yii::$app->apifunction->setResponse('error_in_saving_data',false,500);
                        //}
                    }

                }else{

                    /*no email found create new user*/
                    $user_obj = new Users();
                    //print_r($user_obj);;exit;
                    if($social_type =='g')
                    {
                        $user_obj->google_id = $social_id;
                        $user_obj->google_token=md5($social_id);
                        $token=$user_obj->google_token;
                        if(isset($is_provided_by_user) && $is_provided_by_user == 'n')
                        {
                            $user_obj->is_google_verified = 'Y';
                            $user_obj->email_verified = 'Y';
                        }
                    }
                    if($social_type =='f')
                    {
                        $user_obj->facebook_id = $social_id;
                        $user_obj->facebook_token=md5($social_id);
                        $token=$user_obj->facebook_token;
                        if(isset($is_provided_by_user) && $is_provided_by_user == 'n')
                        {
                            $user_obj->is_facebook_verified = 'Y';
                            $user_obj->email_verified = 'Y';
                        }
                    }
                    //$email_data = Users::find()->where(['is_deleted'=>'N','email'=>$email,'user_type'=>["U"]])->one();
                    //if(isset($email_data) && $email_data != array())
                    //    return Yii::$app->apifunction->setResponse('email_exist_already',false, 200, 400);
                    $user_obj->email = isset($email) ? $email : "";
                    $user_obj->first_name = isset($fullname) ? $fullname : "";
                    //$user_obj->last_name = isset($last_name) ? $last_name : "";
					$user_obj->image = isset($profile_image) ? $profile_image : "";


                    if(isset($_FILES['profile_image']['tmp_name']) && $_FILES['profile_image']['tmp_name'] != null)
                    {
                        $image = $_FILES['profile_image']['name'];
                        $tmp = $_FILES['profile_image']['tmp_name'];
                        $ext = substr(strrchr($image, "."), 1);
                        $fileName = md5(rand() * time()) . ".$ext";
                        //$user_obj->image = Yii::$app->common->Uploadimageonbucket($fileName,$tmp);
                    }
                    //$user_obj->country_code = isset($country_code) ? $country_code : "";
                    //$user_obj->contact_number = isset($contact_number) ? $contact_number : "";

                    /*belo 3 lines will be automaticaly saved*/
                    $user_obj->user_type = 'U';
                    // $user_obj->i_date = date('Y-m-d H:i:s');
                    // $user_obj->u_date = date('Y-m-d H:i:s');

                    $user_obj->i_date = time();
                    $user_obj->u_date = time();

                    /*IF DATA ARE NOT SAVED THEN SEND THE IMIDIATE ERRROR*/
                    if(!$user_obj->save(false))
                    {
                        return Yii::$app->apifunction->setResponse('error_in_saving_data',false,200,400);
                    }
                    /*email is provided by user_error and merge , so email verification is required*/
                        //$send_verification = Yii::$app->apifunction->sendVerificationEmail($user_obj,$social_type);

                    $user_obj->i_by = $user_obj->id;
                    $user_obj->u_by = $user_obj->id;
                    $user_obj->save(false);
                    if(isset($is_provided_by_user) && \strtolower($is_provided_by_user) == 'y')
                    {

                        if(isset($email) && $email!=null)
						{
							$first_name='User';
							if(isset($user_obj->first_name) && $user_obj->first_name!=null)
								$first_name=$user_obj->first_name;
							$link=Url::to("@web/site/useremailverification?args=".$token."&type=".strtoupper($social_type),true);
							Yii::$app->common->sendemail($user_obj->email,$first_name,$link,'emailverify');
							$user_obj->email_verified = 'N';

						}
						else
							$user_obj->email_verified = 'Y';

                        //if($send_verification == true)
                        //{
                        //    return Yii::$app->apifunction->setResponse('email_send_verification',false,505);
                        //}else{
                        //    return Yii::$app->apifunction->setResponse('error_in_saving_data',false,500);
                        //}
                    }
                    //set device and device type to access token
                    $token_result = Yii::$app->apifunction->manageToken($user_obj->id, $device_id, $device_type,Yii::$app->user->identity->accessToken);
                    $result = Yii::$app->apifunction->apiLogin($user_obj, $device_id, $device_type, $social_type,'N',false);
                        return Yii::$app->apifunction->setResponse('welcome_login',true,200,200,$result);
                    //elseif(isset($is_provided_by_user) && \strtolower($is_provided_by_user) == 'n') {
                    //    /*email is not provided by user so merge account and login imidiatly*/
                    //    return Yii::$app->apifunction->apiLogin($user_obj,$device_id,$device_type,$login_type);
                    //}
                }
            }else{
                /*step : 4 from algo*/
                $result['is_email_required']='y';
                return Yii::$app->apifunction->setResponse('email_required',true,200,200,$result);
            }
        }
        else{
            return Yii::$app->apifunction->setResponse('response_text',false,200,400);
        }
        /*return the result*/
       // return $result;
    }




    /***********************************************************************************************************************************
        API FOR Register
        CREATED BY :RAJESH YADAV
        DATE : 14/07/2017
        MODIFIED DATE :
        TESTED : NOT YET
    ***********************************************************************************************************************************/
    //********************************************************************************
    //Title : Register
    //Developer: Qureshi Faizan
    //Email:qureshi@peerbits.com
    //Company:Peerbits Solution
    //Project:LPG Code
    //Created By : Qureshi Faizan
    //Created Date : 22-02-2018
    //Updated Date :
    //Updated By :
    //********************************************************************************
    public function actionRegistersnew()
    {

        /**insert all required veriables*/
        $required_objs = ['password','full_name','email','mobile_number','device_id','device_type','country_code'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {
            extract($_POST);
            // $data = Yii::$app->apifunction->getUserDetailOnEmail($email,'u');
            $data = Yii::$app->apifunction->getUserDetailOnMobile($country_code,$mobile_number,'U');


            if(!empty($email))
            {

                $data = Yii::$app->apifunction->getUserDetailOnEmail($email,'U');
                // $contact_data = Yii::$app->apifunction->getUserDetailOnMobile($_POST['country_code'],$_POST['mobile_number'],'u');
                if(isset($data) && $data != array())
                    return Yii::$app->apifunction->setResponse('Email already exist',false, 200, 400);
            }

            if(!isset($device_id)){$device_id=null;}
            if(!isset($device_type)){$device_type=null;}
            if(!isset($dob)){$dob=null;}
            if($data == null)
            {

                if(isset($_POST['country_code']) && $_POST['country_code']!=null && isset($_POST['mobile_number']) && $_POST['mobile_number']!=null  )
                {


                    $contact_data = Yii::$app->apifunction->getUserDetailOnMobile($_POST['country_code'],$_POST['mobile_number'],'u');
                    if(isset($contact_data) && $contact_data != array())
                        return Yii::$app->apifunction->setResponse('phone_exist_already',false, 200, 400);
                }



                $user = new Users();

                //$user->username = $_POST['name'];
                if(isset($full_name) && $full_name != null)
                    $user->user_name = $_POST['full_name'];

                if(isset($last_name) && $last_name != null)
                    $user->last_name = $_POST['last_name'];

                $user->email_verified = 'Y';//if email is optional
                if(isset($_POST['email']) && $_POST['email']!=null)
                {
                    $user->email = $_POST['email'];
                    $user->email_verified = 'N';
                }
                $user->mobile_verified = 'Y'; //if mobile is optional
                if(isset($_POST['country_code']) && $_POST['country_code']!=null && isset($_POST['mobile_number']) && $_POST['mobile_number']!=null  )
                {
                    $user->country_code = $_POST['country_code'];
                    $user->mobile_number = $_POST['mobile_number'];
                    $user->mobile_verified = 'N';
                }
                $user->password = md5($_POST['password']);

                /*REMOVE IF YOU ARE SAVING globally SAVE METHOD*/
                $user->user_type = 'U';
                $user->notification_enabled = 'Y';

                // $user->i_date = date('Y-m-d H:i:s');
                // $user->u_date = date('Y-m-d H:i:s');

                $user->i_date = time();
                $user->u_date = time();

                $user->dob = $dob;
                $user->save(false);
                $user->i_by = $user->id;
                $user->u_by = $user->id;
                $user->email_verification_token = Yii::$app->apifunction->randomstring($user->id);
                $otp=Yii::$app->common->generate_otp_code();
                $user->otp=$otp;


                if(isset($_POST['country_code']) && $_POST['country_code']!=null && isset($_POST['mobile_number']) && $_POST['mobile_number']!=null  )
                {
                    $content='Your '.Yii::$app->params['appName'].', confirmation code is :'.$otp.'. It expires in 30 minutes, one-time use only.';
                     Yii::$app->common->sendsms($user->country_code.$user->mobile_number,$content);
                    if(isset($user->email) && $user->email!=null)
                        Yii::$app->common->otpemail($user->email,$user->user_name,$content,'otp_mail');

                    $user->mobile_verified = 'N';
                }

                if($user->save(false))
                {
                    ///*send mail via common code you can send via your default code too*/
                    //Yii::$app->apifunction->sendMail('Email Verification', $user->email, array('username' => $user->first_name, 'link' => $link), 'verifyemail');
                    if(isset($_POST['email']) && $_POST['email']!=null)
                    {
                        $link=Url::to("@web/site/useremailverification?args=".$user->email_verification_token."&type=N",true);
                        Yii::$app->common->sendemail($user->email,$user->user_name,$link,'emailverify');
                    }
                    //set device and device type to access token
                    $token_result = Yii::$app->apifunction->manageToken($user->id, $device_id, $device_type,Yii::$app->user->identity->accessToken);
                    ///*set the response code*/
                    $result = Yii::$app->apifunction->apiLogin($user, $device_id, $device_type, '','',false);
                    return Yii::$app->apifunction->setResponse('verification_email_sent', true, 200,200,$result);

                }

            }
            else
            {
                return Yii::$app->apifunction->setResponse('phone_exist_already',false, 200, 400);
            }
        }
        else
        {
            return Yii::$app->apifunction->setResponse('response_text',false,200,400);
        }
        return $result;
    }




    /***********************************************************************************************************************************
        API FOR Forgotpassword
        CREATED BY :INDRA SHASTRI
        DATE : 14/07/2017
        MODIFIED DATE :
        TESTED : NOT YET
    ***********************************************************************************************************************************/
    //********************************************************************************
    //Title : Forgot Password
    //Developer: Qureshi Faizan
    //Email:qureshi@peerbits.com
    //Company:Peerbits Solution
    //Project:LPG Code
    //Created By : Qureshi Faizan
    //Created Date : 08-May-2018
    //Updated Date :
    //Updated By :
    //********************************************************************************
    public function actionForgotpassword()
    {
        
        $required_objs = ['email'];

        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {
            extract($_POST);
            //check if user exist or not
            //$data = Yii::$app->apifunction->getUserDetailOnEmail($email,'u');
            $data = Yii::$app->apifunction->getUserDetailOnEmail($email,'U');
            // print_r($data);
            // die();
            if(isset($data) && $data!=array())
            {

                // set forgot password token, which will passed in url
                $random_str = time().rand(10000,99999);
                $data->forgot_password_token = md5($random_str);

                // set forgot password token timeout, set to 1 hour from now
                $data->forgot_password_token_timeout = time();

                if($data->save(false))
                {

                    // $link = Url::to("@web/site/resetpassword?args=".$data->forgot_password_token,true);

                    $link=Url::to("@web/admin/default/resetpassword?args=".$data->forgot_password_token,true);
                  //  die(print_r($link));
					Yii::$app->common->sendemail($data->email,$data->first_name,$link,'forgot');
                    return Yii::$app->apifunction->setResponse('forgot_password_link_sent',true,200,200);
                }
                else
                {
                    return Yii::$app->apifunction->setResponse('error_forgot_password',false,200,400);
                }
            }
            else
            {
                return Yii::$app->apifunction->setResponse('error_forgot_password_not_found',false,200,400);
            }
        }
        else
        {
            return Yii::$app->apifunction->setResponse('response_text',false,200,400);
        }
    }



    /***********************************************************************************************************************************
        API FOR Logout
        CREATED BY :RAJESH YADAV
        DATE : 14/07/2017
        MODIFIED DATE :
        TESTED : NOT YET
    ***********************************************************************************************************************************/

    public function actionLogout()
    {
        /*insert all required veriables*/
        $required_objs = [];
        if (Yii::$app->apifunction->CheckAuthToken()) {
            if (Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
                extract($_POST);
                Yii::$app->apifunction->updateAccessTockentoNull(Yii::$app->user->identity->accessToken);
                //$result = Yii::$app->apifunction->setResponse('success', true, 200);
                //$result["message"] = Yii::t('app', Yii::$app->params["success_logout"]);
                return Yii::$app->apifunction->setResponse('success_logout',true,200,400);
                return $result;
            } else {
                return Yii::$app->apifunction->setResponse('response_text',false,200,400);
            }
        }else{
            return Yii::$app->apifunction->setResponse('response_text',false,200,400);
        }


    }


    /***********************************************************************************************************************************
        API FOR Changepassword
        CREATED BY :RAJESH YADAV
        DATE : 14/07/2017
        MODIFIED DATE :
        TESTED : NOT YET
    ***********************************************************************************************************************************/
    //********************************************************************************
    //Title : Change Password
    //Developer: Qureshi Faizan
    //Email:qureshi@peerbits.com
    //Company:Peerbits Solution
    //Project:LPG Code
    //Created By : Qureshi Faizan
    //Created Date : 07-02-2018
    //Updated Date :
    //Updated By :
    //********************************************************************************
    public function actionChangepassword()
    {
        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = ['old_password','new_password'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {
            //check user is guest or not
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);


            extract($_POST);
            $userid = Yii::$app->user->id;
            $model = Users::findOne($userid);
            if(isset($model) && $model!=array())
            {

                if($model->is_active=='N')
                {
                    return Yii::$app->apifunction->setResponse('user_deactivated',false,200,400);
                }
                if(md5($old_password) != $model->password)
                {
                    return Yii::$app->apifunction->setResponse('incorrect_old_password',false,200,400);
                }

                if(md5($old_password) == md5($new_password))
                {
                    return Yii::$app->apifunction->setResponse('same_old_password',false,200,400);
                }


                /****save details*****/
                $password =md5($new_password);
                $model->password = md5($new_password);
                $model->save(false);
                /***if want to send the email*/
                //try{
                //     Yii::$app->apifunction->sendMail(Yii::$app->params['mail_subject_for_password_changed'],$model->email,array('username' => $model->first_name,'link'=>''),'passwordchanged');
                //}catch(Exception $e) {
                //    //hope you dont need to uncomment below
                //    //print $e
                //}


                return Yii::$app->apifunction->setResponse('password_changed',true,200,200);
            }
            else{
                return Yii::$app->apifunction->setResponse('error_user_not_found',false,200,400);
            }

        }
        else{
            return Yii::$app->apifunction->setResponse('response_text',false,400,400);
        }
        /**return the result**/
        return $result;
    }
    //********************************************************************************
    //Title : Resend OTP
    //Developer: Qureshi Faizan
    //Email:qureshi@peerbits.com
    //Company:Peerbits Solution
    //Project:LPG
    //Created By : Qureshi Faizan
    //Created Date : 23-02-2018
    //Updated Date :
    //Updated By :
    //********************************************************************************
    // public function actionResendotp()
    // {
    //     $required_objs = ['country_code','mobile_number'];
    //      /*CHECK REQUIRED POST VERIABLES WITH VALUES*/
    //     if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
    //         extract($_POST);

    //         $user_type = 'U';

    //         // if(isset(Yii::$app->user->identity->id) && Yii::$app->user->identity->id!=null) //for logged user (while change mobile number)
    //         //     $data= Users::find()->select('*')->where(['is_deleted'=>'N','id'=>Yii::$app->user->identity->id,"mobile_number"=>$mobile_number])->one();
    //         // else // for guest user
    //             $data= Users::find()->where(['is_deleted'=>'N','country_code'=>$country_code,'user_type'=>$user_type,"mobile_number"=>$mobile_number])->one();
    //         if(isset($data) && $data!=array())
    //         {
    //             if(isset($m_country_code) && $m_country_code!=null)
    //              $data->country_code = $m_country_code;

    //             if(isset($m_mobile_number) && $m_mobile_number!=null)
    //              $data->mobile_number = $m_mobile_number;

    //             $random_str = time().rand(10000,99999);
    //             $data->forgot_password_token = md5($random_str);

    //             // set forgot password token timeout, set to 1 hour from now
    //             $data->forgot_password_token_timeout = time();
    //             $otp=Yii::$app->common->generate_otp_code();
    //             $data->otp=$otp;
    //             if($data->save(false))
    //             {
    //                 //send sms to user mobile number

    //                 $mPIN = Yii::$app->common->generate_otp_code();
    //                 if($data->country_code !=null && $data->mobile_number!=null){
    //                     Yii::$app->common->sendsms($data->country_code.$data->mobile_number,'Welcome to '.Yii::$app->params['appName'].', One Time Password(OTP) to verify your phone number is :'.$otp);
    //                 }

    //                 if(isset($data->email) && $data->email!=null)
    //                 {
    //                     $content='Welcome to '.Yii::$app->params['appName'].', One Time Password(OTP) to verify your phone number is :'.$otp;
    //                     Yii::$app->common->otpemail($data->email,$data->user_name,$content,'otp_mail');
    //                 }
    //                 return Yii::$app->apifunction->setResponse('forgot_password_sms_resent',true,200,200);
    //             }
    //             else
    //             {
    //                 return Yii::$app->apifunction->setResponse('error_forgot_password',false,200,400);
    //             }
    //         }
    //         else
    //         {
    //             return Yii::$app->apifunction->setResponse('error_forgot_password_id_not_found',false,200,400);
    //         }
    //     } else {
    //         return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
    //     }
    // }

    public function actionResendotp()
    {
        $required_objs = ['country_code','mobile_number'];
         /*CHECK REQUIRED POST VERIABLES WITH VALUES*/
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            extract($_POST);

            $user_type = 'U';

            if(isset(Yii::$app->user->identity->id) && Yii::$app->user->identity->id!=null) //for logged user (while change mobile number)
                $data= Users::find()->select('*')->where(['is_deleted'=>'N','id'=>Yii::$app->user->identity->id])->one();
            else // for guest user
                $data= Users::find()->where(['is_deleted'=>'N','country_code'=>$country_code,'user_type'=>$user_type,"mobile_number"=>$mobile_number])->one();
            if(isset($data) && $data!=array())
            {

                if(isset($m_country_code) && $m_country_code!=null)
                 $data->country_code = $m_country_code;

                if(isset($m_mobile_number) && $m_mobile_number!=null)
                 $data->mobile_number = $m_mobile_number;


                $random_str = time().rand(10000,99999);
                $data->forgot_password_token = md5($random_str);

                // set forgot password token timeout, set to 1 hour from now
                $data->forgot_password_token_timeout = time();
                $otp=Yii::$app->common->generate_otp_code();
                $data->otp=$otp;
                if($data->save(false))
                {
                    //send sms to user mobile number
                    $mPIN = Yii::$app->common->generate_otp_code();
                    if($data->country_code!=null && $data->mobile_number!=null)
                       Yii::$app->common->sendsms($data->country_code.$data->mobile_number,'Your '.Yii::$app->params['appName'].', confirmation code is :'.$otp.'. It expires in 30 minutes, one-time use only.');

                    if(isset($data->email) && $data->email!=null)
                    {
                        $content='Welcome to '.Yii::$app->params['appName'].', One Time Password(OTP) to verify your phone number is :'.$otp;
                        Yii::$app->common->otpemail($data->email,$data->user_name,$content,'otp_mail');
                    }
                    return Yii::$app->apifunction->setResponse('forgot_password_sms_resent',true,200,200);
                }
                else
                {
                    return Yii::$app->apifunction->setResponse('error_forgot_password',false,200,400);
                }
            }
            else
            {
                return Yii::$app->apifunction->setResponse('error_forgot_password_id_not_found',false,200,400);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    }
    /***********************************************************************************************************************************
        API FOR VERIFY OTP
        CREATED BY :RAJESH YADAV
        DATE : 14/07/2017
        MODIFIED DATE :
        TESTED : NOT YET
    ***********************************************************************************************************************************/

    //********************************************************************************
    //Title : Verify OTP
    //Developer: Qureshi Faizan
    //Email:qureshi@peerbits.com
    //Company:Peerbits Solution
    //Project:LPG
    //Created By : Qureshi Faizan
    //Created Date : 23-02-2018
    //Updated Date :
    //Updated By :
    //********************************************************************************
    public function actionVerifyotp()
    {
        //insert all required veriables
        $required_objs = ['otp','country_code','mobile_number'];
        $login_type='n';

        /*CHECK REQUIRED POST VERIABLES WITH VALUES*/
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {
            if(!isset($device_id)){$device_id=null;}
            if(!isset($device_type)){$device_type=null;}
            //convert post veriables to keynames
            extract($_POST);
            //$userid = Yii::$app->user->id;
            if(isset(Yii::$app->user->identity->id) && Yii::$app->user->identity->id!=null)
                $data= Users::find()->select('*')->where(['is_deleted'=>'N','id'=>Yii::$app->user->identity->id])->one();
            else
                $data= Users::find()->select('*')->where(['is_deleted'=>'N','country_code'=>$country_code,'user_type'=>'U',"mobile_number"=>$mobile_number])->one();
            if(isset($data) && $data != array())
            {
                if($data->otp == $otp)
                {
                    $data->mobile_verified = 'Y';
                    $data->save(false);

                    $result = Yii::$app->apifunction->apiLogin($data, $device_id, $device_type, $login_type,'',false);

                    return Yii::$app->apifunction->setResponse('mobile_verified_successfully',true,200,200,$result);
                    // if($type=='f')//forgot password
                    // {
                    // return Yii::$app->apifunction->setResponse('mobile_verified_successfully',true,200,200);
                    // }
                    // if($type=='e')//From edit profile need to change new phone number
                    // {
                    //     //$model= Users::find()->select('*')->where(['is_deleted'=>'N','id'=>Yii::$app->user->identity->id])->one();
                    //     $data->country_code = $country_code;
                    //     $data->contact_number = $contact_number;
                    //     $data->u_by = Yii::$app->user->identity->id;
                    //     $data->u_date = date('Y-m-d H:i:s');
                    //     $data->save(false);
                    //     $result = Yii::$app->apifunction->apiLogin($data,$device_id, $device_type, '','',false);
                    //     return Yii::$app->apifunction->setResponse('mobile_verified_successfully',true,200,200,$result);
                    // }
                    // else
                    // {
                    //     $result = Yii::$app->apifunction->apiLogin($data,$device_id, $device_type, '','',false);
                    //     return Yii::$app->apifunction->setResponse('mobile_verified_successfully',true,200,200,$result);
                    // }
                }else{
                    return Yii::$app->apifunction->setResponse('mobile_verification_mismatch',false,200,400);
                }
            }else{
               return Yii::$app->apifunction->setResponse('error_forgot_password_id_not_found',false,200,400);
            }
        }
        else
        {
            return Yii::$app->apifunction->setResponse('response_text',false,200,400);
        }
        return $result;
    }
    //********************************************************************************
    //Title : Resend Email
    //Developer: Qureshi Faizan
    //Email:qureshi@peerbits.com
    //Company:Peerbits Solution
    //Project:LPG
    //Created By : Qureshi Faizan
    //Created Date : 23-02-2018
    //Updated Date :
    //Updated By :
    //********************************************************************************
	public function actionResendemail()
    {
        $required_objs = ['email'];
         /*CHECK REQUIRED POST VERIABLES WITH VALUES*/
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST))
		{
            extract($_POST);
            $data = Yii::$app->apifunction->getUserDetailOnEmail($email,'U');
            if(isset($data) && $data!=array())
			{
				$token=$type='';

                if(isset($_REQUEST['social_type']) && $_REQUEST['social_type']=='f')
                {
                  $type='F';
                  $data->facebook_token=md5($data->facebook_id);
                  $token=$data->facebook_token;
                  /*NEED TO CHECK FOR ALREADY VERIFIED I.E IF ALREADY VERIFIED*/
                }
                else if(isset($_REQUEST['social_type']) && $_REQUEST['social_type']=='g')
                {
                  $type='G';
                  $data->google_token=md5($data->google_id);
                  $token=$data->google_token;
                  /*NEED TO CHECK FOR ALREADY VERIFIED I.E IF ALREADY VERIFIED*/
                }
                else
                {
                    $type='N';//N for normal user(without social)

                    /*NEED TO CHECK FOR ALREADY VERIFIED I.E IF ALREADY VERIFIED*/

                    $data->email_verification_token=md5($data->id);
                    $token=$data->email_verification_token;
                }
				$data->save(false);
                $msg=Yii::$app->params['verification_link_sent'];
                $link=Url::to("@web/site/useremailverification?args=".$token."&type=".$type,true);
                Yii::$app->common->sendemail($data->email,$data->user_name,$link,'emailverify');
				return Yii::$app->apifunction->setResponse('resend_email',true,200,200);
            }
            else
			{

             return Yii::$app->apifunction->setResponse('error_forgot_password_id_not_found',false,200,400);
            }

        }
		else
		{
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    }
    //********************************************************************************
    //Title : Get CMS Page
    //Developer: Qureshi Faizan
    //Email:qureshi@peerbits.com
    //Company:Peerbits Solution
    //Project:LPG
    //Created By : Qureshi Faizan
    //Created Date : 23-02-2018
    //Updated Date :
    //Updated By :
    //********************************************************************************

    public function actionGetcms()
    {
        $required_objs = [];
         /*CHECK REQUIRED POST VERIABLES WITH VALUES*/
        if (Yii::$app->apifunction->checkIsPost($required_objs, $_POST))
        {
            // $result['terms_and_conditions']=Url::to("@web/site/terms?type=U",true);
            // $result['privacy_policy']=Url::to("@web/site/privacy_policy?type=U",true);
            // $result['faqs']=Url::to("@web/site/faq?type=U",true);

             $result['terms_and_conditions']='https://www.vitekenya.com/privacy-policy-2/';
            $result['privacy_policy']='https://www.vitekenya.com/privacy-policy-2/';
            $result['faqs']='https://www.vitekenya.com/faq/';

            $result['about_us']='https://www.vitekenya.com/#about';


   //          For terms and condition & Privacy policy: https://www.vitekenya.com/privacy-policy-2/
			// FAQ:  https://www.vitekenya.com/faq/

            return Yii::$app->apifunction->setResponse('',true,200,200,$result);
        }
        else
        {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }


        return $result;
    }

    //********************************************************************************
    //Title : Get Profile
    //Developer: Qureshi Faizan
    //Email:qureshi@peerbits.com
    //Company:Peerbits Solution
    //Project:LPG
    //Created By : Qureshi Faizan
    //Created Date : 07-02-2018
    //Updated Date :
    //Updated By :
    //********************************************************************************

    public function actionGetprofile()
    {
        $required_objs = ['user_id'];
         /*CHECK REQUIRED POST VERIABLES WITH VALUES*/
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST))
	{
            extract($_POST);
            $userid = Yii::$app->user->id;
            //check user is guest or not
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
            $data = Users::find()->where(['id'=>$user_id,'is_deleted'=>'N'])->one();
            if(!isset($device_id)){$device_id=null;}
            if(!isset($device_type)){$device_type=null;}

            if(isset($data) && $data != array())
            {

                if($data->is_active =='N')
                {
                    return Yii::$app->apifunction->setResponse('account_deactivate',false,200,400);
                }

                $result = Yii::$app->apifunction->apiLogin($data, $device_id, $device_type, '','',false);

                return Yii::$app->apifunction->setResponse('welcome_login',true,200,200,$result);

            }else{
                return Yii::$app->apifunction->setResponse('error_user_not_found',false,200,400);

            }
        }
        else
	{
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
        return $result;
    }
    /***********************************************************************************************************************************
        API FOR UPDATE PROFILE
        CREATED BY :RAJESH YADAV
        DATE : 14/07/2017
        MODIFIED DATE :
        TESTED : NOT YET
    ***********************************************************************************************************************************/
    //********************************************************************************
    //Title : Edit Profile
    //Developer: Qureshi Faizan
    //Email:qureshi@peerbits.com
    //Company:Peerbits Solution
    //Project:LPG
    //Created By : Qureshi Faizan
    //Created Date : 08-May-2018
    //Updated Date :
    //Updated By :
    //********************************************************************************

    public function actionUpdateprofile()
    {

        extract($_POST);
        $userid = Yii::$app->user->id;
        //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
        $data = Users::find()->where(['id'=>$userid,'is_deleted'=>'N'])->one();


        if(isset($data) && $data != array())
        {
            if(!isset($device_id)){$device_id=null;}
            if(!isset($device_type)){$device_type=null;}
            if($data->is_active =='N')
            {
                return Yii::$app->apifunction->setResponse('account_deactivate',false,200,400);
            }


            if(isset($_POST['email']))
            {
                if(empty($_POST['email']))
                {
                    $data->email='';
                }
                if($data->email != $_POST['email'])
                $check_email= Yii::$app->common->checkemail($_REQUEST['email'],$data->id,'U');

                if(isset($check_email) && $check_email != "")
                {

                    return Yii::$app->apifunction->setResponse('email_exist_already',false,200,400);
                }
                if($data->email!=$_POST['email'] && !empty($_POST['email']))
                {

                    $random_str = time().rand(10000,99999);
                    $data->email_verification_token = md5($random_str);
                    $link=Url::to("@web/site/useremailverification?args=".$data->email_verification_token."&type=N",true);
                    Yii::$app->common->sendemail($_REQUEST['email'],$data->user_name,$link,'emailverify');
                    $data->email_verified = 'N';
                }
                $data->email = $_POST['email'];
            }
            if(isset($_POST['first_name']) && $_POST['first_name'] != '')
            $data->first_name = $_POST['first_name'];

            if(isset($_POST['dob']) && $_POST['dob'] != ''   )
            $data->dob = $_POST['dob'];

            if(isset($_POST['full_name']) && $_POST['full_name'] != ''   )
            $data->user_name = $_POST['full_name'];

            if(isset($_POST['country_code']) && $_POST['country_code'] != '' && isset($_POST['mobile_number']) && $_POST['mobile_number'] != '')
            {

                $check_email= Yii::$app->common->checkmobile($_REQUEST['country_code'],$_POST['mobile_number'],$data->id,'U');
                if($check_email > 0){
                    return Yii::$app->apifunction->setResponse('phone_exist_already',false,200,400);
                }

                if($data->country_code!=$_POST['country_code'] || $data->mobile_number!=$_POST['mobile_number'] )
                {

                    $otp=Yii::$app->common->generate_otp_code();
                    $data->otp=$otp;
                    $data->country_code = $_POST['country_code'];
                    $data->mobile_number = $_POST['mobile_number'];

                    //Yii::$app->common->sendsms($data->country_code.$data->contact_number,'Welcome to '.Yii::$app->params['appName'].', One Time Password(OTP) to verify your phone number is :'.$otp);;
                    if(isset($data->email) && $data->email!=null)
                    {
                        $content='Welcome to '.Yii::$app->params['appName'].', One Time Password(OTP) to verify your phone number is :'.$otp;
                        Yii::$app->common->otpemail($data->email,$data->user_name,$content,'otp_mail');
                    }
                    $data->mobile_verified = 'N';
                }

            }
            if(isset($_FILES['profile_image']['tmp_name']) && $_FILES['profile_image']['tmp_name'] != null)
            {
                $image = $_FILES['profile_image']['name'];
                $tmp = $_FILES['profile_image']['tmp_name'];
                $ext = substr(strrchr($image, "."), 1);
                $fileName = md5(rand() * time()) . ".$ext";

                /**
                 * Unlink or delete the previouse image from server
                 */
                if($data->image != null && file_exists(Yii::getAlias('@webroot').'/'.$data->image))
                {
                    unlink(Yii::getAlias('@webroot')."/".$data->image);
                }

                $data->image = Yii::$app->apifunction->normalUpload($_FILES['profile_image'],yii::$app->params['user_direcotry']);
            }

            //update driver detail


            $data->u_by = $data->id;
            // $data->u_date = date('Y-m-d H:i:s');
            $data->u_date = time();
            $data->save(false);

            $result = Yii::$app->apifunction->apiLogin($data, $device_id, $device_type, 'e','',false);

            return Yii::$app->apifunction->setResponse('profile_successfully_updated',true,200,200,$result);

        }else{
            return Yii::$app->apifunction->setResponse('error_user_not_found',false,200,400);

        }
        return $result;
    }

    /*API FOR CLEAR BADGE*/

    public function actionClearbadge()
    {

        extract($_POST);

        $userid = Yii::$app->user->id;
        $badgeCount = (isset($badge_count) && $badge_count!= "") ? $badge_count : 0;
        $data = Users::find()->where(['id'=>$userid,'is_deleted'=>'N'])->one();
        if(!isset($device_id)){$device_id=null;}
            if(!isset($device_type)){$device_type=null;}

        if(isset($data) && $data != array())
        {
            Yii::$app->apifunction->clearbadge($userid,$badgeCount);
        }
        return Yii::$app->apifunction->setResponse('success',true,200,200);
    }

    public function actionContactus()
    {
        $required_objs = ['subject','message'];
        /*CHECK REQUIRED POST VERIABLES WITH VALUES*/
       if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST))
        {
            extract($_POST);
            $userid = Yii::$app->user->id;
            //check user is guest or not
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
            $data = Users::find()->where(['id'=>$userid,'is_deleted'=>'N'])->one();

            if(isset($data) && $data != array())
            {
                if(!isset($device_id)){$device_id=null;}
                if(!isset($device_type)){$device_type=null;}
                if($data->is_active =='N')
                {
                    return Yii::$app->apifunction->setResponse('account_deactivate',false,200,400);
                }

            $contactus = new Contactus();
            $contactus->i_by = $data->id;
            $contactus->subject = $subject;
            $contactus->message = $message;
            $contactus->first_name =  $data->user_name;
            $contactus->last_name = '';
            $contactus->phone_number =  $data->country_code.' '. $data->mobile_number;
            $contactus->email =  $data->email;
            $contactus->send_by = 'U';
            $contactus->i_date = time();

            if($contactus->save(false))
            {
                return Yii::$app->apifunction->setResponse(Yii::$app->params['thanks_feedback'],true,200,200);
            }

       }else{
            return Yii::$app->apifunction->setResponse('error_user_not_found',false,200,400);

        }
    }else{
            return Yii::$app->apifunction->setResponse('response_text',false,200,400);
        }
    }

    public function actionChangemobilenumber()
    {
        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = ['mobile_number','country_code'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {
            //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);


            extract($_POST);
            $userid = Yii::$app->user->id;


            $check_email= Yii::$app->common->checkmobile($_REQUEST['country_code'],$_POST['mobile_number'],$userid,'U');
            if($check_email > 0){
                return Yii::$app->apifunction->setResponse('phone_exist_already',false,200,400);
            }

            $model = Users::findOne($userid);
            if(isset($model) && $model!=array())
            {

                if($model->is_active=='N')
                {
                    return Yii::$app->apifunction->setResponse('user_deactivated',false,200,400);
                }

                /**
                * Save new Mobile number
                */

                $model->country_code = $country_code;
                $model->mobile_number = $mobile_number;

                $model->mobile_verified = 'N';

                $model->save(false);

                $mPIN = Yii::$app->common->generate_otp_code();

                $content='Your '.Yii::$app->params['appName'].', confirmation code is :'.$mPIN.'. It expires in 30 minutes, one-time use only.';
                Yii::$app->common->sendsms($model->country_code.$model->mobile_number,$content);
                if(isset($model->email) && $model->email!=null)
                    Yii::$app->common->otpemailrider($model->email,$model->user_name,$content,$model->country_code.' '.$model->mobile_number);

                /***if want to send the email*/
                //try{
                //     Yii::$app->apifunction->sendMail(Yii::$app->params['mail_subject_for_password_changed'],$model->email,array('username' => $model->first_name,'link'=>''),'passwordchanged');
                //}catch(Exception $e) {
                //    //hope you dont need to uncomment below
                //    //print $e
                //}


                return Yii::$app->apifunction->setResponse('mobile_number_changed',true,200,200);
            }
            else{
                return Yii::$app->apifunction->setResponse('error_user_not_found',false,200,400);
            }

        }
        else{
            return Yii::$app->apifunction->setResponse('response_text',false,400,400);
        }
        /**return the result**/
        return $result;
    }

    public function actionNotificationsetting(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = ['is_online'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {
            //check user is guest or not
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);


            extract($_POST);
            $userid = Yii::$app->user->id;
            $model = Users::findOne($userid);
            if(isset($model) && $model!=array())
            {

                if($model->is_active=='N')
                {
                    return Yii::$app->apifunction->setResponse('user_deactivated',false,200,400);
                }


                if(!in_array($is_online,['Y','N']))
                {
                    return Yii::$app->apifunction->setResponse('error_notification',false,200,400);
                }


                if(isset($is_online) && $is_online !=null)
                    $model->notification_enabled = $is_online;

                //now save record in database
                if($model->save(false)){
                    $message = $model->notification_enabled == 'N'?Yii::$app->params['success_notification_offline']:Yii::$app->params['success_notification_online'];
                        return Yii::$app->apifunction->setResponse($message,true,200,200);
                    }


            }else{
                return Yii::$app->apifunction->setResponse('error_user_not_found',false,200,400);
            }

        }else{
            return Yii::$app->apifunction->setResponse('response_text',false,400,400);
        }
      }//Notification settings end here

      public function actionAddeditaddress(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = ['full_name','mobile_number','country_code','house_number','estate','landmark','address','zipcode','is_default','latitude','longitude'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {
            //check user is guest or not
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);


            extract($_POST);

            if(isset($address_id) && $address_id!= null)
            {
                $model = UserAddress::findOne($address_id);
                $model->full_name = isset($full_name)?$full_name:'';
                $model->mobile_number = isset($mobile_number)?$mobile_number:'';
                $model->country_code = isset($country_code)?$country_code:'';
                $model->house_number = isset($house_number)?$house_number:'';
                $model->estate = isset($estate)?$estate:'';
                $model->area = isset($area)?$area:'';
                $model->landmark = isset($landmark)?$landmark:'';
                $model->address = isset($address)?$address:'';
                $model->zipcode = isset($zipcode)?$zipcode:'';
                // $model->is_default = 'N';
                $model->latitude = isset($latitude)?$latitude:'';
                $model->longitude = isset($longitude)?$longitude:'';
                $model->u_by = yii::$app->user->id;
                $model->u_date = time();

                if($model->is_default == 'N' && $is_default == 'Y'){
                    $addressIds = ArrayHelper::map(UserAddress::find()->where(['user_id'=>yii::$app->user->id,'is_deleted'=>'N'])->all(), 'id','id');
                 UserAddress::updateAll(['is_default' =>'N'], ['id' => $addressIds]);
                 $model->is_default = 'Y';
                }
                //now save record in database
                if($model->save(false)){

                        return Yii::$app->apifunction->setResponse('address_update_successfully',true,200,200);
                    }
            }else{
                $model = new UserAddress();
                $model->full_name = isset($full_name)?$full_name:'';
                $model->user_id = yii::$app->user->id;
                $model->mobile_number = isset($mobile_number)?$mobile_number:'';
                $model->country_code = isset($country_code)?$country_code:'';
                $model->house_number = isset($house_number)?$house_number:'';
                $model->estate = isset($estate)?$estate:'';
                $model->area = isset($area)?$area:'';
                $model->landmark = isset($landmark)?$landmark:'';
                $model->address = isset($address)?$address:'';
                $model->zipcode = isset($zipcode)?$zipcode:'';

                if($is_default == 'Y'){
                    $addressIds = ArrayHelper::map(UserAddress::find()->where(['user_id'=>yii::$app->user->id,'is_deleted'=>'N'])->all(), 'id','id');
                 UserAddress::updateAll(['is_default' =>'N'], ['id' => $addressIds]);
                }

                $model->is_default = isset($is_default)?$is_default:'N';
                $model->latitude = isset($latitude)?$latitude:'';
                $model->longitude = isset($longitude)?$longitude:'';
                $model->i_by = yii::$app->user->id;
                $model->i_date = time();


                //Here i Have to make other address un_default when is_default comes 'Y"

                if($model->save(false)){
                    return Yii::$app->apifunction->setResponse('address_update_successfully',true,200,200);
                }
            }

        }else{
            return Yii::$app->apifunction->setResponse('response_text',false,400,400);
        }
      }//AddEdtiAddress end here

      public function actionAddresslist()
      {
          $required_objs = [];
          Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);

          extract($_POST);
          //check if user exist or not
          //$data = Yii::$app->apifunction->getUserDetailOnEmail($email,'u');

          $addresses = UserAddress::find()->where(['user_id'=>yii::$app->user->id,'is_deleted'=>'N']);


              $start = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0  ;
              $limit  = isset($_REQUEST['limit'])  ? $_REQUEST['limit']+1  : 11 ;
              $addresses = $addresses->offset($start)->limit($limit);


            $addresses = $addresses->all();

              if(isset($addresses) && $addresses!=array())
              {
                  $i = 0;
                  foreach($addresses as $key => $address){

                      $result['address_list'][$i]['id'] = $address->id;
                      $result['address_list'][$i]['full_name'] = $address->full_name?$address->full_name:'';
                      $result['address_list'][$i]['mobile_number'] = $address->mobile_number?$address->mobile_number:'';
                      $result['address_list'][$i]['country_code'] = $address->country_code?$address->country_code:'';
                      $result['address_list'][$i]['house_number'] = $address->house_number?$address->house_number:'';
                      $result['address_list'][$i]['estate'] = $address->estate?$address->estate:'';
                      $result['address_list'][$i]['area'] = $address->area?$address->area:'';
                      $result['address_list'][$i]['landmark'] = $address->landmark?$address->landmark:'';
                      $str = '';

                      if($address->landmark)
                          $str .= ', '.$address->landmark.',';

                      if($address->area != '' )
                          $str .= ' '.$address->area.',';

                      if($address->estate)
                          $str .= ' '.$address->estate.',';

                      if($address->house_number)
                          $str .= ' '.$address->house_number.',';


                      if($address->zipcode)
                          $str .= ' '.$address->zipcode.'.';

                      $result['address_list'][$i]['address'] = $address->address?$address->address:'';
                      $result['address_list'][$i]['formated_address'] = $address->address?$address->address.$str:'';
                      $result['address_list'][$i]['zipcode'] = $address->zipcode?$address->zipcode:'';
                      $result['address_list'][$i]['is_default'] = $address->is_default?$address->is_default:'';
                      $result['address_list'][$i]['i_date'] = $address->i_date;
                      $result['address_list'][$i]['u_date'] = $address->u_date?$address->u_date:'';
                      $result['address_list'][$i]['latitude'] = $address->latitude?$address->latitude:'';
                      $result['address_list'][$i]['longitude'] = $address->longitude?$address->longitude:'';
                      $i++;
                    }
                    $result['is_last'] ='Y';
                    if($i >= $limit){
                        unset($result['address_list'][$i-1]);
                        $result['is_last'] ='N';
                    }
                    return Yii::$app->apifunction->setResponse('address_list',true,200,200,$result);

                }else
                {
                    $result['address_list'] = [];
                  return Yii::$app->apifunction->setResponse('error_address_list_not_found',false,200,400,$result);
              }
      }//Address list end here



      public function actionDeleteaccount(){

            $this->layout=false;
            /*insert all required veriables*/
            $required_objs = [];

            //check user is guest or not
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);


            extract($_POST);
            $userid = Yii::$app->user->id;
            $model = Users::findOne($userid);
            if(isset($model) && $model!=array())
            {

                    $model->is_deleted = 'Y';

                //now save record in database
                if($model->save(false)){
                        return Yii::$app->apifunction->setResponse('account_deleted',true,200,200);
                    }


            }else{
                return Yii::$app->apifunction->setResponse('error_user_not_found',false,200,400);
            }
      }//delete account  end here

    public function actionBrandlist(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = [];

        //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
        extract($_POST);

        //Lets first get the all brand list
        $brand = Brand::find()->where(['is_deleted'=>'N']);

        if(isset($search_text) && $search_text !=null)
            $brand->andFilterWhere([
                'OR',
                ['like', 'brand_name', trim($search_text)]
            ]);

        $start = isset($start) ? $start : 0  ;
        $limit  = isset($limit)  ? $limit+1  : 11 ;
        // $brand = $brand->offset($start)->limit($limit);

        $brand = $brand->all();

        if($brand){
          $i=0;

          foreach ($brand as $key => $value) {
          $result['brand_list'][$i]['id']    = $value->id;
          $result['brand_list'][$i]['brand_name']  = $value->brand_name?$value->brand_name:'';
          $result['brand_list'][$i]['brand_image'] = $value->brand_image?Url::to('@web/'.$value->brand_image,true):'';
          $i++;
          }

          $result['is_last'] ='Y';

          if(isset($_REQUEST['limit']) && $_REQUEST['limit'] !=null){
                if($i >= $limit){
                    unset($result['brand_list'][$i-1]);
                    $result['is_last'] ='N';
                }
              }
          return Yii::$app->apifunction->setResponse('success_brand_list',true,200,200,$result);

        }else{
            $result['brand_list'] = [];
            return Yii::$app->apifunction->setResponse('error_no_brand_list',true,200,200,$result);
        }
  }//Brand list end here


  public function actionPurchaselist(){

            $this->layout=false;
            /*insert all required veriables*/
            $required_objs = ['new_purchase_type'];
            if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
            {
            //check user is guest or not
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
            extract($_POST);

            $stocks = Product::find()->alias('P')->where(['P.product_type'=>$new_purchase_type,'P.is_active'=>'Y','P.is_deleted'=>'N']);
            if(isset($brand_id) && $brand_id != null)
                $stocks = $stocks->joinWith('brand')->andwhere(['B.id'=>explode(',',$brand_id)]);
            else $stocks = $stocks->joinWith('brand');



            $start = isset($start) ? $start : 0  ;
            $limit  = isset($limit)  ? $limit+1  : 11 ;
            $stocks = $stocks->offset($start)->limit($limit);

            $stocks = $stocks->orderBy('id DESC')->all();

            // echo "<pre>";
            // die(print_r($stocks));

            if($stocks){
                $i=0;
                foreach ($stocks as $key => $value) {
                $result['purchase_list'][$i]['id']    = (int)$value->id;
                $result['purchase_list'][$i]['discount_price']    = number_format($value->price -  (($value->price*$value->discount/100)),2);
                // $result['purchase_list'][$i]['discount_price']    = round($value->price -  (($value->price*$value->discount/100)),2);
                $result['purchase_list'][$i]['discount']    = $value->discount?$value->discount:"0";
                $result['purchase_list'][$i]['title'] = $value->title;
                $result['purchase_list'][$i]['product_id'] = $value->id;
                $result['purchase_list'][$i]['brand_id'] = $value->brand_id;
                $result['purchase_list'][$i]['size_id'] = $value->size_id?$value->size_id:'';
                $result['purchase_list'][$i]['size'] = $value->size;
                $result['purchase_list'][$i]['size_image'] = '';
                $result['purchase_list'][$i]['price'] = number_format($value->price,2) ;

                /**
                 * From here I have to find multiple brand names and brand images
                 */
                $result['purchase_list'][$i]['brand_name'] = "";
                $result['purchase_list'][$i]['brand_image'] = "";
                if(isset($value->brand) && $value->brand!= null){
                $result['purchase_list'][$i]['brand_name'] = $value->brand->brand_name?$value->brand->brand_name:'';
                $result['purchase_list'][$i]['brand_image'] = $value->brand->brand_image?Url::to('@web/'.$value->brand->brand_image,true):'';
                }
                $i++;
                }

                $result['is_last'] ='Y';

                if(isset($_REQUEST['limit']) && $_REQUEST['limit'] !=null){
                        if($i >= $limit){
                            unset($result['purchase_list'][$i-1]);
                            $result['is_last'] ='N';
                        }
                    }
                return Yii::$app->apifunction->setResponse('success_purchase_list',true,200,200,$result);

            }else{
                    $result['purchase_list'] = [];
                    return Yii::$app->apifunction->setResponse('error_no_purchase_list',true,200,200,$result);
                }
            }else{
                return Yii::$app->apifunction->setResponse('response_text',false,400,400);
            }
    }//Purchase list end here

    public function actionNotificationlist(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = [];

        //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
        extract($_POST);

        $notification = Notification::find()->where(['type'=>['U','A']])->all();

        $userId = yii::$app->user->id;

      //Now based on UserId check the reciver ids,if found then store its id(notification)
      $notification_ids = array();
      foreach ($notification as $key => $value) {
        $reciver_ids = explode(',', $value->to_user);
        $deleted_ids = explode(',', $value->deleted_by);
        if(in_array($userId,$reciver_ids) && !in_array($userId,$deleted_ids))
              $notification_ids[] = $value->id;
      }
       //Now get those ids data
       $notification = Notification::find()->where(['id'=>$notification_ids]);

       $start = isset($start) ? $start : 0  ;
       $limit  = isset($limit)  ? $limit+1  : 11 ;
       $notification = $notification->offset($start)->limit($limit);


       $notification = $notification->orderBy('id DESC')->all();


        if($notification){
            $i = 0;
        foreach ($notification as $key => $value) {

        $result['notification_list'][$i]['id'] = $value->id;
        $result['notification_list'][$i]['message']  = $value->message?$value->message:'';
        $result['notification_list'][$i]['type'] = $value->notification_type;
        $result['notification_list'][$i]['order_id'] = $value->order_id?$value->order_id:'';
        $result['notification_list'][$i]['timestamp'] = $value->i_datetime;
        $i++;
        }

        $result['is_last'] ='Y';

        if($i >= $limit){
            unset($result['notifications'][$i-1]);
            $result['is_last'] ='N';
        }
        return Yii::$app->apifunction->setResponse('success_notification_list',true,200,200,$result);

        }else{
            $result['notification_list'] = [];
        return Yii::$app->apifunction->setResponse('error_no_notificatin_not_found',true,200,200,$result);
        }
    }//Notification list end here


    public function actionClearnotificationlist(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = [];

        //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
        extract($_POST);

        //Lets first get the all notification list

        $notification = Notification::find()->where(['type'=>['U','A']])->all();

        $userId = yii::$app->user->id;
        $userid[] = $userId;

        //Now based on UserId check the reciver ids,if found then store its id(notification)
        $notification_ids = array();
        foreach ($notification as $key => $value)
        {
            $reciver_ids = explode(',', $value->to_user);
            $deleted_ids = explode(',', $value->deleted_by);
            $deleted_id = explode(',', $value->deleted_by);
            if(in_array($userId,$reciver_ids) && !in_array($userId,$deleted_ids))
                $notification_ids[] = $value->id;
        }

        //Now get those ids data
        $notification = Notification::find()->where(['id'=>$notification_ids])->all();
        if(!$notification)
        {
            return Yii::$app->apifunction->setResponse('allready_clear_notification',false,200,400);
        }
        else
        {
            foreach ($notification as $key => $value)
            {

                $deletedid =  array_merge($deleted_id,$userid);
                $value->deleted_by =implode(',',$deletedid);
                $value->save(false);
            }
            return Yii::$app->apifunction->setResponse('clear_notification',true,200,200);
        }

    }//Clear notification end here

    public function actionCancelorder(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = ['order_id'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {
            //check user is guest or not
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);

            extract($_POST);
            $userId = yii::$app->user->id;

            $order_log = Orderlog::find()->where(['order_id'=>$order_id,'status'=>'8'])->one();
            if($order_log){
                return Yii::$app->apifunction->setResponse('allready_cancel',false,200,400);
            }

            /**
             * Check if rider pass the request no ther rider avilable then dont send to him
             */


            $order = Order::find()->where(['id'=>$order_id])->one();
            if(!$order){
                return Yii::$app->apifunction->setResponse('error_order_not_found',false,200,400);
            }
            $order->status='8';
            if(!empty($reason_id)){
            $reason = Reason::find()->where(['id'=>$reason_id])->one();
            $order->cancellation_reason = $reason->reason;
            }elseif(!empty($other_reason)){
                $order->cancellation_reason = $other_reason;
            }

            if($order->save(false))
            {

            /**
             * Make is_request_recieve == N
             */
            $request_recieve = Users::findOne($order->rider_id);
            if($request_recieve){
                    $request_recieve->is_request_recieve = 'N';
                    $request_recieve->save(false);
            }

                /** Chnage order detail status too for this order*/
              OrderDetail::updateAll(['status' =>8], ['order_id' => $order->id]);
              /**
               * If above code not work then do below code
               */
              $order_details_status = OrderDetail::find()->where(['order_id'=>$order_id])->all();
              foreach($order_details_status as $value){
                $value->status = 8;
                $value->save(false);
              }

              /**
               * Bring the vendor products count in it actula state
               */

              $order_details = OrderDetail::find()->where(['order_id'=>$order->id])->all();
              foreach($order_details as $details){
                  $stock = Stock::find()->where(['user_id'=>$order->vendor_id,'product_id'=>$details->product_id])->one();
                  $stock->quantity = $stock->quantity + $details->quantity;
                  $stock->sold_out = $stock->sold_out - $details->quantity;
                  $stock->save(false);
              }


        /**
         * Make rider available for next ride
         */
            $rider_available = Users::findOne($order->rider_id);
            if($rider_available){
            $rider_available->is_available='Y';
            $rider_available->save(false);
            }

           /**
            * send cancel notification to user as well as his vendor notification
            */


            $can_charge = Setting::find()->where(['key'=>'cancel_fee'])->one();
                if($can_charge){
                    $cancelation_charge = $can_charge->value;
                }else{
                    $cancelation_charge = 100;
                }

            $tmp_order_log = Orderlog::find()->where(['order_id'=>$order_id,'status'=>'2'])->one();

            if($tmp_order_log!= null && $tmp_order_log->i_by != $order->rider_id ){


              $noti = new Notification;
              $noti->from_user = Yii::$app->user->id;
              $noti->order_id = $order_id;

              $both_ids[] = $order->rider_id;
              $both_ids[] = $order->vendor_id;

              $noti->to_user = implode(',',$both_ids);

              $noti->notification_type = 'cancel_status_user';
              $noti->message = 'Order cancelled by the user';
              $noti->type = 'A';

              $noti->i_by = Yii::$app->user->id;
              $noti->i_date = date('Y-m-d H:i:s');
              $noti->i_datetime = time();
              $noti->save(false);

              $body_a=array();
              $body_a['data']['notification_type'] = 'cancel_status_user';
              $body_a['data']['order_id'] = $order->id;
              $body_a['data']['status'] = '8';
              $body_a['data']['master_id'] = $order->id;
              $body_a['data']['message'] = 'Order cancelled by the user';
              $body_a['data']['message2'] = "User has cancelled an order due to you have not cancel from your end, so fee KSH $cancelation_charge applicable in the next order";
              $body_a['data']['message3'] = "You have cancelled an order, so fee KSH $cancelation_charge applicable in the next order";

              $body_i=array();
              $body_i['data'] = array('alert' =>'Order cancelled by the user');
              $body_i['data']['badge'] = 1;
              $body_i['data']['order_id'] = $order->id;
              $body_i['data']['master_id'] = $order->id;
              $body_i['data']['status'] = '8';
              $body_i['data']['notification_type'] = 'cancel_status_user';
              $body_i['data']['sound'] = 'RequestNotification.wav';
              $body_i['data']['message'] = 'Order cancelled by the user';
              $body_i['data']['message2'] = "User has cancelled an order due to you have not cancel from your end, so fee KSH $cancelation_charge applicable in the next order";
              $body_i['data']['message3'] = "You have cancelled an order, so fee KSH $cancelation_charge applicable in the next order";
              $body_i['data']['alert'] = 'Order cancelled by the user';
              $body_i['data']['text'] = 'Order cancelled by the user';


              $user = Users::find()->where(['is_deleted'=>"N",'is_active'=>"Y",'notification_enabled'=>'Y','id'=>$both_ids])->select(['id','is_deleted','is_active','user_type','notification_enabled','is_online'])->all();
              $device_token_android=$device_token_iphone=array();
                $ij=$mn=0;
                if(!empty($user)){
                    foreach ($user as $u) {

                        $uDeviceDetail = Userdevices::find()->where(['user_id'=>$u->id])->orderby("last_login_datetime DESC")->one();

                            if(isset($uDeviceDetail->device_id) && $uDeviceDetail->device_id!=null && isset($uDeviceDetail->device_type) && $uDeviceDetail->device_type!=null)
                            {
                                if($uDeviceDetail->device_type=='a'|| $uDeviceDetail->device_type=='A')
                                {
                                    if(isset($device_token_android[$ij]) && count($device_token_android[$ij]) == 500)
                                        $ij++;
                                    $device_token_android[$ij][$u->id] = $uDeviceDetail->device_id;
                                }
                                if($uDeviceDetail->device_type=='i'|| $uDeviceDetail->device_type=='I')
                                {
                                    if(isset($device_token_iphone[$mn]) && count($device_token_iphone[$mn]) == 500)
                                        $mn++;
                                    $device_token_iphone[$mn][$u->id] = $uDeviceDetail->device_id;
                                }
                            }
                    }
                }

            if($device_token_android != array())
                Yii::$app->mycomponent->pushnotification_android_array($device_token_android,$body_a);

            if($device_token_iphone != array())
                Yii::$app->mycomponent->pushnotification_iphone_array($device_token_iphone,$body_i);

            }else{
                $noti = new Notification;
                $noti->from_user = Yii::$app->user->id;
                $noti->order_id = $order_id;

                $both_ids[] = $order->rider_id;
                $both_ids[] = $order->vendor_id;

                $noti->to_user = implode(',',$both_ids);

                $noti->notification_type = 'cancel_status_user';
                $noti->message = 'Order cancelled by the user';
                $noti->type = 'A';

                $noti->i_by = Yii::$app->user->id;
                $noti->i_date = date('Y-m-d H:i:s');
                $noti->i_datetime = time();
                $noti->save(false);

                $body_a=array();
                $body_a['data']['notification_type'] = 'cancel_status_user';
                $body_a['data']['order_id'] = $order->id;
                $body_a['data']['status'] = '8';
                $body_a['data']['master_id'] = $order->id;
                $body_a['data']['message'] = 'Order cancelled by the user';
                $body_a['data']['message2'] = "User has cancelled an order due to you have not cancel from your end, so fee KSH $cancelation_charge applicable in the next order";
                $body_a['data']['message3'] = "You have cancelled an order, so fee KSH $cancelation_charge applicable in the next order";

                $body_i=array();
                $body_i['data'] = array('alert' =>'Order cancelled by the user');
                $body_i['data']['badge'] = 1;
                $body_i['data']['order_id'] = $order->id;
                $body_i['data']['master_id'] = $order->id;
                $body_i['data']['status'] = '8';
                $body_i['data']['notification_type'] = 'cancel_status_user';
                $body_i['data']['sound'] = 'default';
                $body_i['data']['message'] = 'Order cancelled by the user';
                $body_i['data']['message2'] = "User has cancelled an order due to you have not cancel from your end, so fee KSH $cancelation_charge applicable in the next order";
                $body_i['data']['message3'] = "You have cancelled an order, so fee KSH $cancelation_charge applicable in the next order";
                $body_i['data']['alert'] = 'Order cancelled by the user';
                $body_i['data']['text'] = 'Order cancelled by the user';


                $user = Users::find()->where(['is_deleted'=>"N",'is_active'=>"Y",'notification_enabled'=>'Y','id'=>$both_ids])->select(['id','is_deleted','is_active','user_type','notification_enabled','is_online'])->all();
                $device_token_android=$device_token_iphone=array();
                  $ij=$mn=0;
                  if(!empty($user)){
                      foreach ($user as $u) {

                          $uDeviceDetail = Userdevices::find()->where(['user_id'=>$u->id])->orderby("last_login_datetime DESC")->one();

                              if(isset($uDeviceDetail->device_id) && $uDeviceDetail->device_id!=null && isset($uDeviceDetail->device_type) && $uDeviceDetail->device_type!=null)
                              {
                                  if($uDeviceDetail->device_type=='a'|| $uDeviceDetail->device_type=='A')
                                  {
                                      if(isset($device_token_android[$ij]) && count($device_token_android[$ij]) == 500)
                                          $ij++;
                                      $device_token_android[$ij][$u->id] = $uDeviceDetail->device_id;
                                  }
                                  if($uDeviceDetail->device_type=='i'|| $uDeviceDetail->device_type=='I')
                                  {
                                      if(isset($device_token_iphone[$mn]) && count($device_token_iphone[$mn]) == 500)
                                          $mn++;
                                      $device_token_iphone[$mn][$u->id] = $uDeviceDetail->device_id;
                                  }
                              }
                      }
                  }

              if($device_token_android != array())
                  Yii::$app->mycomponent->pushnotification_android_array($device_token_android,$body_a);

              if($device_token_iphone != array())
                  Yii::$app->mycomponent->pushnotification_iphone_array($device_token_iphone,$body_i);

            }

            $log = new Orderlog;
            $log->order_id=$order->id;
            $log->status=8;
            $log->i_by=$userId;
            $log->is_read= 'Y';
            $log->cancelation_charge = 'Y';
            $log->i_date=time();
            $log->save(false);
            return Yii::$app->apifunction->setResponse('order_canceled',true,200,200);
            }
        }else{
            return Yii::$app->apifunction->setResponse('response_text',false,400,400);
        }
    }//cancel order end here


    public function actionRating(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = ['rate','rider_id','order_id'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST)){
        //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);

        extract($_POST);
        $userId = yii::$app->user->id;

        $review = new Review;
        $review->from_id=$userId;
        $review->order_id=$order_id;
        $review->to_id=$rider_id;
        $review->rating=$rate;
        if(isset($comment) && $comment!=null)
        {
          $review->review=$comment;
        }

        $review->i_by=$userId;
        $review->i_date=date("Y-m-d H:i:s");

        if($review->save(false))
        {
          $rider_sum=Review::find()->where(['to_id'=>$rider_id,'is_deleted'=>'N'])->sum('rating');
          $rider_cnt=Review::find()->where(['to_id'=>$rider_id,'is_deleted'=>'N'])->count();

          $rider=Users::findOne($rider_id);
          $rider->rating= ($rider_sum/$rider_cnt);
          $rider->save(false);

          return Yii::$app->apifunction->setResponse('thanks_feedback',true,200,200);
        }else{
          return Yii::$app->apifunction->setResponse('error_in_save',false,400,400);
        }
        }else{
          return Yii::$app->apifunction->setResponse('response_text',false,400,400);
        }

    }//Rating done here

    public function actionAddtocart(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = ['is_refilling'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST)){
        //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);

        extract($_POST);
        $userId = yii::$app->user->id;


        // Currently, selected cylinder size is not available

        //Without brand
        if($is_refilling == 'N'){
        if(isset($size_id) && $size_id !=null){
            $product = Product::find()->where(['size_id'=>$size_id,'size'=>isset($cylinder_size)?$cylinder_size:null])->andWhere(['is_active'=>'Y'])->one();
            if(!$product){
            return Yii::$app->apifunction->setResponse('error_in_size',false,400,400);

            }
        }
    }

        if((isset($size_id) && $size_id !=null) && (isset($brand_id) && $brand_id !=null)){
            $product = Product::find()->where(['size_id'=>$size_id,'product_type'=>'R','brand_id'=>$brand_id,'is_active'=>'Y','size'=>isset($cylinder_size)?$cylinder_size:null])->andWhere(['is_active'=>'Y','is_deleted'=>'N'])->one();
            if(!$product){
            return Yii::$app->apifunction->setResponse('error_in_brand_with_this_size',false,400,400);

            }
        }


        $cart = new Cart;
        $cart->user_id    =$userId;
        $cart->product_id = isset($product_id)?$product_id:null;
        // $cart->brand_id   = isset($brand_id)?$brand_id:null;
        $cart->size_id  = isset($size_id)?$size_id:null;
        $cart->quantity   = isset($quantity)?$quantity:1;
        $cart->is_refilling= $is_refilling;
        $cart->cylinder_size= isset($cylinder_size)?$cylinder_size:null;
        $cart->i_by   = $userId;
        $cart->i_date = time();

        if($cart->save(false))
        {
          return Yii::$app->apifunction->setResponse('success_cart_added',true,200,200);
        }else{
          return Yii::$app->apifunction->setResponse('error_in_save',false,400,400);
        }
        }else{
          return Yii::$app->apifunction->setResponse('response_text',false,400,400);
        }

    }//Rating done here

    public function actionCartlist(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = [];

        //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
        extract($_POST);

       //Now get those ids data
       $carts = Cart::find()->where(['user_id'=>yii::$app->user->id,'is_deleted'=>'N','is_active'=>'Y','is_buy'=>'N']);

       $start = isset($start) ? $start : 0  ;
       $limit  = isset($limit)  ? $limit+1  : 11 ;
       $carts = $carts->offset($start)->limit($limit);

       $carts = $carts->orderBy('id DESC')->all();


        if($carts){
            $i = 0;
        foreach ($carts as $key => $value) {
        $result['cart_item_list'][$i]['id'] = $value->id;

        $title = '';
        $image = '';
        $type = '';
        $brand_name = '';
        $price = 0;
        $discount = 0;

         if($value->product_id!=null){
            $product = Product::find()->select(['id','title','product_type','price','is_deleted','brand_id','discount'])->where(['id'=>$value->product_id,'is_deleted'=>'N','is_active'=>'Y'])->one();
            if($value->brand_id != null){
                $product = Product::find()->select(['id','title','product_type','price','is_deleted','brand_id','discount'])->where(['id'=>$value->product_id,'is_deleted'=>'N','brand_id'=>$value->brand_id,'is_active'=>'Y'])->one();
            }
            if($product){
            $title = $product->title;
            $brand_name_image = Brand::find()->where(['id'=>$product->brand_id])->one();
            $image = $brand_name_image->brand_image;
            $brand_name = $brand_name_image->brand_name;
            $type  = $product->product_type;
            $price = $product->price;
            $discount = $product->discount;
            }
        // }
        // elseif($value->brand_id!=null){
        //     $brand = Brand::find()->select(['id','brand_name','brand_image'])->where(['id'=>$value->brand_id])->one();
        //     if($brand){
        //     $title = $brand->brand_name;
        //     $image = $brand->brand_image;
        //     }
         }elseif($value->size_id!=null){
            //  print_r($value->size_id);die;
            // $stock = Stock::findOne(['size_id'=>$value->size_id]);
            $product = Product::find()->select(['id','title','product_type','price','is_deleted','brand_id','discount'])->where(['size_id'=>$value->size_id,'is_deleted'=>'N','product_type'=>'R','is_active'=>'Y'])->one();
            
            if($value->brand_id != null){
                $product = Product::find()->select(['id','title','product_type','price','is_deleted','brand_id','discount'])->where(['size_id'=>$value->size_id,'is_deleted'=>'N','product_type'=>'R','brand_id'=>$value->brand_id,'is_active'=>'Y'])->one();
            }
            if($product){
            $title = $product->title;
            $brand_name_image = Brand::find()->where(['id'=>$product->brand_id])->one();
            $image = $brand_name_image->brand_image;
            $brand_name = $brand_name_image->brand_name;
            $type  = $product->product_type;
            $price = $product->price;
            $discount = $product->discount;
            }
         }
         if(empty($product->id)){
            unset($result['cart_item_list'][$i]);
                continue;
         }

        $result['cart_item_list'][$i]['title']  = $title;
        $result['cart_item_list'][$i]['brand_image'] = ($image!='')?Url::to('@web/'.$image,true):'';
        $result['cart_item_list'][$i]['brand_name'] = $brand_name;
        $result['cart_item_list'][$i]['type'] = $type;
        $result['cart_item_list'][$i]['discount_percentage'] = $discount ? $discount : 0 ;
        $result['cart_item_list'][$i]['price'] = number_format($value->quantity*$price,2);
        $result['cart_item_list'][$i]['product_id'] = $product->id;
        $result['cart_item_list'][$i]['discounted_price'] = number_format($value->quantity*round($price -  (($price*$discount/100)),2),2);
        $result['cart_item_list'][$i]['quantity'] = $value->quantity;

        $i++;
        }

        $result['is_last'] ='Y';
        if($i >= $limit){
            unset($result['cart_item_list'][$i-1]);
            $result['is_last'] ='N';
        }
        return Yii::$app->apifunction->setResponse('success_carts_list',true,200,200,$result);

        }else{
            $result['cart_item_list'] = [];
        return Yii::$app->apifunction->setResponse('error_no_carts_found',true,200,200,$result);
        }
    }//Cart list end here


    public function actionRemovecart(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = ['item_id'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST)){
        //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);

        extract($_POST);
        $userId = yii::$app->user->id;

        $cart = Cart::find()->where(['id'=>$item_id,'is_deleted'=>'N'])->one();
        if(!$cart){
          return Yii::$app->apifunction->setResponse('error_cart_not_found',false,400,400);
        }
        $cart->is_deleted = 'Y' ;
        $cart->u_by   = $userId;
        $cart->u_date = time();

        if($cart->save(false))
        {
          return Yii::$app->apifunction->setResponse('success_cart_deleted',true,200,200);
        }else{
          return Yii::$app->apifunction->setResponse('error_in_save',false,400,400);
        }
        }else{
          return Yii::$app->apifunction->setResponse('response_text',false,400,400);
        }

    }//Remove cart done here


    public function actionUpdatecart(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = ['cart_id','quantity'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST)){
        //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);

        extract($_POST);
        $userId = yii::$app->user->id;

        $cart = Cart::find()->where(['id'=>$cart_id,'is_deleted'=>'N','is_active'=>'Y','is_buy'=>'N'])->one();
        if(!$cart){
          return Yii::$app->apifunction->setResponse('error_cart_not_found',false,400,400);
        }
        // $cart->quantity = $cart->quantity+$quantity ;
        $cart->quantity = $quantity ;

        /**
         * Check the quantity: Is greater then 10 or not
         */
        if($cart->quantity > 10){
            return Yii::$app->apifunction->setResponse('error_in_quantity',false,400,400);
        }
        $cart->u_by   = $userId;
        $cart->u_date = time();

        if($cart->save(false))
        {
          return Yii::$app->apifunction->setResponse('success_cart_update',true,200,200);
        }else{
          return Yii::$app->apifunction->setResponse('error_in_save',false,400,400);
        }
        }else{
          return Yii::$app->apifunction->setResponse('response_text',false,400,400);
        }

    }//Remove cart done here



    public function actionApplypromocode(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = ['promo_code'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST)){
        //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);

        extract($_POST);
            $promocode = Promocode::find()->where(['promo_code'=>$promo_code,'is_deleted'=>'N','is_active'=>'Y'])
                         ->andwhere(['>=','end_date',time()])->one();


        if($promocode)
        {
            $result['discount'] = $promocode->discount?$promocode->discount:0;
            $result['id'] = $promocode->id;

          return Yii::$app->apifunction->setResponse('promocode_apply_successfully',true,200,200,$result);
        }else{
          return Yii::$app->apifunction->setResponse('promocode_not_valid',false,400,400);
        }
        }else{
          return Yii::$app->apifunction->setResponse('response_text',false,400,400);
        }

    }//Apply promo-code done here

    // public function actionOrderlist(){


    //     $timezone = Setting::find()->where(['key'=>'timezone'])->one()->value;
    //     yii::$app->timeZone = $timezone;

    //     $this->layout=false;
    //     /*insert all required veriables*/
    //     $required_objs = ['type'];
    //     if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST)){

    //     //check user is guest or not
    //     Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
    //     extract($_POST);

    //     //First get all cylinder sizes from size_master table
    //     $sizes = Size::find()->where(['is_deleted'=>'N','is_active'=>'Y'])->all();

    //     if($sizes){
    //         $i = 0;
    //         foreach ($sizes as $key => $value) {
    //             $result['cylinder_size_list'][$i]['id'] = $value->id;
    //             $result['cylinder_size_list'][$i]['size'] = $value->wieght;
    //             $result['cylinder_size_list'][$i]['size_image'] = $value->size_image?Url::to('@web/'.$value->size_image,true):'';
    //             $i++;
    //         }
    //     }else{
    //             $result['cylinder_size_list'] = [];
    //         }

    // //    $order = Order::find()->alias('O')->where(['user_id'=>yii::$app->user->id]);

    //     if(in_array($type,['C','O','R']))
    //         $order = OrderDetail::find()->alias('O')->where(['M.user_id'=>yii::$app->user->id,'O.product_type'=>$type])->andWhere(['NOT',['order_id'=>null]]);
    //         // ->andWhere(['NOT',['O.status'=>['1','3','4']]]);
    //     else
    //         $order = OrderDetail::find()->alias('O')->where(['M.user_id'=>yii::$app->user->id,'O.status'=>['1','3','4']])->andWhere(['NOT',['order_id'=>null]]);

    //    $order = $order->joinwith(['brand','product','order'])->orWhere(["M.status"=>7,"M.is_payment_received"=>'N']);

    //    $start = isset($start) ? $start : 0  ;
    //    $limit  = isset($limit)  ? $limit+1  : 11 ;
    //    $order = $order->offset($start)->limit($limit);

    //    $order = $order->orderBy('id DESC')->all();

    //     if($order){
    //         $i = 0;
    //     foreach ($order as $key => $value) {
    //     $result['order_list'][$i]['order_id'] = $value->id;
    //     $result['order_list'][$i]['master_id'] = $value->order_id;
    //     // $result['order_list'][$i]['order_date']  = $value->i_date;
    //     $result['order_list'][$i]['order_status'] = $value->status;
    //     $result['order_list'][$i]['order_description'] = $value->product->title;
    //     $result['order_list'][$i]['brand_name'] = $value->brand->brand_name;
    //     $result['order_list'][$i]['brand_image'] = $value->brand->brand_image?Url::to('@web/'.$value->brand->brand_image,true):'';
    //     $result['order_list'][$i]['quantity'] = $value->quantity;
    //     $result['order_list'][$i]['total_price'] = number_format($value->total_price,2);
    //     $result['order_list'][$i]['order_date'] = $value->i_date;

    //     $i++;
    //     }

    //     $result['is_last'] ='Y';
    //     if($i >= $limit){
    //         unset($result['order_list'][$i-1]);
    //         $result['is_last'] ='N';
    //     }
    //     return Yii::$app->apifunction->setResponse('success_order_list',true,200,200,$result);

    //     }else{
    //         $result['order_list'] = [];
    //     return Yii::$app->apifunction->setResponse('error_no_order_found',true,200,200,$result);
    //     }
    //     }else{
    //         return Yii::$app->apifunction->setResponse('response_text',false,400,400);
    //     }
    // }//Order list end here


    public function actionOrderlist(){


        $timezone = Setting::find()->where(['key'=>'timezone'])->one()->value;
        yii::$app->timeZone = $timezone;

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = ['type'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST)){

        //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
        extract($_POST);

        //First get all cylinder sizes from size_master table
        $sizes = Size::find()->where(['is_deleted'=>'N','is_active'=>'Y'])->all();

        if($sizes){
            $i = 0;
            foreach ($sizes as $key => $value) {
                $result['cylinder_size_list'][$i]['id'] = $value->id;
                $result['cylinder_size_list'][$i]['size'] = $value->wieght;
                $result['cylinder_size_list'][$i]['size_image'] = $value->size_image?Url::to('@web/'.$value->size_image,true):'';
                $i++;
            }
        }else{
                $result['cylinder_size_list'] = [];
            }

    //    $order = Order::find()->alias('O')->where(['user_id'=>yii::$app->user->id]);

        if(in_array($type,['C','O','R']))
            $order = OrderDetail::find()->alias('O')->where(['M.user_id'=>yii::$app->user->id,'O.product_type'=>$type])->andWhere(['NOT',['order_id'=>null]]);
            // ->andWhere(['NOT',['O.status'=>['1','3','4']]]);
        else
            $order = OrderDetail::find()->alias('O')->where(
                ['O.status'=>['1','3','4'],
                'M.user_id'=>yii::$app->user->id])->andWhere(['NOT',['order_id'=>null]]);

       $order = $order->joinwith(['brand','product','order'])->orWhere(["M.status"=>7,"M.is_payment_received"=>'N','M.user_id'=>yii::$app->user->id]);

       $start = isset($start) ? $start : 0  ;
       $limit  = isset($limit)  ? $limit+1  : 11 ;
       $order = $order->offset($start)->limit($limit);

       $order = $order->orderBy('id DESC')->all();

        if($order){
            $i = 0;
        foreach ($order as $key => $value) {
        $result['order_list'][$i]['order_id'] = $value->id;
        $result['order_list'][$i]['master_id'] = $value->order_id;
        // $result['order_list'][$i]['order_date']  = $value->i_date;
        $result['order_list'][$i]['order_status'] = $value->status;
        $result['order_list'][$i]['order_description'] = $value->product->title;
        $result['order_list'][$i]['brand_name'] = $value->brand->brand_name;
        $result['order_list'][$i]['brand_image'] = $value->brand->brand_image?Url::to('@web/'.$value->brand->brand_image,true):'';
        $result['order_list'][$i]['quantity'] = $value->quantity;
        $result['order_list'][$i]['total_price'] = number_format($value->total_price,2);
        $result['order_list'][$i]['order_date'] = $value->i_date;

        $i++;
        }

        $result['is_last'] ='Y';
        if($i >= $limit){
            unset($result['order_list'][$i-1]);
            $result['is_last'] ='N';
        }
        return Yii::$app->apifunction->setResponse('success_order_list',true,200,200,$result);

        }else{
            $result['order_list'] = [];
        return Yii::$app->apifunction->setResponse('error_no_order_found',true,200,200,$result);
        }
        }else{
            return Yii::$app->apifunction->setResponse('response_text',false,400,400);
        }
    }//Order list end here


    public function actionOrderdetail(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = ['master_id'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST)){

        //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
        extract($_POST);

       $order_master = Order::find()->alias('O')->where(['user_id'=>yii::$app->user->id,'id'=>$master_id])->one();
       if($order_master){
       $result['order_details']['order_id'] = $order_master->id;

       $result['order_details']['order_status'] = $order_master->status;
       $result['message1'] = Yii::t('app', Yii::$app->params['rider_not_available']);
       if( $order_master->status == 9)
       $result['message1'] = "Order cancelled due to \"$order_master->cancellation_reason\"";


       $result['order_details']['order_date'] = $order_master->i_date;
       $result['order_details']['discount_percentage'] = (float)$order_master->product_discount_percentage;
       $result['order_details']['discount'] = number_format($order_master->product_discount_price,2);
       $result['order_details']['sub_total'] = number_format($order_master->base_price,2);
       $result['order_details']['total_price'] = number_format($order_master->total_price,2);
       $result['order_details']['payment_mode'] = $order_master->payment_status;
       $result['order_details']['payment_status'] = $order_master->is_payment_received;
       $result['order_details']['cancelation_charge'] = $order_master->cancellation_fee?$order_master->cancellation_fee:'';
       $result['order_details']['cancellation_reason'] = $order_master->cancellation_reason?$order_master->cancellation_reason:'';
            if($order_master->promocode_id != null){
                $result['order_details']['is_promo'] = 'Y';
                $result['order_details']['promocode_price'] = number_format(($order_master->base_price*$order_master->promocode_discount)/100,2);

            }
            else{
                $result['order_details']['is_promo'] = 'N';
                $result['order_details']['promocode_price'] = '';
            }

       $result['order_details']['total_price'] = number_format($order_master->total_price,2);

       // 'i_by'=>yii::$app->user->id
       $order_log = Orderlog::find()->where(['order_id'=>$master_id,'status'=>'8'])->one();
       if(!$order_log){
        $rider = Users::findOne($order_master->rider_id);

        $result['rider_info']['rider_id'] = $rider->id;
        $result['rider_info']['rider_name'] = $rider->user_name;
        $result['rider_info']['vehicle_number'] = $rider->motor_bike_number;
        $result['rider_info']['latitude'] = $rider->latitude !=''?$rider->latitude:'';
        $result['rider_info']['longitude'] = $rider->longitude !=''?$rider->longitude:'';
        $result['rider_info']['mobile_number'] = $rider->country_code.' '.$rider->mobile_number;
        $result['rider_info']['rider_image'] = $rider->image !='' ?Url::to('@web/'.$rider->image,true):'';
       }else{
       $result['rider_info']['rider_id'] = '';
       $result['rider_info']['rider_name'] = '';
       $result['rider_info']['vehicle_number'] = '';
       $result['rider_info']['latitude'] = '';
       $result['rider_info']['longitude'] = '';
       $result['rider_info']['mobile_number'] = '';
       $result['rider_info']['rider_image'] = '';
       }
       /**
        * Let's cehck this driver is rated for this order
        */
        if(isset($rider) && $rider!=null)
         $rate = UserReview::find()->where(['order_id'=>$order_master->id,'from_id'=>yii::$app->user->id,'to_id'=>$rider->id,'is_deleted'=>'N'])->one();


        if(isset($rate) && $rate != null)
          $result['rider_info']['is_rated'] = 'Y';
        else
          $result['rider_info']['is_rated'] = 'N';

       $address = UserAddress::find()->where(['user_id'=>yii::$app->user->id,'id'=>$order_master->address_id])->one();
       $result['delivery_address']['full_name'] = $address->full_name;

       $str = '';

        if($address->landmark)
            $str .= ', ' .$address->landmark.',';

        if($address->area != '')
            $str .= ' ' .$address->area.',';

        if($address->estate)
            $str .= ' ' .$address->estate.',';

        if($address->house_number)
            $str .= ' ' .$address->house_number.',';


        if($address->zipcode)
            $str .= ' ' .$address->zipcode.'.';

       $result['delivery_address']['address'] = $address->address.$str;
       $result['delivery_address']['mobile_number'] = $address->mobile_number;
       $result['delivery_address']['country_code'] = $address->country_code;
       $result['delivery_address']['latitude'] = $address->latitude;
       $result['delivery_address']['longitude'] = $address->longitude;



       $order = OrderDetail::find()->alias('O')->where(['user_id'=>yii::$app->user->id,'order_id'=>$order_master->id]);

       $order = $order->joinwith(['brand','product']);

       $order = $order->orderBy('id DESC')->all();

        if($order){
            $i = 0;
        foreach ($order as $key => $value) {
        $result['order_list'][$i]['id'] = $value->id;
        // $result['order_list'][$i]['master_id'] = $value->order_id;
        $result['order_list'][$i]['order_status'] = $value->status;
        $result['order_list'][$i]['title'] = $value->product->title;
        $result['order_list'][$i]['discount_percentage'] = $value->product_discount_percentage ? $value->product_discount_percentage : 0 ;

        if(empty($value->product_discount_percentage))
            $discount = 1;
        $result['order_list'][$i]['discounted_price'] = number_format(($value->total_price - $value->product_discount_price),2);

        $result['order_list'][$i]['brand_name'] = $value->brand->brand_name;
        $result['order_list'][$i]['brand_image'] = $value->brand->brand_image?Url::to('@web/'.$value->brand->brand_image,true):'';
        $result['order_list'][$i]['quantity'] = $value->quantity;
        $result['order_list'][$i]['price'] = number_format($value->total_price,2);
        $result['order_list'][$i]['type'] = $value->product_type;
        $i++;
        }

        return Yii::$app->apifunction->setResponse('success_order_detail',true,200,200,$result);

        }}else{
            $result['order_list'] = [];
        return Yii::$app->apifunction->setResponse('error_no_order_found',true,200,200,$result);
        }
        }else{
            return Yii::$app->apifunction->setResponse('response_text',false,400,400);
        }
    }//Order Detail end here


    public function actionDefaultaddress(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = ['address_id'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {
            //check user is guest or not
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);


            extract($_POST);

             $addressIds = ArrayHelper::map(UserAddress::find()->where(['user_id'=>yii::$app->user->id,'is_deleted'=>'N'])->all(), 'id','id');
             UserAddress::updateAll(['is_default' =>'N'], ['id' => $addressIds]);

                $model = UserAddress::findOne($address_id);
                $model->is_default = 'Y';
                $model->u_by = yii::$app->user->id;
                $model->u_date = time();

                //now save record in database
                if($model->save(false)){
                        return Yii::$app->apifunction->setResponse('address_update_successfully',true,200,200);
                    }

        }else{
            return Yii::$app->apifunction->setResponse('response_text',false,400,400);
        }
      }//Default Address end here


      public function actionPrevieworder(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = [];

        //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
        extract($_POST);

       //Now get those ids data
       $carts = Cart::find()->where(['user_id'=>yii::$app->user->id,'is_deleted'=>'N','is_active'=>'Y','is_buy'=>'N']);

       $start = isset($start) ? $start : 0  ;
       $limit  = isset($limit)  ? $limit+1  : 11 ;
       $carts = $carts->offset($start)->limit($limit);

       $carts = $carts->orderBy('id DESC')->all();

        if($carts){
            $i = 0;
            $title = '';
            $image = '';
            $type = '';
            $price = 0;
            $base_price = 0;
            $discount_price = 0;
            $discount = 1;
            $product_ids = [];
        foreach ($carts as $key => $value) {

        $result['preview_list'][$i]['id'] = $value->id;

        if($value->product_id!=null){
            $product = Product::find()->select(['id','title','product_type','price','is_deleted','brand_id','discount'])->where(['id'=>$value->product_id,'is_deleted'=>'N','is_active'=>'Y'])->one();
            if($product){
            $title = $product->title;
            $brand_name_image = Brand::find()->where(['id'=>$product->brand_id])->one();
            $image = $brand_name_image->brand_image;
            $brand_name = $brand_name_image->brand_name;
            $type  = $product->product_type;
            $price = $product->price;
            $discount = $product->discount;
            $product_ids[] =   $product->id;
            }

        }elseif($value->size_id!=null){

            // $stock = Stock::find()->where(['size_id'=>$value->size_id])->one();
            $product = Product::find()->select(['id','title','product_type','price','is_deleted','brand_id','discount'])
            ->where(['size_id'=>$value->size_id,'is_deleted'=>'N','product_type'=>'R','is_active'=>'Y'])->one();
            if($value->brand_id != null){
                $product = Product::find()->select(['id','title','product_type','price','is_deleted','brand_id','discount'])->where(['size_id'=>$value->size_id,'is_deleted'=>'N','product_type'=>'R','brand_id'=>$value->brand_id,'is_active'=>'Y'])->one();
            }
            if($product){
            $title = $product->title;
            $brand_name_image = Brand::find()->where(['id'=>$product->brand_id])->one();
            $image = $brand_name_image->brand_image;
            $brand_name = $brand_name_image->brand_name;
            $type  = $product->product_type;
            $price = $product->price;
            $discount = $product->discount;
            $product_ids[] =   $product->id;
            }
        }
        // elseif($value->size_id!=null && $value->brand_id!=null){

        //     $stock = Stock::find()->where(['size_id'=>$value->size_id])->one();
        //     $product = Product::find()->select(['id','title','product_type','price','is_deleted','brand_id'])->where(['id'=>$stock->product_id,'is_deleted'=>'N'])->one();
        //     if($product){
        //     $title = $product->title;
        //     $image = Brand::find()->where(['id'=>$product->brand_id])->one()->brand_image;
        //     $type  = $product->product_type;
        //     $price = $product->price;
        //     $discount = $product->discount;
        //     }
        // }

        $result['preview_list'][$i]['title']  = $title;
        $result['preview_list'][$i]['brand_image'] = ($image!='')?Url::to('@web/'.$image,true):'';
        $result['preview_list'][$i]['brand_name'] = $brand_name;
        $result['preview_list'][$i]['type'] = $type;

        $result['preview_list'][$i]['discount_percentage'] = $discount ? $discount : 0 ;
        $result['preview_list'][$i]['discounted_price'] = number_format($value->quantity*round($price -  (($price*$discount/100)),2),2);

        $result['preview_list'][$i]['price'] = number_format($value->quantity*$price,2);
        $result['preview_list'][$i]['quantity'] = $value->quantity;


        $base_price = $base_price + $value->quantity*$price;
        $discount_price = $discount_price + ((($value->quantity*$price)*$discount)/100);

        $i++;
        }
        // var_dump($product_ids);die;
        $result['discount'] = (float)round(($discount_price*100)/$base_price,2);
        $result['base_price'] = (float)$base_price;
        $result['discount_price'] = (float)round($discount_price,2);

        /**
         * Find the previous cancel order
         */
        $result['cancelation_charge'] = 0;
        $result['next_charge'] = 0;

        $order_log = Orderlog::find()->where(['i_by'=>yii::$app->user->id,'status'=>'8','cancelation_charge'=>'Y'])->count();
            if($order_log){
                $can_charge = Setting::find()->where(['key'=>'cancel_fee'])->one();
                if($can_charge){
                    // $cancelation_charge = $can_charge->value;
                    if($order_log >= 2)
                        $result['cancelation_charge'] = isset($can_charge->value)?$can_charge->value:0;
                    else
                        $result['cancelation_charge'] = 0;

                    $result['next_charge'] = isset($can_charge->value)?$can_charge->value:0;
                }else{
                    $result['cancelation_charge'] = 0;
                    $result['next_charge'] = 0;
                }
            }


        $address = UserAddress::find()->where(['user_id'=>yii::$app->user->id,'is_default'=>'Y'])->one();
        $result['delivery_address']['full_name'] = (isset($address->full_name) && $address->full_name != null)?$address->full_name:"";

        $str = '';


        if($address->landmark)
            $str .= ', '.$address->landmark.',';

        if($address->area != '')
            $str .= ' '.$address->area.',';

        if($address->estate)
            $str .= ' '.$address->estate.',';

        if($address->house_number)
            $str .= ' '.$address->house_number.',';


        if($address->zipcode)
            $str .= ' '.$address->zipcode.'.';


        $result['delivery_address']['address'] = $address->address.$str;
        $result['delivery_address']['mobile_number'] = (isset($address->mobile_number)&& $address->mobile_number != null)?$address->mobile_number:"";
            $result['delivery_address']['country_code'] = (isset($address->country_code)&& $address->country_code !=null)?$address->country_code:"";


        $result['is_last'] ='Y';
        if($i >= $limit){
            unset($result['preview_list'][$i-1]);
            $result['is_last'] ='N';
        }
        return Yii::$app->apifunction->setResponse('success_preview_list',true,200,200,$result);

        }else{
            $result['preview_list'] = [];
            $result['discount'] = 0;
            $result['base_price'] = 0;
            $result['discount_price'] = 0;
            $result['address'] = '';
        return Yii::$app->apifunction->setResponse('error_no_order_preview_found',true,200,200,$result);
        }
    }//preview order end here


    public function actionPurchaseorder(){

        $this->layout=false;
        /*insert all required veriables*/
        // $required_objs = ['payment_mode'];

        // if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        // {
            //check user is guest or not
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
            extract($_POST);

            /**
             * Find if this user order already in process;so dont allow him/her for next order
             * untill it complete
             */

            $user_order = Order::find()->where(['user_id'=>yii::$app->user->id,'status'=>['3','4']])->one();
            if($user_order){
                return Yii::$app->apifunction->setResponse("You have an ongoing order so you can't place new one until it's complete",false,200,200);
            }
            //Now get those ids data
            $carts = Cart::find()->where(['user_id'=>yii::$app->user->id,'is_deleted'=>'N','is_active'=>'Y','is_buy'=>'N']);

            $start = isset($start) ? $start : 0  ;
            $limit  = isset($limit)  ? $limit+1  : 11 ;
            $carts = $carts->offset($start)->limit($limit);

            $carts = $carts->orderBy('id DESC')->all();

            if($carts){
                $i = 0;
                $title = '';
                $image = '';
                $type = '';
                $price = 0;
                $base_price = 0;
                $discount_price = 0;
                $discount = 1;
                $product_id = null;
                $brand_id = null;
                $total_quantity = 0;
               // $product_type="";
                /**
                 * Bellow line is Creatical
                 *  $product_type = 'R';
                 */

                 $product_type = 'R';
                //for storing order_details ids
                $order_detail_ids = [];

                //for storing cart ids
                $cart_ids = [];

                //for storing product ids and there quantities
                 $product_ids_quantity = [];

            foreach ($carts as $key => $value) {

            $order_detail = new OrderDetail;

            if($value->product_id!=null){
                $product = Product::find()->select(['id','title','product_type','price','is_deleted','brand_id','discount'])->where(['id'=>$value->product_id,'is_deleted'=>'N','is_active'=>'Y'])->one();
                 //die(var_dump( $product->product_type));
                if($product){
                $title = $product->title;
                $image = Brand::find()->where(['id'=>$product->brand_id])->one()->brand_image;
                $type  = $product->product_type;
                $price = $product->price;
                $discount = $product->discount;
                $product_id = $product->id;
                $brand_id = $product->brand_id;

                $product_type = $product->product_type;
                }

            }elseif($value->size_id!=null){

                $product = Product::find()->select(['id','title','product_type','price','is_deleted','brand_id','discount'])->where(['size_id'=>$value->size_id,'is_deleted'=>'N','size'=>$value->cylinder_size,'product_type'=>'R','is_active'=>'Y'])->one();
                if($value->brand_id != null)
                {
                    $product = Product::find()->select(['id','title','product_type','price','is_deleted','brand_id','discount'])->where(['size_id'=>$value->size_id,'is_deleted'=>'N','product_type'=>'R','brand_id'=>$value->brand_id,'is_active'=>'Y'])->one();
                }
                if($product){
                $title = $product->title;
                $image = Brand::find()->where(['id'=>$product->brand_id])->one()->brand_image;
                $type  = $product->product_type;
                $price = $product->price;
                $discount = $product->discount;
                $product_id = $product->id;
                $brand_id = $product->brand_id;
                $product_type = $product->product_type;
                }
            }

            $order_detail->product_id = $product_id;
            $order_detail->brand_id = $brand_id;
            $order_detail->user_id = yii::$app->user->id;
            $order_detail->quantity = $value->quantity;
            $order_detail->unit_price = $price;
            $order_detail->total_price = $value->quantity*$price;
            $order_detail->product_discount_percentage = round($discount, 2);
            $order_detail->product_discount_price = ((($value->quantity*$price)*$discount)/100);
            $order_detail->status = '1';
            $order_detail->i_date = time();
            $order_detail->product_type = $product_type;

            $order_detail->save(false);
            $order_detail_ids[] = $order_detail->id;
            $cart_ids[] = $value->id;

            $product_ids_quantity[$product_id] = $value->quantity;

            $base_price = $base_price + $value->quantity*$price;
            $discount_price = $discount_price + ((($value->quantity*$price)*$discount)/100);
            $total_quantity = $total_quantity + $value->quantity;
            $i++;
            }//Foreach loop end here for order_details

            $address = UserAddress::find()->where(['user_id'=>yii::$app->user->id,'is_default'=>'Y'])->one();

             /**
              * Put one more extar protection for brand id null then get all vendors with same attributes
              */
            //   if($value->brand_id != null){
            //     $product = Product::find()->select(['id','title','product_type','price','is_deleted','brand_id'])->where(['size_id'=>$value->size_id,'is_deleted'=>'N','product_type'=>'R','brand_id'=>$value->brand_id])->one();
            //     if($product){
            //         $stocks = Stock::find()->where(['product_id'=>$product->id])->andWhere(['NOT',['quantity'=>null]])->all();
            //             foreach($stocks as $stock){
            //               $product_ids_quantity[$stock->product_id] = $stock->quantity;
            //             }
            //         }
            //     }
            /** Here we will find the vendor based on lat,long and driver
             * avaibilty and its product stocks
            **/

             //(1) First find the all stock avaibilty
             //(i) First get the stoks based on requirements
            //  print_r($test);die;


            foreach($product_ids_quantity as $pro_id => $qty ){
                $test[] = Stock::find()->where(['product_id'=>$pro_id])
                                     ->andwhere(['>=','quantity',$qty])
                                     ->asArray()
                                     ->all();
            }
            // print_r($test);die;

             //(ii) Now find who is fullfilling the entire requirement
            $final_sort['list'] = [];
            foreach($test as $object)
            {
                foreach($object as $array)
                {
                    if(in_array($array['product_id'],array_keys($product_ids_quantity)))
                    {
                        $final_sort['list'][$array['user_id']][$array['product_id']] = true;
                    }
                }
            }
             // print_r($final_sort);die;
            //(iii) Now check who is success
           $vendor_ids = [];

            foreach($final_sort['list'] as $key => $value)
            {
               if(count($product_ids_quantity) == count($value))

                  $vendor_ids[] = $key;

            }
            // print_r($vendor_ids);die;
             //If no vendor qualify then return stock not available
            if(empty($vendor_ids))
            {
                return Yii::$app->apifunction->setResponse('No nearest vendor found, We are coming to your location soon',false,400,400);
            }

            //(2) Find the vendor based on the nearest location (from user to vendor)
            $sett_dis = Setting::find()->where(['key'=>'distance'])->one();

            if($sett_dis)
            {
                $distance   = $sett_dis->value;
            }
            else $distance = 10; //static distance 10km
        
            // $distance=1;
            $vendors = Users::find()->select("*,(6371 * acos( cos( radians($address->latitude) ) * cos( radians( latitude) ) * cos( radians( longitude
            ) - radians($address->longitude) ) + sin( radians($address->latitude) ) * sin( radians( latitude ) ) ) ) AS distance")
            ->where(['user_type'=>'V','is_deleted'=>'N','is_active'=>'Y','profile_status'=>'A'])
            ->andWhere(['NOT',['latitude'=>null,'longitude'=>null]])
            ->andWhere(['id'=>$vendor_ids])
            ->andHaving("distance < $distance")->orderBy(['distance' => SORT_ASC])->all();

          if(empty($vendors))
          {
            return Yii::$app->apifunction->setResponse('No nearest vendor found, We are coming to your location soon',false,400,400);
          }

            //(3) Find the rider based on the nearest location (from vendor to rider) and also find avaiblity of the rider

            $vendors = ArrayHelper::map($vendors,'latitude','longitude','id');

            /**
             * I think I have to store vendor ids for this order for future purpose
             */

            //  die(var_dump($vendors));


            $history_ids = [];
            foreach($vendors  as $key => $value){
                $history = new Vendorhistory;
                $history->vendor_id = $key;
                $history->i_date = time();
                $history->save(false);
                $history_ids[]=  $history->id;
            }

            // $orders_log = Orderlog::find()->where(['is_read'=>'Y'])->all();

            // foreach($orders_log as $log){
            //    $exclude_ids[] = $log->order_id;
            // }

            // if(isset($exclude_ids) && $exclude_ids!=null){
            //     $new_orders_log = Orderlog::find()->where(['NOT',['order_id'=>$exclude_ids]])->andWhere(['NOT',['status'=>['2','10']]])->all();

            // }

            // if(isset($new_orders_log) && $new_orders_log!=null)
            //     $ids1=ArrayHelper::map($new_orders_log,'i_by','i_by');

            foreach($vendors  as $vendor => $lat_long){
            //(i) Find all riders of the random vendor

            $vendor_lat = array_keys($lat_long)[0];
            $vendor_long = array_values($lat_long)[0];



            // die(var_dump($vendor ,$vendor_lat,$vendor_long));

            //(ii) Here find the nearest rider and exclude those rider which are in order on the way
            $riders = Users::find()->select("*,( 6371 * acos( cos( radians($vendor_lat) ) * cos( radians( latitude) ) * cos( radians( longitude
                            ) - radians($vendor_long) ) + sin( radians($vendor_lat) ) * sin( radians( latitude ) ) ) ) AS distance")
                        ->where(['user_type'=>'R','is_deleted'=>'N','is_active'=>'Y','profile_status'=>'A','notification_enabled'=>'Y','is_available'=>'Y','is_request_recieve'=>'N','is_online'=>'Y','is_connected'=>'Y'])
                        ->andWhere(['vendor_id'=>$vendor])
                        // ->andWhere(['NOT',['id'=>isset($ids1)?$ids1:null]])
                        ->andWhere(['NOT',['latitude'=>null,'longitude'=>null]])
                        ->andHaving("distance < $distance")->orderBy(['distance' => SORT_ASC])->one();

            if(!empty($riders))
                    break;

                    /**
                     * From here i have to also check this rider, is assigned some where
                     * if yes the put continue condition
                     */

            }//foreach end here

            if(empty($riders)){

                // die(var_dump('$ids1',$ids1,'$vendors', $vendors));
                /**
                 * Send one notification to user to notify about rider
                 */
              $noti = new Notification;
              $noti->from_user = Yii::$app->user->id;

              $noti->to_user = Yii::$app->user->id;

              $noti->notification_type = 'no_rider_found';
              $noti->message = Yii::t('app',Yii::$app->params['rider_not_available_for_order']);
              $noti->type = 'U';

              $noti->i_by = Yii::$app->user->id;
              $noti->i_date = date('Y-m-d H:i:s');
              $noti->i_datetime = time();
              $noti->save(false);

              $body_a=array();
              $body_a['data']['notification_type'] = 'no_rider_found';
            //   $body_a['data']['order_id'] = $order->id;
            //   $body_a['data']['master_id'] = $order->id;
              $body_a['data']['message'] = Yii::t('app',Yii::$app->params['rider_not_available_for_order']);

              $body_i=array();
              $body_i['data'] = array('alert' =>Yii::t('app',Yii::$app->params['rider_not_available_for_order']));
              $body_i['data']['badge'] = 1;
            //   $body_i['data']['order_id'] = $order->id;
            //   $body_i['data']['master_id'] = $order->id;
              $body_i['data']['notification_type'] = 'no_rider_found';
              $body_i['data']['sound'] = 'default';
              $body_i['data']['message'] = Yii::t('app',Yii::$app->params['rider_not_available_for_order']);
              $body_i['data']['alert'] = Yii::t('app',Yii::$app->params['rider_not_available_for_order']);
              $body_i['data']['text'] = Yii::t('app',Yii::$app->params['rider_not_available_for_order']);


              $user = Users::find()->where(['is_deleted'=>"N",'is_active'=>"Y",'notification_enabled'=>'Y','id'=> Yii::$app->user->id])->select(['id','is_deleted','is_active','user_type','notification_enabled','is_online'])->all();
              $device_token_android=$device_token_iphone=array();
                $ij=$mn=0;
                if(!empty($user)){
                    foreach ($user as $u) {

                        $uDeviceDetail = Userdevices::find()->where(['user_id'=>$u->id])->orderby("last_login_datetime DESC")->one();

                            if(isset($uDeviceDetail->device_id) && $uDeviceDetail->device_id!=null && isset($uDeviceDetail->device_type) && $uDeviceDetail->device_type!=null)
                            {
                                if($uDeviceDetail->device_type=='a'|| $uDeviceDetail->device_type=='A')
                                {
                                    if(isset($device_token_android[$ij]) && count($device_token_android[$ij]) == 500)
                                        $ij++;
                                    $device_token_android[$ij][$u->id] = $uDeviceDetail->device_id;
                                }
                                if($uDeviceDetail->device_type=='i'|| $uDeviceDetail->device_type=='I')
                                {
                                    if(isset($device_token_iphone[$mn]) && count($device_token_iphone[$mn]) == 500)
                                        $mn++;
                                    $device_token_iphone[$mn][$u->id] = $uDeviceDetail->device_id;
                                }
                            }
                    }
                }

            if($device_token_android != array())
                Yii::$app->mycomponent->pushnotification_android_array($device_token_android,$body_a);

            if($device_token_iphone != array())
                Yii::$app->mycomponent->pushnotification_iphone_array($device_token_iphone,$body_i);

                return Yii::$app->apifunction->setResponse('rider_not_available_for_order',false,400,400);
            }

            $order = new Order;

            $order->user_id = yii::$app->user->id;


            /** Static vendor id(here we will find the vendor based on lat,long and driver
             * avaibilty and its product stocks
             **/

            $order->vendor_id = $riders->vendor_id;

            /**
             * Static rider id (form here we will find the rider baed on its activeness
             * and lat,long.
             *
             *
             * */

            /**
             * This bellow code not need in futur just done for bug solving
            * if rider not enable then return the message rider not available
            */
            // $user = Users::findOne(119);

            // if($user->notification_enabled == 'N'){
            // return Yii::$app->apifunction->setResponse('rider_not_available',false,200,400);

            // }

            $order->rider_id = $riders->id;

            /**
             * Make is_request_recieve == Y
             */
            $request_recieve = Users::findOne($riders->id);
            if($request_recieve){
                    $request_recieve->is_request_recieve = 'Y';
                    $request_recieve->save(false);
            }

            $order->promocode_id = isset($promocode_id)?$promocode_id:null;
            $order->promocode_discount = isset($promocode_discount)?$promocode_discount:0;
            $order->address_id = $address->id;
            $order->product_discount_percentage =  round(($discount_price*100)/$base_price,2);
            $order->product_discount_price = $discount_price;
            $order->base_price = $base_price;
            $order->total_quantity = $total_quantity;
            $order->status = '1';
            $order->admin_receive = '';
            $order->rider_receive = '';
            $order->vendor_receive = '';

            /**
             * Find the previous cancel order
             */
            $order_log = Orderlog::find()->where(['i_by'=>yii::$app->user->id,'status'=>'8','cancelation_charge'=>'Y'])->count();
            if($order_log >= 2){
                $can_charge = Setting::find()->where(['key'=>'cancel_fee'])->one();
                if($can_charge){
                    $cancelation_charge = $can_charge->value;
                }
            }else{
                $cancelation_charge = 0;
            }

            $order->cancellation_fee = $cancelation_charge;
            /**
             * Bellow payment status is static; it will be come from app side
             */
            $order->payment_status = 'C';

            /**
             * Below perfect for online
             */
            if(isset($payment_mode) && $payment_mode != null)
                  $order->payment_status = $payment_mode;

            $order->i_date = time();
            $order->u_date = time();

            $promo_code_price =  (float)(($base_price*$order->promocode_discount)/100);
            $order->total_price = $base_price-($promo_code_price+$order->product_discount_price)+$cancelation_charge;
            /**
             * Here I have to save timer 50 sec for rider after that it will cancel autometacilly
             */

            // die(var_dump( ($order->total_price) ));

            $order->timer = time()+51 ;
            $order->save(false);


            /**
             * Here I will store the odrer status in order_log
             *
             */
            $order_log = new Orderlog;
            $order_log->order_id = $order->id;
            $order_log->status   = $order->status;
            $order_log->i_by     = $order->rider_id;
            $order_log->i_date   = $order->i_date;
            $order_log->save(false);


            /**
             * Here I have to decrement the vendor products count
             * i.e $order->vendor_id
             */


            /**
             * Here I have to increment rider number_of_orders
             * i.e $order->rider_id
             */
            // $rider = Users::findOne($order->rider_id);
            // $rider->number_of_orders = $rider->number_of_orders +1;
            // $rider->save(false);


            //Now here I have to save this master_order_id into orders details and history
            OrderDetail::updateAll(['order_id' =>$order->id], ['id' => $order_detail_ids]);
            // OrderDetail::updateAll(['order_id' =>$order->id,'vendorId'=>$order->vendor_id], ['id' => $order_detail_ids]);
            Vendorhistory::updateAll(['order_id' =>$order->id], ['id' => $history_ids]);


            //Now Clear the cart List;
            Cart::updateAll(['is_buy' =>'Y'], ['id' => $cart_ids]);
                $result['order_id'] =  $order->id;


            //Finally send notificatioin to Rider for new order
            /**
             * Here I have to create notification for rider in notification master
             */
            yii::$app->mycomponent->newOrderNotification($order);
            // die(var_dump(yii::$app->mycomponent->newOrderNotification($order)));

            return Yii::$app->apifunction->setResponse('success_place_order',true,200,200,$result);

            }else{

            return Yii::$app->apifunction->setResponse('error_place_order',true,200,200);
            }
        // }else{
        //     return Yii::$app->apifunction->setResponse('response_text',false,400,400);
        // }
    }//preview order end here


    /**
     * Make for ipay sending request
     */

    public function actionIpayprocessing(){

        $required_objs = ['order_id'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {
            //check user is guest or not
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);

            $user = Users::findOne(yii::$app->user->id);

            extract($_POST);
            /**
             * From order id find require information
             */
            $order = Order::find()->alias('O')->where(['O.id'=>$order_id,'O.user_id'=>$user->id])->joinwith('add')->one();

            if($order){

            $oid = $order->id;
            $amount = $order->total_price;
             /**
               * And here I to check previose order is_cancel the reduct the define price
               * which will be come from magical space :) or may be from tabel which is
               * not desighn yet
               */
            // $mobile = $order->add->country_code.' '.$order->add->mobile_number;
            $mobile = '0'.$order->add->mobile_number;
            $email = $user->email;

            $url = Yii::$app->common->Ipay($oid,$amount,$mobile,$email);
            if($url != ''){
                $result['url'] = $url;

                return Yii::$app->apifunction->setResponse('Payment url',true,200,200,$result);
            }else{
                return Yii::$app->apifunction->setResponse('Url not found',false,400,400);
            }
            }else{
                return Yii::$app->apifunction->setResponse('Order not found',false,400,400);
            }


        }else{

            return Yii::$app->apifunction->setResponse('response_text',false,200,400);
        }
    }

    public function actionIpayresponse(){

        if(isset($_REQUEST['status']) && $_REQUEST['status']){
            if('aei7p7yrx4ae34' == $_REQUEST['status'] ){
                $result['is_done'] = true;
                /**
                 * In all condition I have to process the order data which is comming in p1 as a order_id
                 *
                 */
            if(isset($_REQUEST['p1']) && $_REQUEST['p1'] !=''){

                $order = Order::find()->where(['id'=> $_REQUEST['p1']])->one();

                if($order){

                    $order->is_payment_received = 'Y';
                    $order->save(false);
                    $result['order_id'] = $order->id;

                    $rider = Users::findOne($order->rider_id);
                    $rider->is_available='Y';
                    $rider->save(false);


                 /**
                  * And may be I have to fire one more notification to rider for payment recieved
                  */
             /**
               * send payment notification to rider as well as his vendor
               */
              $noti = new Notification;
              $noti->from_user = Yii::$app->user->id;

              $both_ids[] = $order->rider_id;
              $both_ids[] = $order->vendor_id;

              $noti->to_user = implode(',',$both_ids);

              $noti->notification_type = 'payment_status';
              $noti->message = "User has been paid payment of order #$order->id";
              $noti->type = 'A';
              $noti->order_id = $order->id;
              $noti->i_by = Yii::$app->user->id;
              $noti->i_date = date('Y-m-d H:i:s');
              $noti->i_datetime = time();
              $noti->save(false);

              $body_a=array();
              $body_a['data']['notification_type'] = 'payment_status';
              $body_a['data']['order_id'] = $order->id;
              $body_a['data']['master_id'] = $order->id;
              $body_a['data']['status'] = $order->status;
              $body_a['data']['message'] = "The payment for order #$order->id has been received";

              $body_i=array();
              $body_i['data'] = array('alert' =>"The payment for order #$order->id has been received");
              $body_i['data']['badge'] = 1;
              $body_i['data']['order_id'] = $order->id;
              $body_i['data']['master_id'] = $order->id;
              $body_i['data']['status'] = $order->status;
              $body_i['data']['notification_type'] = 'payment_status';
              $body_i['data']['sound'] = 'default';
              $body_i['data']['message'] = "The payment for order #$order->id has been received";
              $body_i['data']['alert'] = "The payment for order #$order->id has been received";
              $body_i['data']['text'] = "The payment for order #$order->id has been received";


              $user = Users::find()->where(['is_deleted'=>"N",'is_active'=>"Y",'notification_enabled'=>'Y','id'=>$both_ids])->select(['id','is_deleted','is_active','user_type','notification_enabled','is_online'])->all();
              $device_token_android=$device_token_iphone=array();
                $ij=$mn=0;
                if(!empty($user)){
                    foreach ($user as $u) {

                        $uDeviceDetail = Userdevices::find()->where(['user_id'=>$u->id])->orderby("last_login_datetime DESC")->one();

                            if(isset($uDeviceDetail->device_id) && $uDeviceDetail->device_id!=null && isset($uDeviceDetail->device_type) && $uDeviceDetail->device_type!=null)
                            {
                                if($uDeviceDetail->device_type=='a'|| $uDeviceDetail->device_type=='A')
                                {
                                    if(isset($device_token_android[$ij]) && count($device_token_android[$ij]) == 500)
                                        $ij++;
                                    $device_token_android[$ij][$u->id] = $uDeviceDetail->device_id;
                                }
                                if($uDeviceDetail->device_type=='i'|| $uDeviceDetail->device_type=='I')
                                {
                                    if(isset($device_token_iphone[$mn]) && count($device_token_iphone[$mn]) == 500)
                                        $mn++;
                                    $device_token_iphone[$mn][$u->id] = $uDeviceDetail->device_id;
                                }
                            }
                    }
                }
                    if($device_token_android != array())
                        Yii::$app->mycomponent->pushnotification_android_array($device_token_android,$body_a);

                    if($device_token_iphone != array())
                        Yii::$app->mycomponent->pushnotification_iphone_array($device_token_iphone,$body_i);


                }else{
                return Yii::$app->apifunction->setResponse('Order not found',false,400,400);
                }
            }

            return Yii::$app->apifunction->setResponse(yii::$app->common->ipaystatuscode($_REQUEST['status']),true,200,200,$result);

            }elseif('bdi6p2yy76etrs' == $_REQUEST['status'] ){
                $result['is_done'] = false;
                return Yii::$app->apifunction->setResponse(yii::$app->common->ipaystatuscode($_REQUEST['status']),false,200,400,$result);
            }elseif('cr5i3pgy9867e1' == $_REQUEST['status'] ){
                $result['is_done'] = false;
                return Yii::$app->apifunction->setResponse(yii::$app->common->ipaystatuscode($_REQUEST['status']),false,200,400,$result);
            }elseif('dtfi4p7yty45wq' == $_REQUEST['status'] ){
                $result['is_done'] = false;
                return Yii::$app->apifunction->setResponse(yii::$app->common->ipaystatuscode($_REQUEST['status']),false,200,400,$result);
            }elseif('eq3i7p5yt7645e' == $_REQUEST['status']){
                $result['is_done'] = false;
                return Yii::$app->apifunction->setResponse(yii::$app->common->ipaystatuscode($_REQUEST['status']),false,200,400,$result);
            }else{
                $result['is_done'] = false;
                return Yii::$app->apifunction->setResponse(yii::$app->common->ipaystatuscode($_REQUEST['status']),false,200,400,$result);
            }
        }else{
            $result['is_done'] = false;
            return Yii::$app->apifunction->setResponse('response_text',false,200,400,$result);
        }
    }

     public function actionZipcodelist()
      {
        // $required_objs = [];

        $zipcodes = Zipcode::find()->where(['is_deleted'=>'N','is_active'=>'Y'])->all();

        if(isset($zipcodes) && $zipcodes!= array())
        {
            $i = 0;
            foreach($zipcodes as $key => $zipcode){

            $result['zipcodes'][$i]['zipcode_id'] = $zipcode->id;
            $result['zipcodes'][$i]['zipcode_area'] = $zipcode->area_name;
            $result['zipcodes'][$i]['zipcode_code'] = $zipcode->zipcode;
            $i++;

        }
            return Yii::$app->apifunction->setResponse('zipcode_list',true,200,200,$result);

        }else{
            $result['zipcode_list'] = [];
            return Yii::$app->apifunction->setResponse('error_zipcode_list_not_found',false,200,400,$result);
        }

      }

      public function actionChangepaymentmode(){

        $required_objs = ['order_id'];
        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {
            //check user is guest or not
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);

            $user = Users::findOne(yii::$app->user->id);

            extract($_POST);
            /**
             * From order id find require information
             */
            $order = Order::find()->alias('O')->where(['O.id'=>$order_id,'O.user_id'=>yii::$app->user->id])->one();

            if($order){
                $order->payment_status = 'C';
                $order->save(false);

              $noti = new Notification;
              $noti->from_user = Yii::$app->user->id;

              $both_ids[] = $order->rider_id;
              $both_ids[] = $order->vendor_id;
            //   $both_ids[] = $order->user_id;
              $noti->order_id = $_REQUEST['order_id'];
              $noti->to_user = implode(',',$both_ids);

              $noti->notification_type = 'payment_mode_change';
              $noti->message = "Order #$order->id payment mode changed by the user";
              $noti->type = 'A';

              $noti->i_by = Yii::$app->user->id;
              $noti->i_date = date('Y-m-d H:i:s');
              $noti->i_datetime = time();
              $noti->save(false);

              $body_a=array();
              $body_a['data']['notification_type'] = 'payment_mode_change';
              $body_a['data']['order_id'] = $order->id;
              $body_a['data']['status'] = $order->status;
              $body_a['data']['master_id'] = $order->id;
              $body_a['data']['message'] = "Order #$order->id payment mode changed by the user";
            //   $body_a['data']['message2'] = "User has cancelled an order due to you have not cancel from your end, so fee KSH $cancelation_charge applicable in the next order";
            //   $body_a['data']['message3'] = "You have cancelled an order, so fee KSH $cancelation_charge applicable in the next order";

              $body_i=array();
              $body_i['data'] = array('alert' =>"Order #$order->id payment mode changed by the user");
              $body_i['data']['badge'] = 1;
              $body_i['data']['order_id'] = $order->id;
              $body_i['data']['master_id'] = $order->id;
              $body_i['data']['status'] = $order->status;
              $body_i['data']['notification_type'] = 'payment_mode_change';
              $body_i['data']['sound'] = 'default';
              $body_i['data']['message'] = "Order #$order->id payment mode changed by the user";
            //   $body_i['data']['message2'] = "User has cancelled an order due to you have not cancel from your end, so fee KSH $cancelation_charge applicable in the next order";
            //   $body_i['data']['message3'] = "You have cancelled an order, so fee KSH $cancelation_charge applicable in the next order";
              $body_i['data']['alert'] = "Order #$order->id payment mode changed by the user";
              $body_i['data']['text'] = "Order #$order->id payment mode changed by the user";


              $user = Users::find()->where(['is_deleted'=>"N",'is_active'=>"Y",'notification_enabled'=>'Y','id'=>$both_ids])->select(['id','is_deleted','is_active','user_type','notification_enabled','is_online'])->all();
              $device_token_android=$device_token_iphone=array();
                $ij=$mn=0;
                if(!empty($user)){
                    foreach ($user as $u) {

                        $uDeviceDetail = Userdevices::find()->where(['user_id'=>$u->id])->orderby("last_login_datetime DESC")->one();


                            if(isset($uDeviceDetail->device_id) && $uDeviceDetail->device_id!=null && isset($uDeviceDetail->device_type) && $uDeviceDetail->device_type!=null)
                            {
                                if($uDeviceDetail->device_type=='a'|| $uDeviceDetail->device_type=='A')
                                {
                                    if(isset($device_token_android[$ij]) && count($device_token_android[$ij]) == 500)
                                        $ij++;
                                    $device_token_android[$ij][$u->id] = $uDeviceDetail->device_id;
                                }
                                if($uDeviceDetail->device_type=='i'|| $uDeviceDetail->device_type=='I')
                                {
                                    if(isset($device_token_iphone[$mn]) && count($device_token_iphone[$mn]) == 500)
                                        $mn++;
                                    $device_token_iphone[$mn][$u->id] = $uDeviceDetail->device_id;
                                }
                            }
                    }
                }

            if($device_token_android != array())
                Yii::$app->mycomponent->pushnotification_android_array($device_token_android,$body_a);

            if($device_token_iphone != array())
                Yii::$app->mycomponent->pushnotification_iphone_array($device_token_iphone,$body_i);

                return Yii::$app->apifunction->setResponse('Payment mode changed successfully',true,200,200);


            }else{
                return Yii::$app->apifunction->setResponse('Order not found',false,400,400);
            }


        }else{

            return Yii::$app->apifunction->setResponse('response_text',false,200,400);
        }
    }


    public function actionDeleteaddress(){

        $this->layout=false;
        /*insert all required veriables*/
        $required_objs = ['address_id'];

        if(Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs,$_POST))
        {
        //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);


        extract($_POST);
        $userid = Yii::$app->user->id;
        $model = UserAddress::find()->where(['id'=>$address_id,'user_id'=>$userid])->one();

        if(isset($model) && $model!=array())
        {

            $model->is_deleted = 'Y';

            //now save record in database
            if($model->save(false)){
                    return Yii::$app->apifunction->setResponse('address_deleted',true,200,200);
                }
        }else{
            return Yii::$app->apifunction->setResponse('error_address_list_not_found',false,200,400);
        }
    }else{

        return Yii::$app->apifunction->setResponse('response_text',false,200,400);
    }
  }//delete address  end here
    
    public function actionAddeditbankdetail()
    {
        /**insert all required veriables*/
        $required_objs = ['mobile_number', 'bank_name', 'branch','account_number', 'account_name', 'swift_code', 'bank_code', 'branch_code'];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            extract($_POST);
            $userid = Yii::$app->user->id;
            // print_r($userid);die;
            $model = Bankdetail::findOne(['user_id' => yii::$app->user->id]);
            if (isset($model) && $model != array()) {

            }else{
                $model = new Bankdetail(); 
            }
            $model->mobile_pay_number = $mobile_number;
            $model->bank_name = $bank_name;
            $model->account_number = $account_number;
            $model->account_name = $account_name;
            $model->swift_code = $swift_code;
            $model->branch_code = $branch_code;
            $model->bank_code = $bank_code;
            $model->branch = $branch;
            $model->user_id = $userid;
            $model->save();
            return Yii::$app->apifunction->setResponse('success_bank_detail', true, 200, 200);
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 200, 400);
        }
    }

    public function actionGetbankdetails()
    {
        extract($_POST);
        $userid = Yii::$app->user->id;
        // print_r($userid);
        if(isset(Yii::$app->user->id) && Yii::$app->user->id != ""){
            $model = Bankdetail::findOne(['user_id' => yii::$app->user->id]);
            if (isset($model) && $model != array()) {
            $result = array();
            $result['id'] = $model->id;
            $result['mobile_number'] = $model->mobile_pay_number;
            $result['bank_name'] = $model->bank_name;
            $result['account_name'] = $model->account_name;
            $result['account_number'] = $model->account_number;
            $result['branch'] = $model->branch;
            $result['bank_code'] = $model->bank_code;
            $result['branch_code'] = $model->branch_code;
            $result['swift_code'] = $model->swift_code;
            return Yii::$app->apifunction->setResponse('success_bank_detail', true, 200, 200,$result);
            }else{
                return Yii::$app->apifunction->setResponse('error_bankdetail_not_found', false, 200, 400);
            }
            
        }else{
            return Yii::$app->apifunction->setResponse('response_text', false, 200, 400);
        }
    }
    
    public function actionVendors(){
        $required_objs = ['latitude', 'longitude', 'type','radius'];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            extract($_POST);
            $userid = Yii::$app->user->id;
            $vendors = Userstore::find()->select("user_stores.*,um.rating as vendor_rating,( 6371 * acos( cos( radians($latitude) ) * cos( radians( user_stores.latitude) ) * cos( radians( user_stores.longitude) - radians($longitude) ) + sin( radians($latitude) ) * sin( radians( user_stores.latitude ) ) ) ) AS radius")
                            ->leftJoin('user_master um','um.id=user_stores.user_id')
                            ->where(['user_stores.vendor_type'=>$type,'um.user_type'=>'V'])
                            ->andHaving("radius < $radius")->orderBy(['radius' => SORT_ASC])
                            ->all();
            $result['vendors'] = array();
            if(isset($vendors)&& $vendors != array()){
                $i = 0;
                foreach($vendors as $vendor){
                    $result['vendors'][$i]['id'] = $vendor->user_id;
                    $result['vendors'][$i]['shop_name'] = $vendor->shop_name;
                    if($type == 'R')
                        $result['vendors'][$i]['price'] = number_format($vendor->price,2);
                    else
                        $result['vendors'][$i]['price'] = number_format($vendor->price_per_kg,2);
                    $result['vendors'][$i]['latitude'] = $vendor->latitude  ;
                    $result['vendors'][$i]['longitude'] = $vendor->longitude;
                    $result['vendors'][$i]['location'] = $vendor->address;
                    $result['vendors'][$i]['logo'] = $vendor->logo ? Url::to('@web/' . $vendor->logo, true):"";
                    $result['vendors'][$i]['rating'] = $vendor->vendor_rating;
                    $i++;
                }
            }
            return Yii::$app->apifunction->setResponse('', true, 200, 200,$result);
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 200, 400);
        }
    }

    public function actionPurchaselistnew()
    {

        $this->layout = false;
        /*insert all required veriables*/
        $required_objs = ['new_purchase_type','vendor_id'];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            //check user is guest or not
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
            extract($_POST);
            $stocks = Product::find()->alias('P')->where(['P.is_active' => 'Y', 'P.is_deleted' => 'N','P.vendor_id'=>$vendor_id]);
            if($new_purchase_type != "other"){
                $stocks = $stocks->andWhere(['P.product_type' => $new_purchase_type]); 
            }
            $start = isset($start) ? $start : 0;
            $limit  = isset($limit)  ? $limit + 1  : 11;
            $stocks = $stocks->offset($start)->limit($limit);

            $stocks = $stocks->orderBy('id DESC')->all();
            // print_r($stocks);die;
            if ($stocks) {
                $i = 0;
                foreach ($stocks as $key => $value) {
                    $result['purchase_list'][$i]['id']    = (int) $value->id;
                    $result['purchase_list'][$i]['discount_price']    = number_format($value->price -  (($value->price * $value->discount / 100)), 2);
                    // $result['purchase_list'][$i]['discount_price']    = round($value->price -  (($value->price*$value->discount/100)),2);
                    $result['purchase_list'][$i]['discount']    = $value->discount ? $value->discount : "0";
                    $result['purchase_list'][$i]['title'] = $value->title;
                    $result['purchase_list'][$i]['product_id'] = $value->id;
                    $result['purchase_list'][$i]['size_id'] = $value->size_id ? $value->size_id : '';
                    $result['purchase_list'][$i]['size'] = $value->size;
                    $result['purchase_list'][$i]['size_image'] = '';
                    $result['purchase_list'][$i]['price'] = number_format($value->price, 2);
                    $result['purchase_list'][$i]['more_details'] = $value->description;
                    $i++;
                }
                $result['is_last'] = 'Y';
                if (isset($_REQUEST['limit']) && $_REQUEST['limit'] != null) {
                    if ($i >= $limit) {
                        unset($result['purchase_list'][$i - 1]);
                        $result['is_last'] = 'N';
                    }
                }
                return Yii::$app->apifunction->setResponse('success_purchase_list', true, 200, 200, $result);
            } else {
                $result['purchase_list'] = [];
                return Yii::$app->apifunction->setResponse('error_no_purchase_list', true, 200, 200, $result);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    } 
   

}
