<?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 : 
//********************************************************************************

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\OrderDetail;
use app\models\Notification;
use app\models\Users;
use app\models\Userstock;
use app\models\Userstore;
use app\models\Brand;
use app\models\Bankdetail;
use app\models\Product;
use app\models\Subscription;
use app\models\UserSubscription;
use app\models\Reason;
use app\models\UserReview;
use app\models\Stock;
use app\models\Review;
use app\models\Cart;
use app\models\Contactus;
use app\models\UserAddress;
use app\models\Setting;
use app\models\Deliverytimeslot;
use yii2\web\Request;
use yii\filters\AccessControl;
use Dompdf\Dompdf;
use Dompdf\Options;

include_once(Yii::getAlias('@vendor') . '/dompdf/autoload.inc.php');


class VendorController 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',
    ];


    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', 'generatereport', 'cronjobforstock', 'cronfororders',/*'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;
    }
    
    //********************************************************************************
    //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()
    {


        //insert all required veriables
        $required_objs = ['email','password', 'device_id', 'device_type'];
        // $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 = Yii::$app->apifunction->getUserDetailOnEmailandPassword($email,$password,'V');
            // $data = Yii::$app->apifunction->getUserDetailOnPasswordForLogin($mobile_number, $password, 'V');

            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);
                /*common code for login device updation is also there*/
                $result = Yii::$app->apifunction->apiLogin($data, $device_id, $device_type, $login_type, '', false);
                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;
    }

    public function actionMyaccount()
    {


        //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;
        }


        $userid = Yii::$app->user->id;
        $data = Users::findOne($userid);

        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);

            }

            //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);
            /*common code for login device updation is also there*/
            $result = Yii::$app->apifunction->apiLogin($data, $device_id, $device_type, $login_type, '', false);
            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;
    }


    //********************************************************************************
    //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;
    }

    
    //********************************************************************************
    //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 actionRegister()
    {

        /**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, 'V');

            if (!empty($email)) {

                $data = Yii::$app->apifunction->getUserDetailOnEmail($email, 'V');
                // $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'], 'V');
                    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 = 'V';
                $user->notification_enabled = 'Y';

                /**
                 * Provide fee plan day's
                 */
                $days = Setting::find()->where(['key' => 'subscription_pexpired'])->one();
                if ($days) {
                    $days = $days->value;
                    $user->subscription_expired_date = strtotime("+$days");
                }
                // $user->i_date = date('Y-m-d H:i:s');
                // $user->u_date = date('Y-m-d H:i:s');
                $user->is_update = 'N';
                $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 = 'Welcome to ' . Yii::$app->params['appName'] . ', One Time Password(OTP) to verify your phone number is :' . $otp;
                    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_id, 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;
    }

    //********************************************************************************
    //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, 'V');

            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/admin/default/resetpassword?args=" . $data->forgot_password_token, true);
                    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);
        }
    }


    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);
        }
    }

    
    //********************************************************************************
    //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 = 'V';

            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, '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);
        }
    }
   
    //********************************************************************************
    //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' => 'V', "mobile_number" => $mobile_number])->one();
            }
            if (isset($data) && $data != array()) {
                if ($data->otp == $otp) {
                    $data->mobile_verified = 'Y';
                    $data->save(false);

                    return Yii::$app->apifunction->setResponse('mobile_verified_successfully', true, 200, 200);
                    // 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, 'V');
            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=V", true);
            $result['privacy_policy'] = Url::to("@web/site/privacy_policy?type=V", true);
            $result['faqs'] = Url::to("@web/site/faq?type=V", true);
            $result['about_us'] = Url::to("@web/site/about?type=V", true);

            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;
    }
    
    //********************************************************************************
    //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 = '';
                }
                $check_email = Yii::$app->common->checkemail($_REQUEST['email'], $data->id, 'U');
                if ($check_email > 0) {

                    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['latitude']) && $_POST['latitude'] != '')
            $data->latitude = $_POST['latitude'];

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

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

            if (isset($_POST['longitude']) && $_POST['longitude'] != '' && $_POST['longitude'] != null)

                $data->longitude = $_POST['longitude'];

            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;
    }

    public function actionBusinessprofile()
    {
        $required_objs = ['shop_name', 'location', 'id_number', 'latitude', 'longitude','vendor_type'];

        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);

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

            $data = Users::find()->where(['id' => $userId, 'is_deleted' => 'N'])->one();


            $store = new Userstore;
            $store->user_id = $userId;
            $store->shop_name = isset($shop_name) ? $shop_name : '';
            $store->address = isset($location) ? $location : '';
            $store->id_number = isset($id_number) ? $id_number : '';

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

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

            $data->is_profile_completed = 'Y';
            $data->save(false);

            $store->zipcode = isset($zipcode) ? $zipcode : '';
            $store->latitude = isset($latitude) ? $latitude : '';
            $store->longitude = isset($longitude) ? $longitude : '';
            $store->vendor_type = isset($vendor_type) ? $vendor_type : 'R';
            if (isset($_FILES['logo']['tmp_name']) && $_FILES['logo']['tmp_name'] != null) {
                /**
                 * Unlink or delete the previouse image from server
                 */
                if ($store->logo != null && file_exists(Yii::getAlias('@webroot') . '/' . $store->logo)) {
                    unlink(Yii::getAlias('@webroot') . "/" . $store->logo);
                }


                $store->logo = Yii::$app->apifunction->normalUpload($_FILES['logo'], yii::$app->params['storeimage']);
            }

            if (isset($_FILES['business_license']['tmp_name']) && $_FILES['business_license']['tmp_name'] != null) {

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


                $store->business_license = Yii::$app->apifunction->normalUpload($_FILES['business_license'], yii::$app->params['licenceimage']);
            }

            if (isset($_FILES['kra_pin_certificate']['tmp_name']) && $_FILES['kra_pin_certificate']['tmp_name'] != null) {

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

                $store->kra_pin_certificate = Yii::$app->apifunction->normalUpload($_FILES['kra_pin_certificate'], yii::$app->params['licenceimage']);
            }

            $store->i_by = $userId;
            $store->i_date = time();
            $store->save(false);

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

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


    public function actionUpdatebusinessprofile()
    {
        $required_objs = ['shop_name', 'location', 'id_number', 'full_name', 'mobile_number', 'country_code', 'email', 'latitude', 'longitude'];

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

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

            $data = Users::find()->where(['id' => $userId, 'is_deleted' => 'N'])->one();

            //die(print_r($data));

            $data->user_name = isset($full_name) ? $full_name : '';
            $data->country_code = isset($country_code) ? $country_code : '';
            $data->mobile_number = isset($mobile_number) ? $mobile_number : '';
            $data->email = isset($email) ? $email : '';
            //make profile again in re-verify to admin 
            $data->profile_status = 'P';
            $data->readby_admin = 'N';
            $data->is_update = 'Y';

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

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

            $data->save(false);

            $store = Userstore::findOne(['user_id' => $userId]);
            // die(var_dump($store));
            $store->user_id = $userId;
            $store->shop_name = isset($shop_name) ? $shop_name : '';
            $store->address = isset($location) ? $location : '';
            $store->id_number = isset($id_number) ? $id_number : '';
            $store->zipcode = isset($zipcode) ? $zipcode : '';
            $store->latitude = isset($latitude) ? $latitude : '';
            $store->longitude = isset($longitude) ? $longitude : '';

            if (isset($_FILES['logo']['tmp_name']) && $_FILES['logo']['tmp_name'] != null) {
                $store->logo = Yii::$app->apifunction->normalUpload($_FILES['logo'], yii::$app->params['storeimage']);
            }

            if (isset($_FILES['business_license']['tmp_name']) && $_FILES['business_license']['tmp_name'] != null) {
                $store->business_license = Yii::$app->apifunction->normalUpload($_FILES['business_license'], yii::$app->params['licenceimage']);
            }

            if (isset($_FILES['kra_pin_certificate']['tmp_name']) && $_FILES['kra_pin_certificate']['tmp_name'] != null) {

                $store->kra_pin_certificate = Yii::$app->apifunction->normalUpload($_FILES['kra_pin_certificate'], yii::$app->params['licenceimage']);
            }

            Yii::$app->common->sendemail($data->email, $data->user_name, $link = null, 'Pending');


            $store->u_by = $userId;
            $store->u_date = time();
            $store->save(false);

            // $noti = new Notification;
            // $noti->from_user = 0;
            // $noti->to_user = $userId;
            // //$noti->order_id = $product_id;
            // $noti->notification_type = 'Update Vendor';
            // $noti->message = 'Vendor profile_successfully_updated';
            // $noti->type = 'V';

            // $noti->i_by = 0;
            // $noti->i_date = date('Y-m-d H:i:s');
            // $noti->i_datetime = time();
            // $noti->save(false);

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

            return Yii::$app->apifunction->setResponse('business_profile_successfully_updated', true, 200, 200, $result);
        } else {
            die(var_dump("coming"));
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 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 = 'V';
                $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;
            $model = Users::findOne($userid);


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

            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 = 'Welcome to ' . Yii::$app->params['appName'] . ', One Time Password(OTP) to verify your phone number is :' . $mPIN;
                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);

                // $user->mobile_verified = 'N';

                /***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->is_online = $is_online;
                    $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 actionAddeditbankdetail()
    {

        $this->layout = false;
        /*insert all required veriables*/
        $required_objs = ['mpesa_number', 'bank_name', 'account_name', 'account_number', 'branch', 'bank_code', 'branch_code', 'swift_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);
            if (isset($bank_id) && $bank_id != null) {
                $model = Bankdetail::findOne($bank_id);
                $model->mobile_pay_number = isset($mpesa_number) ? $mpesa_number : '';
                $model->mobile_pay_type = isset($mobile_pay_type) ? $mobile_pay_type : '';
                $model->bank_name = isset($bank_name) ? $bank_name : '';
                $model->account_name = isset($account_name) ? $account_name : '';
                $model->account_number = isset($account_number) ? $account_number : '';
                $model->branch = isset($branch) ? $branch : '';
                $model->pin_code = isset($bank_code) ? $bank_code : '';
                $model->branch_code = isset($branch_code) ? $branch_code : '';
                $model->swift_code = isset($swift_code) ? $swift_code : '';

                //now save record in database
                if ($model->save(false)) {
                    return Yii::$app->apifunction->setResponse('bankdetail_update_successfully', true, 200, 200);
                }
            } else {
                if (Bankdetail::findOne(['user_id' => yii::$app->user->id])) {
                    return Yii::$app->apifunction->setResponse('bankdetail_allready_added', false, 200, 400);
                }

                $model = new Bankdetail;
                $model->user_id = Yii::$app->user->id;
                $model->mobile_pay_number = isset($mpesa_number) ? $mpesa_number : '';
                $model->mobile_pay_type = isset($mobile_pay_type) ? $mobile_pay_type : '';
                $model->bank_name = isset($bank_name) ? $bank_name : '';
                $model->account_name = isset($account_name) ? $account_name : '';
                $model->account_number = isset($account_number) ? $account_number : '';
                $model->branch = isset($branch) ? $branch : '';
                $model->pin_code = isset($bank_code) ? $bank_code : '';
                $model->branch_code = isset($branch_code) ? $branch_code : '';
                $model->swift_code = isset($swift_code) ? $swift_code : '';
                if ($model->save(false)) {
                    return Yii::$app->apifunction->setResponse('bankdetail_added_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 : '';
                $result['address_list'][$i]['address'] = $address->address ? $address->address : '';
                $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 : '';
                $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 actionPlanlist()
    {
        $required_objs = [];
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);

        extract($_POST);

        $subsciptions = Subscription::find()->where(['is_active' => 'Y', 'is_deleted' => 'N']);


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


        $subsciptions = $subsciptions->all();

        if (isset($subsciptions) && $subsciptions != array()) {
            $i = 0;
            //Les't check this having subscribed plan

            $subscribed = UserSubscription::find()->where(['user_id' => yii::$app->user->id, 'is_expired' => 'N'])->one();

            foreach ($subsciptions as $key => $subsciption) {

                $result['package_plan'][$i]['id'] = $subsciption->id;
                $result['package_plan'][$i]['plan_tilte'] = $subsciption->plan_name ? $subsciption->plan_name : '';
                $result['package_plan'][$i]['plan_price'] = $subsciption->price ? number_format($subsciption->price, 2) : 0;
                $result['package_plan'][$i]['plan_type'] = $subsciption->plan_type ? $subsciption->plan_type : '';
                if ($subscribed)
                    $result['package_plan'][$i]['is_active'] = $subscribed->plan_id == $subsciption->id ? 'Y' : 'N';
                else
                    $result['package_plan'][$i]['is_active'] = 'N';

                $result['package_plan'][$i]['SKU'] = $subsciption->SKU ? $subsciption->SKU : '';

                $i++;
            }
            $result['is_last'] = 'Y';
            if ($i > $limit) {
                unset($result['package_plan'][$i - 1]);
                $result['is_last'] = 'N';
            }
            return Yii::$app->apifunction->setResponse('package_plan', true, 200, 200, $result);
        } else {
            $result['package_plan'] = [];
            return Yii::$app->apifunction->setResponse('package_not_found', false, 200, 400, $result);
        }
    } //Subscription Plan List end here


    public function actionRiderlist()
    {
        $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');

        $riders = Users::find()->where(['vendor_id' => yii::$app->user->id, 'is_deleted' => 'N']);


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


        $riders = $riders->all();

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

                $result['rider_list'][$i]['id'] = $rider->id;
                $result['rider_list'][$i]['name'] = $rider->user_name ? $rider->user_name : '';
                $result['rider_list'][$i]['image'] = $rider->image ? Url::to('@web/' . $rider->image, true) : '';
                $result['rider_list'][$i]['last_active'] = $rider->last_active ? $rider->last_active : '';
                $result['rider_list'][$i]['is_online'] = $rider->is_online ? $rider->is_online : '';
                $result['rider_list'][$i]['is_active'] = $rider->profile_status ? $rider->profile_status : '';

                $result['rider_list'][$i]['email'] = $rider->email ? $rider->email : '';

                $result['rider_list'][$i]['mobile_number'] = $rider->mobile_number ? $rider->mobile_number : '';


                $result['rider_list'][$i]['country_code'] = $rider->country_code ? $rider->country_code : '';

                $result['rider_list'][$i]['motor_bike_number'] = $rider->motor_bike_number ? $rider->motor_bike_number : '';

                $result['rider_list'][$i]['address'] = $rider->address ? $rider->address : '';

                $result['rider_list'][$i]['latitude'] = $rider->latitude ? $rider->latitude : '';

                $result['rider_list'][$i]['longitude'] = $rider->longitude ? $rider->longitude : '';

                $i++;
            }
            $result['is_last'] = 'Y';
            if ($i > $limit) {
                unset($result['rider_list'][$i - 1]);
                $result['is_last'] = 'N';
            }
            return Yii::$app->apifunction->setResponse('rider_list', true, 200, 200, $result);
        } else {
            $result['rider_list'] = [];
            return Yii::$app->apifunction->setResponse('error_rider_list_not_found', false, 200, 200, $result);
        }
    } //rider list end here

    public function actionDeleterider()
    {

        $this->layout = false;
        /*insert all required veriables*/
        $required_objs = ['rider_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 = Users::find()->where(['id' => $rider_id, 'user_type' => 'R', 'vendor_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('rider_deleted_successfully', true, 200, 200);
                }
            } else {
                return Yii::$app->apifunction->setResponse('error_rider_not_found', false, 200, 400);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    } //delete rider  end here


    public function actionPlandetail()
    {

        $this->layout = false;
        /*insert all required veriables*/
        $required_objs = ['plan_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;
            $subsciption = Subscription::find()->where(['id' => $plan_id, 'is_active' => 'Y', 'is_deleted' => 'N'])->one();

            if (isset($subsciption) && $subsciption != array()) {
                $subscribed = UserSubscription::find()->where(['user_id' => yii::$app->user->id, 'is_expired' => 'N', 'plan_id' => $plan_id])->one();

                $result['package_plan']['id'] = $subsciption->id;
                $result['package_plan']['plan_tilte'] = $subsciption->plan_name ? $subsciption->plan_name : '';
                $result['package_plan']['plan_price'] = $subsciption->price ? number_format($subsciption->price, 2) : 0;
                $result['package_plan']['plan_type'] = $subsciption->plan_type ? $subsciption->plan_type : '';
                if ($subscribed) {
                    $result['package_plan']['is_active'] = $subscribed->plan_id == $subsciption->id ? 'Y' : 'N';
                    $result['package_plan']['start_date'] = $subscribed->purchase_date;
                    $result['package_plan']['end_date'] = $subscribed->expired_date;
                    // $Useraddress = UserAddress::find()->where(['user_id'=>yii::$app->user->id,'is_deleted'=>'N'])->one();
                    $Useraddress = Users::findOne(yii::$app->user->id);
                    $result['package_plan']['address'] = isset($Useraddress->address) ? $Useraddress->address : '';
                } else {
                    $result['package_plan']['is_active'] = 'N';
                    // $result['package_plan']['start_date'] = time();
                    $result['package_plan']['start_date'] = '';

                    // if($subsciption->plan_type == 'W')
                    //  $exp = '+7 days';
                    // if($subsciption->plan_type == 'M')
                    //  $exp = '+1 month';
                    // if($subsciption->plan_type == 'Q')
                    //  $exp = '+3 months';
                    // if($subsciption->plan_type == 'H')
                    //  $exp = '+6 months';
                    // if($subsciption->plan_type == 'Y')
                    //  $exp = '+12 months';
                    // if($subsciption->plan_type == 'YY')
                    //  $exp = '+24 months';

                    //  $result['package_plan']['end_date'] = strtotime($exp);
                    $result['package_plan']['end_date'] = '';
                    $result['package_plan']['address'] = '';
                }

                $result['package_plan']['SKU'] = $subsciption->SKU ? $subsciption->SKU : '';
                $result['package_plan']['payment_mode'] = 'in_app';


                return Yii::$app->apifunction->setResponse('success_plan_detail', true, 200, 200, $result);
            } else {
                return Yii::$app->apifunction->setResponse('package_not_found', false, 200, 400);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    } //plan detail  end here


    public function actionUpdatestock()
    {

        $this->layout = false;
        /*insert all required veriables*/
        $required_objs = ['product_id', 'stock'];
        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 = Stock::find()->where(['user_id' => yii::$app->user->id, 'product_id' => $product_id])->one();
            if ($model) {
                $model->quantity = $stock;
                // $model->quantity += $stock;
                $model->i_date = time();

                //now save record in database
                if ($model->save(false)) {
                    return Yii::$app->apifunction->setResponse('product_stock_added_successfully', true, 200, 200);
                } else {
                    return Yii::$app->apifunction->setResponse('error_product_stock_error', false, 200, 400);
                }
            } else {
                return Yii::$app->apifunction->setResponse('error_product_not_found', false, 400, 400);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    } //update stock  end here

    public function actionAddproduct()
    {

        $this->layout = false;
        /*insert all required veriables*/
        $required_objs = ['product_id', 'quantity', 'size_id']; //,'size_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;

            //Lets first check this product is already added or not

            if (Stock::find()->where(['user_id' => yii::$app->user->id, 'product_id' => $product_id])->one()) {
                return Yii::$app->apifunction->setResponse('product_already_added', true, 200, 200);
            }
            $model = new Stock;
            $model->user_id = yii::$app->user->id;
            $model->size_id = isset($size_id) ? $size_id : '';
            $model->quantity = isset($quantity) ? $quantity : '';
            $model->product_id = $product_id;
            $model->i_date = time();

            //now save record in database
            if ($model->save(false)) {
                return Yii::$app->apifunction->setResponse('product_added_successfully', true, 200, 200);
            } else {
                return Yii::$app->apifunction->setResponse('error_product_add', false, 200, 400);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    } //add product  end here


    public function actionStockreminder()
    {

        $this->layout = false;
        /*insert all required veriables*/
        $required_objs = ['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;
            $model = Userstock::findOne(['user_id' => yii::$app->user->id]);

            if (isset($model) && $model != array()) {
                $model->quantity = isset($quantity) ? $quantity : 10;
                $model->save(false);
                return Yii::$app->apifunction->setResponse('success_remider_quantity_update', true, 200, 200);
            } else {
                $model = new Userstock;
                $model->user_id = yii::$app->user->id;
                $model->product_id = isset($product_id) ? $product_id : '';
                $model->quantity   = isset($quantity) ? $quantity : 10;
                $model->save(false);
                return Yii::$app->apifunction->setResponse('success_remider_quantity_update', true, 200, 200);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    } //delete rider  end here


    public function actionRiderdetail()
    {

        $this->layout = false;
        /*insert all required veriables*/
        $required_objs = ['rider_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 = Users::find()->where(['id' => $rider_id, 'user_type' => 'R', 'vendor_id' => $userid])->one();

            if (isset($model) && $model != array()) {
                $result['rider_name'] = isset($model->user_name) ? $model->user_name : '';
                $result['image'] = isset($model->profile_image) ? Url::to('@web/' . $model->profile_image, true) : '';
                $result['vehicle_number'] = isset($model->motor_bike_number) ? $model->motor_bike_number : '';
                $result['is_active'] = isset($model->is_active) ? $model->is_active : '';

                $result['is_online'] = $model->is_online ? $model->is_online : '';
                $result['is_active'] = $model->profile_status ? $model->profile_status : '';


                $result['country_code'] = isset($model->country_code) ? $model->country_code : '';
                $result['mobile_number'] = isset($model->mobile_number) ? $model->mobile_number : '';
                $result['no_of_order_accepted'] = isset($model->number_of_orders) ? $model->number_of_orders : '';
                $result['no_of_order_delivered'] = isset($model->no_of_order_delivered) ? $model->no_of_order_delivered : '';
                $result['no_of_order_passed'] = isset($model->no_of_order_passed) ? $model->no_of_order_passed : '';
                $result['rating'] = isset($model->rating) ? $model->rating : '';

                return Yii::$app->apifunction->setResponse('success_rider_detail', true, 200, 200, $result);
            } else {
                return Yii::$app->apifunction->setResponse('error_rider_not_found', false, 200, 400);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    } //rider details  end here

    public function actionCategorylist()
    {

        $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);

            //Lets first get the all brand list
            if (empty($_REQUEST['brand_id']))
                $product = Product::find()->alias('P')->where(['P.is_deleted' => 'N', 'P.is_active' => 'Y', 'product_type' => $type]);
            else
                $product = Product::find()->alias('P')->where(['P.is_deleted' => 'N', 'P.is_active' => 'Y', 'product_type' => $type])
                    ->andWhere(['P.brand_id' => explode(',', $_REQUEST['brand_id'])]);

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

            $product = $product->orderBy('id DESC')->all();
            if ($product) {
                $i = 0;

                /**
                 * Here let me find Category for this vendor 
                 */
                $all_ready_added = Stock::find()->select(['id', 'product_id', 'user_id'])->where(['user_id' => yii::$app->user->id])->all();

                $all_ready_added = ArrayHelper::map($all_ready_added, 'product_id', 'product_id');

                foreach ($product as $key => $value) {
                    $result['category_item_list'][$i]['id']    = $value->id;
                    $result['category_item_list'][$i]['title'] = $value->title;
                    $result['category_item_list'][$i]['size'] = $value->size;
                    $result['category_item_list'][$i]['size_id'] = $value->size_id;

                    $result['category_item_list'][$i]['discount_price']    = number_format($value->price -  (($value->price * $value->discount / 100)), 2);
                    $result['category_item_list'][$i]['discount']    = $value->discount ? $value->discount : "0";

                    $result['category_item_list'][$i]['price'] = number_format($value->price, 2);
                    $result['category_item_list'][$i]['brand'] = $value->brand->brand_name ? $value->brand->brand_name : '';
                    $result['category_item_list'][$i]['brand_image'] = $value->brand->brand_image ? Url::to('@web/' . $value->brand->brand_image, true) : '';
                    $result['category_item_list'][$i]['is_added'] = in_array($value->id, $all_ready_added) ? 'Y' : 'N';
                    $i++;
                }

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

                if (isset($_REQUEST['limit']) && $_REQUEST['limit'] != null) {
                    if ($i >= $limit) {
                        unset($result['category_item_list'][$i - 1]);
                        $result['is_last'] = 'N';
                    }
                }
                return Yii::$app->apifunction->setResponse('success_category_item_list', true, 200, 200, $result);
            } else {
                $result['category_item_list'] = [];
                return Yii::$app->apifunction->setResponse('error_no_category_list', true, 200, 200, $result);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    } //Category list end here


    public function actionProductlist()
    {

        $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);

            //Lets first get the all brand list
            $stocks = Stock::find()->alias('S')->where(['S.user_id' => yii::$app->user->id]);
            $stocks = $stocks->joinWith('product')->andWhere(['P.product_type' => $type]);

            if (empty($_REQUEST['brand_id']))
                $stocks = $stocks->joinWith('product.brand');
            else $stocks = $stocks->joinWith('product.brand')
                ->andWhere(['brand_id' => explode(',', $_REQUEST['brand_id'])]);


            $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['category_item_list'][$i]['id']    = (int) $value->id;
                    $result['category_item_list'][$i]['product_id']  = (int) $value->product_id;
                    $result['category_item_list'][$i]['quantity']    = $value->quantity;
                    $result['category_item_list'][$i]['title'] = $value->product->title;
                    $result['category_item_list'][$i]['size'] = $value->product->size;
                    $result['category_item_list'][$i]['size_id'] = $value->product->size_id ? $value->product->size_id : '';
                    $result['category_item_list'][$i]['size_image'] = '';

                    $result['category_item_list'][$i]['discount_price']    = number_format($value->product->price -  (($value->product->price * $value->product->discount / 100)), 2);
                    $result['category_item_list'][$i]['discount']    = $value->product->discount ? $value->product->discount : "0";

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

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

                if (isset($_REQUEST['limit']) && $_REQUEST['limit'] != null) {
                    if ($i >= $limit) {
                        unset($result['category_item_list'][$i - 1]);
                        $result['is_last'] = 'N';
                    }
                }
                return Yii::$app->apifunction->setResponse('success_category_item_list', true, 200, 200, $result);
            } else {
                $result['category_item_list'] = [];
                return Yii::$app->apifunction->setResponse('error_no_category_list', true, 200, 200, $result);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    } //Product 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' => ['V', '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' => ['V', '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);
            }


            $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($other_reason) && !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)) {
                $log = new Orderlog;
                $log->order_id = $order->id;
                $log->status = 8;
                $log->i_by = $userId;
                $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', 'comment'];
        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->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;

            $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->vendor_id  = isset($vendor_id) ? $vendor_id : null;
            $cart->quantity   = isset($quantity) ? $quantity : null;
            $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']);

        $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 = '';
                $price = 0;

                if ($value->product_id != null) {
                    $product = Product::find()->select(['id', 'title', 'product_type', 'price', 'is_deleted', 'brand_id'])->where(['id' => $value->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;
                    }
                } 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;
                    }
                }
                $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]['type'] = $type;
                $result['cart_item_list'][$i]['price'] = number_format($value->quantity * $price, 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 actionAddrider()
    {

        /**insert all required veriables*/
        $required_objs = ['full_name', 'email', 'mobile_number', 'motor_bike_number', 'address', 'country_code', 'latitude', 'longitude'];
        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,'V');

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

            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'], 'R');
                if (isset($contact_data) && $contact_data != array())
                    return Yii::$app->apifunction->setResponse('phone_exist_already', false, 200, 400);
            }

            $user = new Users();

            if (isset($full_name) && $full_name != null)
                $user->user_name = $full_name;

            if (isset($latitude) && $latitude != null)
                $user->latitude = $latitude;

            if (isset($longitude) && $longitude != null)
                $user->longitude = $longitude;

            if (isset($last_name) && $last_name != null)
                $user->last_name = $last_name;

            if (isset($address) && $address != null)
                $user->address = $address;

            $user->email_verified = 'Y'; //if email is optional
            if (isset($email) && $email != null) {
                $user->email = $email;
                $user->email_verified = 'Y';
            }
            $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 = 'Y';
            }
            $mPIN = Yii::$app->common->generate_otp_code();

            $user->password = md5($mPIN);

            $user->motor_bike_number = isset($motor_bike_number) ? $motor_bike_number : '';
            $user->vendor_id = $userId;

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

            // $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->save(false);

            $user->i_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 = 'Welcome to ' . Yii::$app->params['appName'] . ', Your M-PIN number is :' . $mPIN;
                Yii::$app->common->sendsms($user->country_code . $user->mobile_number, $content);



                if (isset($user->email) && $user->email != null) {
                    Yii::$app->common->otpemailrider($user->email, $user->user_name, $content, $user->country_code . ' ' . $user->mobile_number);
                }
                $user->mobile_verified = 'Y';
            }
            if ($user->save(false)) {
                return Yii::$app->apifunction->setResponse('rider_added_successfully', true, 200, 200);
            }

            // }
            // 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;
    }


    public function actionEditrider()
    {

        /**insert all required veriables*/
        $required_objs = ['full_name', 'email', 'mobile_number', 'motor_bike_number', 'address', 'country_code', 'latitude', 'longitude', 'rider_id'];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {

            extract($_POST);

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

            if (!isset($device_id)) {
                $device_id = null;
            }
            if (!isset($device_type)) {
                $device_type = null;
            }
            if (!isset($dob)) {
                $dob = 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'], 'R');

                if (isset($contact_data) && $contact_data != array())
                    if ($contact_data->id != $rider_id)
                        return Yii::$app->apifunction->setResponse('phone_exist_already', false, 200, 400);
            }

            $user = Users::findOne($rider_id);

            if (empty($user->id)) {
                return Yii::$app->apifunction->setResponse('Rider not found', false, 200, 400);
            }

            if (isset($full_name) && $full_name != null)
                $user->user_name = $full_name;

            if (isset($latitude) && $latitude != null)
                $user->latitude = $latitude;

            if (isset($longitude) && $longitude != null)
                $user->longitude = $longitude;

            if (isset($last_name) && $last_name != null)
                $user->last_name = $last_name;

            if (isset($address) && $address != null)
                $user->address = $address;

            if (isset($email) && $email != null) {
                $user->email = $email;
                $user->email_verified = 'Y';
            }

            if (isset($_POST['country_code']) && $_POST['country_code'] != null && isset($_POST['mobile_number']) && $_POST['mobile_number'] != null) {
                if ($user->mobile_number != $_POST['mobile_number'])
                    $user->mobile_verified = 'N';
                else
                    $user->mobile_verified = 'Y';

                $user->country_code = $_POST['country_code'];
                $user->mobile_number = $_POST['mobile_number'];
            }

            $user->motor_bike_number = isset($motor_bike_number) ? $motor_bike_number : '';

            $user->u_date = time();
            $user->i_by = $userId;
            $otp = Yii::$app->common->generate_otp_code();
            $user->otp = $otp;
            if ($user->save(false)) {

                if ($user->mobile_verified == 'N') {

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

                    if (isset($user->email) && $user->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->email, $user->user_name, $content, 'otp_mail');
                    }
                }
                return Yii::$app->apifunction->setResponse('Update successfully', true, 200, 200);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 200, 400);
        }
        return $result;
    }

    public function actionBankdetail()
    {

        $this->layout = false;

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

        extract($_POST);
        $userid = Yii::$app->user->id;
        $model = Bankdetail::findOne(['user_id' => yii::$app->user->id]);

        if (isset($model) && $model != array()) {
            $result['id'] = $model->id;
            $result['mpesa_number'] = isset($model->mobile_pay_number) ? $model->mobile_pay_number : '';
            $result['bank_name'] = isset($model->bank_name) ? $model->bank_name : '';
            $result['account_name'] = isset($model->account_name) ? $model->account_name : '';
            $result['account_number'] = isset($model->account_number) ? $model->account_number : '';
            $result['branch'] = isset($model->branch) ? $model->branch : '';
            $result['bank_code'] = isset($model->pin_code) ? $model->pin_code : '';
            $result['branch_code'] = isset($model->branch_code) ? $model->branch_code : '';
            $result['swift_code'] = isset($model->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);
        }
    } //rider details  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 = [];
        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($type) && $type == 'OG')
                $order = OrderDetail::find()->alias('O')->where(['O.status' => ['1', '3', '4']]);
            else
                $order = OrderDetail::find()->alias('O');
            //$order = Order::find()->alias('O')->where(['O.vendor_id'=>yii::$app->user->id]);
            $order = $order->joinwith(['order']);
            $order = $order->joinwith(['order.customer']);
            $order = $order->joinwith(['order.rider'])->andwhere(['not', ['rider_id' => null]]);
            $order = $order->joinwith(['product']);
            $order = $order->joinwith(['product.brand']);

            $start = isset($start) ? $start : 0;
            $limit  = isset($limit)  ? $limit + 1  : 11;
            $order = $order->andwhere(['M.vendor_id' => yii::$app->user->id]);


            if (isset($_POST['order_type']) && $_POST['order_type'] != null) {
                $order_type = $_POST['order_type'];
                $order = $order->andWhere(['O.product_type' => $order_type]);
            }

            if (isset($order_status) && $order_status) {

                if ($order_status == 'D')
                    $order_status = ['7'];
                elseif ($order_status == 'O')
                    $order_status = ['3', '4', '1'];
                elseif ($order_status == 'A')
                    $order_status = ['3', '4', '1', '8', '9', '7', '10'];
                elseif ($order_status == 'C')
                    $order_status = ['8', '9', '10'];
                else
                    $order_status = ['3', '4', '1', '8', '9', '7'];


                $order = $order->andWhere(['O.status' => $order_status]);
            }

            if (isset($_POST['start_date']) && $_POST['start_date'] != null) {
                $start_date = $_POST['start_date'];
                $order = $order->andFilterWhere(['>=', 'O.i_date', $start_date]);
            }


            if (isset($_POST['end_date']) && $_POST['end_date'] != null) {
                $end_date = $_POST['end_date'];
                $order = $order->andFilterWhere(['<=', 'O.i_date', $end_date]);
            }

            $order = $order->offset($start)->limit($limit);

            $order = $order->orderBy('O.i_date 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]['time'] = $value->order->i_date;
                    $result['order_list'][$i]['status'] = $value->status;
                    // $result['order_list'][$i]['status'] = $value->order->status;
                    $result['order_list'][$i]['order_description'] = $value->product->title;
                    $result['order_list'][$i]['brand'] = $value->product->brand->brand_name;
                    $result['order_list'][$i]['brand_image'] = $value->product->brand->brand_image ? Url::to('@web/' . $value->product->brand->brand_image, true) : '';
                    $result['order_list'][$i]['quantity'] = $value->quantity;
                    $result['order_list'][$i]['total_price'] = number_format($value->order->total_price, 2);
                    $result['order_list'][$i]['price'] = number_format($value->unit_price, 2);
                    $result['order_list'][$i]['customer_name'] = $value->order->customer->user_name;
                    $result['order_list'][$i]['customer_image'] = $value->order->customer->image ? Url::to('@web/' . $value->order->customer->image, true) : '';
                    $result['order_list'][$i]['rider_name'] = $value->order->rider->user_name;
                    $result['order_list'][$i]['rider_image'] = $value->order->rider->image ? Url::to('@web/' . $value->order->rider->image, true) : '';
                    $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(['id' => $master_id])->one();
            //**********************************************************///

            // uncomment bellow code on complete senario 
            //*********************************************************///

            // $order_master = Order::find()->alias('O')->where(['vendor_id'=>yii::$app->user->id,'id'=>$master_id])->one();

            if ($order_master) {
                $order_derail_obj = OrderDetail::find()->alias('OD')->where(['order_id' => $order_master->id])->one();
                $result['order_details']['order_id'] = $order_master->id;
                $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']['price'] = number_format($order_derail_obj->unit_price, 2);
                $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 : '';
                $result['order_details']['order_status'] = $order_master->status;

                $result['order_details']['payment_mode'] = $order_master->payment_status;

                if ($order_master->promocode_id != null) {
                    $result['order_details']['is_promo'] = 'Y';
                    $result['order_details']['promocode_price'] = ($order_master->base_price * $order_master->promocode_discount) / 100;
                } else {
                    $result['order_details']['is_promo'] = 'N';
                    $result['order_details']['promocode_price'] = '';
                }

                // $result['order_details']['total_price'] = $order_master->total_price;
                // $result['order_details']['total_price'] = $order_master->total_price;


                $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) : '';

                /**
                 * Let's cehck this driver is rated for this order 
                 */
                $rate = UserReview::find()->where(['order_id' => $order_master->id, 'to_id' => $rider->id, 'is_deleted' => 'N'])->one();
                // $rate = UserReview::find()->where(['order_id'=>$order_master->id,'from_id'=>yii::$app->user->id,'to_id'=>$rider->id,'is_deleted'=>'N'])->one();
                if ($rate)
                    $result['rider_info']['is_rated'] = 'Y';
                else
                    $result['rider_info']['is_rated'] = 'N';

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

                $str = '';


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

                if ($address->area && $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;

                $result['delivery_address']['user_image'] = $order_master->customer->image != '' ? Url::to('@web/' . $order_master->customer->image, true) : '';




                // $order = OrderDetail::find()->alias('O')->where(['user_id'=>$order_master->user_id,'order_id'=>$order_master->id]);
                $order = OrderDetail::find()->alias('O')->where(['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]['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]['base_price'] = number_format($value->unit_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 actionCustomerlist()
    {

        $this->layout = false;
        /*insert all required veriables*/
        $required_objs = [];
        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(['O.vendor_id' => yii::$app->user->id]);
            $order_master = $order_master->joinWith(['customer']);

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


            $order_master = $order_master->orderBy('i_date DESC')->groupBy('user_id')->all();

            if ($order_master) {
                $i = 0;
                foreach ($order_master as $key => $value) {
                    $result['customer_list'][$i]['name'] = $value->customer->user_name;
                    $result['customer_list'][$i]['last_purchase'] = $value->i_date;
                    $result['customer_list'][$i]['image'] = $value->customer->image ? Url::to('@web/' . $value->customer->image, true) : '';

                    $i++;
                }
                $result['is_last'] = 'Y';
                if ($i > $limit) {
                    unset($result['customer_list'][$i - 1]);
                    $result['is_last'] = 'N';
                }
                return Yii::$app->apifunction->setResponse('success_customer_list', true, 200, 200, $result);
            } else {
                $result['customer_list'] = [];
                return Yii::$app->apifunction->setResponse('error_no_customer_found', true, 200, 200, $result);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    } //Customer list end here

    public function actionAddsubscription()
    {

        $this->layout = false;
        /*insert all required veriables*/
        $required_objs = ['tansacation_id', 'subscription_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);

            $subsciptions = Subscription::find()->where(['is_active' => 'Y', 'is_deleted' => 'N', 'id' => $subscription_id])->one();

            if ($subsciptions) {
                $new_subscription = new UserSubscription;
                $new_subscription->user_id = yii::$app->user->id;
                $new_subscription->plan_id = $subsciptions->id;
                $new_subscription->plan_name = $subsciptions->plan_name;
                $new_subscription->price = $subsciptions->price;
                $new_subscription->purchase_date = time();

                if ($subsciptions->plan_type == 'W')
                    $exp = '+7 days';
                if ($subsciptions->plan_type == 'M')
                    $exp = '+1 month';
                if ($subsciptions->plan_type == 'Q')
                    $exp = '+3 months';
                if ($subsciptions->plan_type == 'H')
                    $exp = '+6 months';
                if ($subsciptions->plan_type == 'Y')
                    $exp = '+12 months';
                if ($subsciptions->plan_type == 'YY')
                    $exp = '+24 months';

                $new_subscription->expired_date =  strtotime($exp);
                $new_subscription->tansacation_id = $tansacation_id;
                $new_subscription->save(false);

                return Yii::$app->apifunction->setResponse('Success', true, 200, 200);
            } else {
                return Yii::$app->apifunction->setResponse('Subscription plan not found', true, 200, 400);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    } //Customer list end here


    public function getLastNDays($days, $format = 'd-m-Y')
    {
        $m = date("m");
        $de = date("d");
        $y = date("Y");
        $dateArray = array();
        for ($i = 0; $i <= $days - 1; $i++) {
            $dateArray[] = '' . date($format, mktime(0, 0, 0, $m, ($de - $i), $y)) . '';
        }
        return array_reverse($dateArray);
    }

    public function actionReview()
    {

        $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);
        $rider_ids = ArrayHelper::map(Users::find()->where(['vendor_id' => yii::$app->user->id])->all(), 'id', 'id');
        $result['overall_rating'] = Review::find()->where(['to_id' => $rider_ids])->sum('rating') / Review::find()->where(['to_id' => $rider_ids])->count();
        $result['review_count'] = (int) Review::find()->where(['to_id' => $rider_ids])->count();
        // $result['one_rate_count']= (int)Review::find()->where(['to_id'=>$rider_ids,'is_deleted'=>'N'])->andwhere(['rating'=>1])->count();
        // $result['two_rate_count']= (int)Review::find()->where(['to_id'=>$rider_ids,'is_deleted'=>'N'])->andwhere(['rating'=>2])->count();
        // $result['three_rate_count']= (int)Review::find()->where(['to_id'=>$rider_ids,'is_deleted'=>'N'])->andwhere(['rating'=>3])->count();
        // $result['four_rate_count']= (int)Review::find()->where(['to_id'=>$rider_ids,'is_deleted'=>'N'])->andwhere(['rating'=>4])->count();
        // $result['five_rate_count']= (int)Review::find()->where(['to_id'=>$rider_ids,'is_deleted'=>'N'])->andwhere(['rating'=>5])->count();

        $result['one_rate_count'] = (int) Review::find()->where(['to_id' => yii::$app->user->id])->andWhere(['between', 'rating', 0.5, 1])->count();
        $result['two_rate_count'] = (int) Review::find()->where(['to_id' => yii::$app->user->id])->andWhere(['between', 'rating', 1.5, 2])->count();
        $result['three_rate_count'] = (int) Review::find()->where(['to_id' => yii::$app->user->id])->andWhere(['between', 'rating', 2.5, 3])->count();
        $result['four_rate_count'] = (int) Review::find()->where(['to_id' => yii::$app->user->id])->andWhere(['between', 'rating', 3.5, 4])->count();
        $result['five_rate_count'] = (int) Review::find()->where(['to_id' => yii::$app->user->id])->andWhere(['between', 'rating', 4.5, 5])->count();


        //First find all driver for this vendor


        //Lets  gets all review  list

        $reviews = Review::find()->where(['to_id' => $rider_ids, 'is_deleted' => 'N']);

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

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

        if ($reviews) {
            $i = 0;
            foreach ($reviews as  $value) {
                $result['review_list_list'][$i]['review_id'] = $value->id;
                $result['review_list_list'][$i]['rate'] = (float) $value->rating;
                $result['review_list_list'][$i]['date'] = strtotime($value->i_date);
                $result['review_list_list'][$i]['review_description'] = isset($value->review) ? $value->review : '';
                $i++;
            }

            $result['is_last'] = 'Y';
            if ($i > $limit) {
                unset($result['review_list_list'][$i - 1]);
                $result['is_last'] = 'N';
            }

            return Yii::$app->apifunction->setResponse('review_list_list', true, 200, 200, $result);
        }
        $result['review_list_list'] = [];
        return Yii::$app->apifunction->setResponse('error_review_list_list', true, 200, 400, $result);
    } //Review list end here


    public function actionDashboard()
    {

        $this->layout = false;
        /*insert all required veriables*/
        $required_objs = [];
        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);

            $data = Users::findOne(yii::$app->user->id);
            // I have to find the Collection


            // set current date
            $date = date(yii::$app->params['datetimeformat1']);
            // parse about any English textual datetime description into a Unix timestamp 
            $ts = strtotime($date);
            // find the year (ISO-8601 year number) and the current week
            $year = date('o', $ts);
            $week = date('W', $ts);

            $last7days = $this->getLastNDays(7);

            /*change by rajesh */
            $i = 0;
            foreach ($last7days as $last7daysval) {
                $week_timestamp['week'][$i]['start'] = strtotime($last7daysval);
                $week_timestamp['week'][$i]['end'] = strtotime($last7daysval . ' 23:59:59');
                $week_timestamp['week'][$i]['day'] = date("D", strtotime($last7daysval));
                $i++;
            }
            /*end change by rajesh */

            // print week for the current date
            // for($i = 1; $i <= 7; $i++) {
            //     // timestamp from ISO week date format
            //     $week_timestamp['week'][$i]['start'] = strtotime($year.'W'.$week.$i);
            //     $end_date = date('Y-m-d', strtotime($year.'W'.$week.$i));
            //     $week_timestamp['week'][$i]['end'] = strtotime($end_date.' 23:59:59');
            //     $week_timestamp['week'][$i]['day'] =  date("m/d/Y l", strtotime($year.'W'.$week.$i));
            // }


            $j = 0;
            foreach ($week_timestamp['week']  as $day) {
                $result['weekly_data'][$j]['daywise'] =  (float) Order::find()->where(['vendor_id' => yii::$app->user->id, 'status' => ['7']])
                    ->andwhere(['between', 'i_date', $day['start'], $day['end']])
                    ->sum('total_price');
                $result['weekly_data'][$j]['day'] = $day['day'];
                $j++;
            }
            $result['is_profile_approved']  = $data->profile_status == 'A' ? 'Y' : 'N';


            $start_date = date('Y-m-d', time());
            $start_date = strtotime($start_date . ' 00:00:00');


            $end_date = date('Y-m-d', time());
            $end_date = strtotime($end_date . ' 23:59:59');


            $todays_order = Order::find()->where(['vendor_id' => yii::$app->user->id, 'status' => ['7']])
                ->andwhere(['between', 'i_date', $start_date, $end_date]) //change by rajesh as record no getting
                // ->andwhere('i_date >='.$start_date) 
                // ->andwhere('i_date <='.$end_date) 
                ->sum('total_price');



            $result['todays_sales'] = $todays_order ? number_format($todays_order, 2) : 0;


            $start_date = strtotime('first day of january this year');
            $end_date = strtotime('last day of december this year');

            $year_order = Order::find()->where(['vendor_id' => yii::$app->user->id, 'status' => ['7']])
                ->andwhere(['between', 'i_date', $start_date, $end_date])
                ->sum('total_price');
            if ($year_order)
                $result['total_sales_of_year']  = number_format($year_order, 2);
            else
                $result['total_sales_of_year']  = '';


            $order = OrderDetail::find()->alias('O');

            $order = $order->joinwith(['order'])->andwhere(['not', ['M.status' => ['7', '8', '9', '10']]]);
            $order = $order->joinwith(['order.customer']);
            $order = $order->joinwith(['order.rider'])->andwhere(['not', ['rider_id' => null]]);
            $order = $order->joinwith(['product']);
            $order = $order->joinwith(['product.brand']);

            $start = isset($start) ? $start : 0;
            $limit  = isset($limit)  ? $limit + 1  : 11;
            $order = $order->offset($start)->limit($limit);
            $order = $order->andwhere(['M.vendor_id' => yii::$app->user->id]); //change by rajesh

            $order = $order->orderBy('O.i_date DESC')->all();

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

            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]['time'] = $value->order->i_date;
                    $result['order_list'][$i]['status'] = $value->order->status;
                    $result['order_list'][$i]['order_description'] = $value->product->title;
                    $result['order_list'][$i]['brand'] = $value->product->brand->brand_name;
                    $result['order_list'][$i]['brand_image'] = $value->product->brand->brand_image ? Url::to('@web/' . $value->product->brand->brand_image, true) : '';
                    $result['order_list'][$i]['quantity'] = $value->quantity;
                    $result['order_list'][$i]['total_price'] = number_format($value->order->total_price, 2);
                    $result['order_list'][$i]['price'] = number_format($value->unit_price, 2); //changed by rajesh on 13 june 2018
                    $result['order_list'][$i]['customer_name'] = $value->order->customer->user_name;
                    $result['order_list'][$i]['customer_image'] = $value->order->customer->image ? Url::to('@web/' . $value->order->customer->image, true) : '';
                    $result['order_list'][$i]['rider_name'] = $value->order->rider->user_name;
                    $result['order_list'][$i]['rider_image'] = $value->order->rider->image ? Url::to('@web/' . $value->order->rider->image, true) : '';
                    $i++;
                }

                $sub_on_off = Setting::find()->where(['key' => 'enable_subscription'])->one()->value;
                $result['is_expired'] = 'N';
                if ($sub_on_off == 'on')
                    $result['is_expired'] = 'N';
                else {
                    if ($data->subscription_expired_date <= time()) {
                        $result['is_expired'] = 'Y';
                    } else {
                        $subscribed = UserSubscription::find()->where(['user_id' => yii::$app->user->id, 'is_expired' => 'N'])->one();
                        if ($subscribed != array()) {
                            $result['is_expired'] = 'N';
                        } else {
                            $result['is_expired'] = 'Y';
                        }
                    }
                }


                $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);
        }
    } //Dashboard end here

    public function actionTransaction()
    {

        $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);

            //For Today's Transaction
            if ($type == 'T') {
                $start_date = date('Y-m-d', time());
                $start_date = strtotime($start_date . ' 00:00:00');
                $end_date = date('Y-m-d', time());
                $end_date = strtotime($end_date . ' 23:59:59');
            }
            //For Week's Transaction
            if ($type == 'W') {
                $date = date(yii::$app->params['datetimeformat1']);
                // parse about any English textual datetime description into a Unix timestamp 
                $ts = strtotime($date);
                // find the year (ISO-8601 year number) and the current week
                $year = date('o', $ts);
                $week = date('W', $ts);

                $last7days = $this->getLastNDays(7);

                $i = 0;
                foreach ($last7days as $last7daysval) {
                    $week_timestamp['week'][$i]['start'] = strtotime($last7daysval);
                    $week_timestamp['week'][$i]['end'] = strtotime($last7daysval . ' 23:59:59');
                    $week_timestamp['week'][$i]['day'] = date("D", strtotime($last7daysval));
                    $i++;
                }

                $j = 0;

                $start_date = date('Y-m-d', $week_timestamp['week'][0]['start']);
                $start_date = strtotime($start_date . ' 00:00:00');
                $end_date = date('Y-m-d', $week_timestamp['week'][6]['end']);
                $end_date = strtotime($end_date . ' 23:59:59');

                /**
                 * Take date from app developer bcos they passing date whole the time
                 */
                if (
                    isset($_REQUEST['from_date']) && $_REQUEST['from_date'] != '' &&
                    isset($_REQUEST['to_date']) && $_REQUEST['to_date'] != ''
                ) {
                    $start_date = $_REQUEST['from_date'];
                    $end_date   = $_REQUEST['to_date'];
                }
            }
            //For Custom date's Transaction
            if ($type == 'C') {
                $start_date = date('Y-m-d ', $from_date);
                $start_date = strtotime($start_date . ' 00:00:00');
                $end_date = date('Y-m-d', $to_date);
                $end_date = strtotime($end_date . ' 23:59:59');
            }

            $total_order = Order::find()->where(['vendor_id' => yii::$app->user->id, 'status' => ['7']])
                ->andwhere(['between', 'i_date', $start_date, $end_date]);

            /**
             * Admin Commision will come from admin setting
             */
            $admin_commision = Setting::findOne(['key' => 'admin_fee'])->value;

            $earning = Order::find()->where(['vendor_id' => yii::$app->user->id, 'status' => ['7']])
                ->andwhere(['between', 'i_date', $start_date, $end_date])
                ->sum('total_price');
            $result['total_earning'] = (float) $earning;
            $result['admin_commision']  = (float) $admin_commision * $earning / 100;
            $result['net_earning']  = (float) ($earning - ($admin_commision * $earning / 100));
            $result['admin_percentage']  = $admin_commision;

            $cash = Order::find()->where(['vendor_id' => yii::$app->user->id, 'status' => ['7']])
                ->andwhere(['between', 'i_date', $start_date, $end_date])->andwhere(['payment_status' => 'C'])
                ->sum('total_price');

            $online = Order::find()->where(['vendor_id' => yii::$app->user->id, 'status' => ['7']])
                ->andwhere(['between', 'i_date', $start_date, $end_date])->andwhere(['payment_status' => 'O'])
                ->sum('total_price');

            $result['cash']  = (float) $cash;
            $result['online']  = (float) $online;

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

            $total_order = $total_order->orderBy('i_date DESC')->all();

            // die(var_dump($total_order));


            if ($total_order) {


                if ($total_order) {
                    $i = 0;
                    foreach ($total_order as $key => $value) {
                        $result['transaction_history'][$i]['id'] = $value->id;
                        $result['transaction_history'][$i]['date'] = $value->i_date;
                        $result['transaction_history'][$i]['total_price'] = number_format($value->total_price, 2);
                        $result['transaction_history'][$i]['payment_mode'] = $value->payment_status == 'O' ? 'Online' : 'Cash';
                        $i++;
                    }

                    $result['is_last'] = 'Y';
                    if ($i >= $limit) {
                        unset($result['transaction_history'][$i - 1]);
                        $result['is_last'] = 'N';
                    }
                    return Yii::$app->apifunction->setResponse('success_transaction_history', true, 200, 200, $result);
                }
            } else {
                $result['transaction_history'] = [];
                return Yii::$app->apifunction->setResponse('error_no_order_found', true, 200, 200, $result);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    } //Transaction 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

    // below code for the send pdf (report) of riders - chirag  and edit by faizan//
    public function actionReportPdf()
    {
        $this->layout = false;
        /*insert all required veriables*/
        $required_objs = ['rider_ids', 'start_date', 'end_date', 'reports'];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            extract($_POST);

            $query = Order::find()->alias('O');
            $query->where(['O.rider_id' => isset($_REQUEST['rider_ids']) ? explode(',', $_REQUEST['rider_ids']) : null]);

            if ($type == 1) // for delivered
                $query->andwhere(['O.status' => ['7']]);
            else  //for cancel and reject
                $query->andwhere(['O.status' => ['8', '9']]);

            $query->joinWith(['customer', 'vendor', 'add', 'rider', 'details', 'details.product', 'details.brand'])->orderBy('O.id desc');

            if (isset($start_date) && $start_date != null) {
                $query =  $query->andFilterWhere(['>=', 'O.i_date', $start_date]);
            }
            if (isset($end_date) && $end_date != null) {
                $query =  $query->andFilterWhere(['<=', 'O.i_date', $end_date]);
            }
            $data = $query->all();

            $filename = 'rider.pdf';
            $dompdf = new Dompdf(array('enable_remote' => true));
            // $html = $this->renderPartial('rider.php',['request_model'=>$data]);
            $html = $this->renderPartial('rider.php', ['data' => $data, 'start_date' => $start_date, 'end_date' => $end_date]);
            $dompdf->loadHtml($html, 'UTF-8');
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();

            //   set_time_limit(5000);
            $file_to_save = Yii::getAlias('@webroot') . '/report/' . $filename;
            file_put_contents($file_to_save, $dompdf->output());


            $url = Yii::$app->common->normalUploadpdf($filename, $file_to_save);


            //check 22 file exists then send by email
            $id = Yii::$app->user->id;

            $data = Users::findOne($id);
            if (isset($data) && $data != array()) {
                Yii::$app->common->sendemail2($data->email, $data->user_name, $url, 'reports');

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

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

            $this->generatereport();

            //check 22 file exists then send by email
            $id = Yii::$app->user->id;
            $data = Users::findOne($id);
            if (isset($data) && $data != array()) {

                $link = Yii::getAlias('@webroot') . '/report/' . Yii::$app->user->id . ".xls";
                Yii::$app->common->sendemail2($data->email, $data->user_name, $link, 'reports');
                //Yii::$app->common->sendemail($data->email,$data->user_name,$link,'emailverify');
            }
            return Yii::$app->apifunction->setResponse('report_send', true, 200, 200);
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    } //Report  end here

    public function Generatereport()
    {

        extract($_POST);

        $query = Order::find()->alias('O');
        $query->where(['O.vendor_id' => yii::$app->user->id]);

        if (isset($type) && $type == 1) // for delivered
            $query->andwhere(['O.status' => ['7']]);
        else  //for cancel and reject
            $query->andwhere(['O.status' => ['8', '9']]);

        $query->joinWith(['customer', 'vendor', 'add', 'rider']);

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


        if (isset($start_date) && $start_date != null) {
            $query = $query->andFilterWhere(['>=', 'O.i_date', $start_date]);
        }
        if (isset($end_date) && $end_date != null) {
            $query =  $query->andFilterWhere(['<=', 'O.i_date', $end_date]);
        }

        $data =  $query->orderBy('i_date desc')->all();

        include Yii::getAlias('@vendor') . '/PHPExcel/Classes/PHPExcel/IOFactory.php';
        include Yii::getAlias('@vendor') . '/PHPExcel/Classes/PHPExcel/Writer/Excel2007.php';
        include Yii::getAlias('@vendor') . '/PHPExcel/Classes/PHPExcel/Worksheet/MemoryDrawing.php';

        $filename = 'Rider_report-' . date('_d-m-Y') . '.xls';
        $lastCol = 'H';
        $objPHPExcel = new \PHPExcel();
        $title = "Rider Report";

        if (isset($start_date) && $start_date != null && isset($end_date) && $end_date != null) {
            $title = "Rider Report - " . date('d-m-Y', $start_date) . " to " . date('d-m-Y', $end_date);
        }

        $objSheet = $objPHPExcel->getActiveSheet();
        $objSheet->setTitle('Rider_report');
        $objSheet->getStyle('A1:' . $lastCol . '1')->getFont()->setBold(true)->setSize(12);

        $objPHPExcel->setActiveSheetIndex(0);

        $rowCount = 1;
        $objPHPExcel->getActiveSheet()->getDefaultRowDimension(1)->setRowHeight(25);
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);

        // $objPHPExcel->getActiveSheet()->getDefaultRowDimension(1)->setRowHeight(25);
        // $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
        // $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(-1);

        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(false)->setWidth(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('A')->setRowHeight(40);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(false)->setWidth(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('B')->setRowHeight(40);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(false)->setWidth(10);
        $objPHPExcel->getActiveSheet()->getRowDimension('C')->setRowHeight(40);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(false)->setWidth(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('D')->setRowHeight(40);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(false)->setWidth(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('E')->setRowHeight(40);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(false)->setWidth(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('F')->setRowHeight(40);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(false)->setWidth(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('G')->setRowHeight(40);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(false)->setWidth(15);
        $objPHPExcel->getActiveSheet()->getRowDimension('H')->setRowHeight(40);


        $objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, $title);
        $objPHPExcel->getActiveSheet()->mergeCells('A' . $rowCount . ':' . $lastCol . $rowCount);
        $objSheet->getStyle('A' . ($rowCount))->getFont()->setBold(true);
        $rowCount++;

        $objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, 'Rider Details');
        $objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, 'Product Details');
        $objPHPExcel->getActiveSheet()->SetCellValue('C' . $rowCount, 'Order ID');
        $objPHPExcel->getActiveSheet()->SetCellValue('D' . $rowCount, 'Amount (KSH)');
        $objPHPExcel->getActiveSheet()->SetCellValue('E' . $rowCount, 'Delivery Adrress');
        $objPHPExcel->getActiveSheet()->SetCellValue('F' . $rowCount, 'Customer Info');
        $objPHPExcel->getActiveSheet()->SetCellValue('G' . $rowCount, 'Date & Time');
        $objPHPExcel->getActiveSheet()->SetCellValue('H' . $rowCount, 'Order Status');

        $objSheet->getStyle('A' . $rowCount . ':' . $lastCol . $rowCount)->getFont()->setBold(true);

        $rowCount++;
        $totalprice = 0;

        if (isset($data) && $data != null) {
            foreach ($data as $list) {

                $objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, ucfirst($list->rider->user_name) . "\r" . $list->rider->country_code . ' ' . $list->rider->mobile_number . "\r" . $list->rider->email);

                $product_detail = "";

                if (isset($list->details) && $list->details != null) {
                    foreach ($list->details as $key => $detail) {
                        if (isset($detail->product) && $detail->product != null) {
                            $type = "";
                            if (isset($detail->brand) && $detail->brand != null)
                                $type .= " " . $detail->brand->brand_name;
                            if ($detail->product->product_type == 'C')
                                $type .= " Complete";
                            if ($detail->product->product_type == 'R')
                                $type .= " Refilling";
                            if ($detail->product->product_type == 'O')
                                $type .= " Outright";

                            $product_detail .= $type . " " . $detail->product->title . " X " . $detail->quantity . "\n";
                        }
                    }
                }

                $objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, $product_detail);

                $objPHPExcel->getActiveSheet()->SetCellValue('C' . $rowCount, "VT" . $list['id']);

                $objPHPExcel->getActiveSheet()->SetCellValue('D' . $rowCount, number_format((float) $list->total_price, 2));
                $objPHPExcel->getActiveSheet()->getStyle('D' . $rowCount)->getNumberFormat()->setFormatCode('#,##0.00');

                $totalprice += $list->total_price;

                $customer_address = "";
                if (isset($list->add) && $list->add->address != '')
                    $customer_address =  $list->add->address;
                $objPHPExcel->getActiveSheet()->SetCellValue('E' . $rowCount, $customer_address);


                $customer_name = "";
                if (isset($list->add) && $list->add->full_name != '')
                    $customer_name =  $list->add->full_name;

                if (isset($list->add) && $list->add->country_code != null)
                    $customer_name .= "\n" . $list->add->country_code . " " . $list->add->mobile_number;

                $objPHPExcel->getActiveSheet()->SetCellValue('F' . $rowCount, $customer_name);


                $objPHPExcel->getActiveSheet()->SetCellValue('G' . $rowCount, isset($list['i_date']) ? date(Yii::$app->params['datetimeformat2'], $list['i_date']) : '');

                $orderStatus = Yii::$app->common->orderStatus();
                if ($list->status != null)
                    $orderStatus = $orderStatus[$list->status];
                else
                    $orderStatus = "NA";

                $objPHPExcel->getActiveSheet()->SetCellValue('H' . $rowCount, $orderStatus);

                $rowCount++;
            }
        }
        $objPHPExcel->getActiveSheet()->SetCellValue('C' . $rowCount, 'Grand Total');
        $objSheet->getStyle('C' . ($rowCount))->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->SetCellValue('D' . $rowCount, number_format($totalprice, 2));
        // $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount,'Notes');
        $objSheet->getStyle('A' . ($rowCount))->getFont()->setBold(true);
        // $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount,isset($_POST['reports'])?$_POST['reports']:'');
        $objPHPExcel->getActiveSheet()->getStyle('D' . $rowCount)->getNumberFormat()->setFormatCode('#,##0.00');
        $objSheet->getStyle('D' . ($rowCount))->getFont()->setBold(true);
        $objSheet->getStyle('A1:' . $lastCol . ($rowCount - 1))->applyFromArray(array('borders' => array('allborders' => array('style' => \PHPExcel_Style_Border::BORDER_THIN, 'color' => array('rgb' => '000')))));
        $objSheet->getStyle('A1:' . $lastCol . $rowCount)->getAlignment()->applyFromArray(array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,));


        $objPHPExcel->getActiveSheet()->getStyle('E3:' . $lastCol . ($rowCount - 1))->getAlignment()->setWrapText(true);

        for ($i = 3; $i < $rowCount; $i++) {
            $objPHPExcel->getActiveSheet()->getRowDimension($i)->setRowHeight(40);
        }


        header('Content-type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        // header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');

        //Delete previous file if exist allready 

        if (file_exists(Yii::getAlias('@webroot') . '/report/' . Yii::$app->user->id . ".xls")) {

            unlink(yii::getAlias('@webroot' . "/report/" . Yii::$app->user->id . ".xls"));
        }




        $my_excel_filename = Yii::getAlias('@webroot') . '/report/' . Yii::$app->user->id . ".xls";

        $gdImage = '';
        $my_excel_filename = Yii::getAlias('@webroot') . '/report/' . Yii::$app->user->id . ".xls";

        $image_bg = Setting::find()->where(['key' => 'admin_image'])->one();
        if ($image_bg) {
            if (file_exists(Yii::getAlias('@webroot') . '/' . $image_bg->value)) {
                $gdImage = Url::to('@web/' . $image_bg->value, true);
            }
        }
        if ($gdImage != '')
            $gdImage = imagecreatefrompng($gdImage);
        else
            $gdImage = imagecreatefrompng(Url::to('@web/' . 'img/logo-color.png', true));

        /**
         * I will check this one letter
         */
        // $style = array(
        //     'alignment' => array(
        //         'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
        //     )
        // );


        // $gdImage = imagecreatefrompng('img/logo-color.png');
        // // Add a drawing to the worksheetecho date('H:i:s') . " Add a drawing to the worksheet\n";
        // $objDrawing = new \PHPExcel_Worksheet_MemoryDrawing();
        // $objDrawing->setName('Sample image');$objDrawing->setDescription('Sample image');
        // $objDrawing->setImageResource($gdImage);
        // $objDrawing->setRenderingFunction(\PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG);
        // $objDrawing->setMimeType(\PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
        // $objDrawing->setResizeProportional(false);
        // $objDrawing->setHeight(53);


        // $objDrawing->setWidthAndHeight(50,150);
        // $objDrawing->setResizeProportional(true);

        // $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
        // $objSheet->getStyle("A1:E1")->applyFromArray($style);
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save($my_excel_filename);
    }

    public function actionCronjobforstock()
    {

        /**
         * First of all i have to get all stocks and there vendor ids
         */
        $reminder = ArrayHelper::map(Userstock::find()->all(), 'user_id', 'quantity');

        foreach ($reminder as $user_id => $quantity) {

            $stock = Stock::find()->where(['user_id' => $user_id])
                ->andwhere(['<=', 'quantity', $quantity])
                ->one();
            if ($stock) {
                $stocks[$user_id] = $stock->product_id;
            }
        }
        if ($stocks) {


            foreach ($stocks as $user_id => $product_id) {

                /** 
                 * send stock notification to all vendors
                 */
                $noti = new Notification;
                $noti->from_user = 0;
                $noti->to_user = $user_id;
                $noti->order_id = $product_id;
                $noti->notification_type = 'stock_reminder';
                $noti->message = 'Product stock reminder notification';
                $noti->type = 'V';

                $noti->i_by = 0;
                $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'] = 'stock_reminder';
                $body_a['data']['product_id'] = $product_id;
                $body_a['data']['message'] = 'Product stock reminder notification';

                $body_i = array();
                $body_i['data'] = array('alert' => 'Product stock reminder notification');
                $body_i['data']['badge'] = 1;
                $body_i['data']['product_id'] = $product_id;
                $body_i['data']['notification_type'] = 'stock_reminder';
                $body_i['data']['sound'] = 'default';
                $body_i['data']['message'] = 'Product stock reminder notification';
                $body_i['data']['alert'] = 'Product stock reminder notification';
                $body_i['data']['text'] = 'Product stock reminder notification';


                $user = Users::find()->where(['is_deleted' => "N", 'is_active' => "Y", 'notification_enabled' => 'Y', 'id' => $user_id])->select(['id', 'is_deleted', 'is_active', 'user_type', 'notification_enabled', 'is_online'])->one();

                if ($user) {
                    $uDeviceDetail = Userdevices::find()->where(['user_id' => $user->id])->orderby("last_login_datetime DESC")->one();
                }
                if (!empty($uDeviceDetail)) {
                    if ($uDeviceDetail['device_type'] == 'A') {

                        yii::$app->common->pushnotification_android($uDeviceDetail['device_id'], $body_a);
                    }
                    if ($uDeviceDetail['device_type'] == 'I') {
                        yii::$app->common->pushnotification_iphone($uDeviceDetail['device_id'], $body_i);
                    }
                }
            } //foreach end here


        } //if end of stocks
    } //main function end here

    public function actionCreatetimeslot(){
        $required_objs = ['start_time','end_time'];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            extract($_POST);
            $userid = Yii::$app->user->id;
            
            $timeslots =new Deliverytimeslot();
            $timeslots->start_time = $start_time;
            $timeslots->end_time = $end_time;
            $timeslots->is_enable = "Y";
            $timeslots->vendor_id = $userid;
            $timeslots->i_by = $userid;
            $timeslots->u_by = $userid;
            $timeslots->i_date = time();
            $timeslots->u_date = time();
            $result['timeslots'] = array();
            if($timeslots->save()){

                $result['timeslots']['id'] = $timeslots->id;
                $stime = date('h:iA',strtotime($timeslots->start_time));
                $etime = date('h:iA',strtotime($timeslots->end_time));
                $result['timeslots']['time'] = $stime.'-'.$etime;
                $result['timeslots']['enabled'] = ($timeslots->is_enable=='Y')?true:false;
            }
            return Yii::$app->apifunction->setResponse('', true, 200, 200,$result);
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 200, 400);
        }
    }

    public function actionEdittimeslot(){
        $required_objs = ['id','start_time','end_time','enabled'];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            extract($_POST);
            // print_r($_POST);die;
            $userid = Yii::$app->user->id;
            $timeslots =Deliverytimeslot::find()->where(['id'=>$id])->one();
            if($timeslots){
                $timeslots->start_time = $start_time;
                $timeslots->end_time = $end_time;
                if($enabled == "true"){
                    $timeslots->is_enable = "Y";
                }else{
                    $timeslots->is_enable = "N";
                }
                $timeslots->vendor_id = $userid;
                $timeslots->u_by = $userid;
                $timeslots->u_date = time();
                $timeslots->save();
                return Yii::$app->apifunction->setResponse('timslot_update', true, 200, 200);
            }else{
                return Yii::$app->apifunction->setResponse('timslot_update_not_found', false, 200, 400);    
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 200, 400);
        }
    }

    public function actionDeletetimeslot(){
        $required_objs = ['id'];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            extract($_POST);
            $userid = Yii::$app->user->id;
            $timeslots =Deliverytimeslot::find()->where(['id'=>$id])->one();
            if($timeslots){
                $timeslots->is_deleted = 'Y';
                $timeslots->u_by = $userid;
                $timeslots->u_date = time();
                $timeslots->save();
                return Yii::$app->apifunction->setResponse('timslot_delete', true, 200, 200);
            }else{
                return Yii::$app->apifunction->setResponse('timslot_update_not_found', false, 200, 400);    
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 200, 400);
        }
    }
    
    public function actionTimeslots(){
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
        extract($_POST);
        $userid = Yii::$app->user->id;
        $timeslots = Deliverytimeslot::find()->where(['vendor_id'=>$userid,'is_deleted'=>'N','is_active'=>'Y'])->all();
        $result['timeslots'] = array();
        if(isset($timeslots)&& $timeslots != array()){
            $i = 0;
            foreach($timeslots as $time){
                $result['timeslots'][$i]['id'] = $time->id;
                $result['timeslots'][$i]['start_time'] = $time->start_time;
                $result['timeslots'][$i]['end_time'] = $time->end_time;
                $result['timeslots'][$i]['enabled'] = ($time->is_enable=='Y')?true:false;
                $i++;
            }
        }
        return Yii::$app->apifunction->setResponse('', true, 200, 200,$result);
    }

}
