<?php

namespace app\modules\api\v3\controllers;

use Yii;
use yii\helpers\Url;
use yii\rest\ActiveController;
use yii\helpers\ArrayHelper;
use yii\filters\auth\HttpBearerAuth;
use \Exception;
use app\models\Userdevices;
use app\models\Orderlog;
use app\models\Order;
use app\models\Notification;
use app\models\Users;
use app\models\Brand;
use app\models\Zipcode;
use app\models\State;
use app\models\OrderDetail;
use app\models\Size;
use app\models\Product;
use app\models\Reason;
use app\models\UserReview;
use app\models\Review;
use app\models\Stock;
use app\models\Promocode;
use app\models\Cart;
use app\models\Contactus;
use app\models\UserAddress;
use app\models\Setting;
use app\models\Vendorhistory;
use app\models\Bankdetail;
use app\models\Userstore;
use app\models\Uservendor;
use app\models\Deliverytimeslot;
use yii2\web\Request;
use yii\filters\AccessControl;
use app\models\Paymentresponse;
use app\models\Usertype_master;
use app\models\Expertize;

class UserController extends ActiveController
{
    public $modelClass = 'app\modules\api\v1\models\Users';

    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' => [
                'registersnew', 'gettoken', 'gettechuser', 'getcms', 'ipayresponse', 'paymentresponsesuccess', 'orderpayment' ,'paymentresponse', 'testsms', 'vendors',/*'login','sociallogin','register','forgotpassword' ,'resetpassword','verifyotp','resendotp','getcms','getcategories','getitems','getstores','getavailabledrivercount',*/
                'emailexist', 'resendemail','userexpertize', 'testfcmv1'
            ],
            'class' => HttpBearerAuth::className(),

        ];

        return $behaviors;
    }

    public function actionTestFcmV1()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $token = Yii::$app->request->post('device_token');
        $platform = Yii::$app->request->post('platform', 'android');

        $body = Yii::$app->request->post('body', []);

        if (empty($body)) {
            $body = [
                'data' => [
                    'notification_type' => 'test_notification',
                    'message' => 'This is FCM v1 test push',
                    'title' => 'FCM Test',
                    'body' => 'This is FCM v1 test push',
                    'is_accepted' => 'N',
                    'badge' => 1,
                    'sound' => 'default',
                ]
            ];
        }

        $result = Yii::$app->mycomponent->testFcmV1Push($token, $body, strtolower($platform));

        return [
            'status' => true,
            'result' => $result,
        ];
    }

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

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

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

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

        $usertype = Usertype_master::find()->where(['deleted_at' => null])->all();

        $result['usertype'] = $usertype;

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

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

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

        $result['userexpertize'] = $usertype;

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

    public function actionGettechuser()
    {
        extract($_POST);
        $tech_charge = Setting::find()->where(['key' => 'tech_charge'])->one()->value;
        $sett_dis = Setting::find()->where(['key' => 'distance'])->one();

        if ($sett_dis) {
            $distance = $sett_dis->value;
        } else $distance = 100; //static distance 10km

 //    $distance = 100000000;

        $idarray = Usertype_master::find()->select('id')->where(['deleted_at' => null])->andWhere(['<>', 'id', 1])->asArray()->all();
        $idarray = array_column($idarray, 'id');

        $technicians = Users::find()->select("*,(6371 * acos( cos( radians($lat) ) * cos( radians( latitude) ) * cos( radians( longitude) - radians($long) ) + sin( radians($lat) ) * sin( radians( latitude ) ) ) ) AS distance")
            ->where([ 'is_online' => 'Y', 'notification_enabled' => 'Y', 'is_request_recieve' => 'N', 'is_deleted' => 'N', 'is_active' => 'Y', 'profile_status' => 'A'])
            ->andWhere(['NOT', ['latitude' => null, 'longitude' => null]])
            ->andWhere(['in', 'user_type', $idarray])
            ->andHaving("distance < $distance")->orderBy(['distance' => SORT_ASC])->all();

            // 'is_online' => 'Y', 'notification_enabled' => 'Y', 'is_request_recieve' => 'N',

        // if (empty($technicians)) { 'is_connected' => 'Y',
        //     return Yii::$app->apifunction->setResponse('No nearest technician found, We are coming to your location soon', false, 400, 400);
        // }

        // $technicians = Users::find()
        //     ->where(['is_online' => 'Y','is_connected' => 'Y', 'is_request_recieve' => 'N', 'is_deleted' => 'N', 'is_active' => 'Y', 'profile_status' => 'A'])
        //     ->andWhere(['in', 'user_type', $idarray])
        //     ->all();

        //, 'mobile_verified' => 'Y'
        $result['tech_charge'] = $tech_charge;
        if (count($technicians) > 0){
            $result['technician'] = $technicians;
        }
        else
            $result['technician'] = [];
        return Yii::$app->apifunction->setResponse('', true, 200, 200, $result);
    }

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

    public function actionLogin()
    {

        $required_objs = ['mobile_number', 'password', 'device_id', 'device_type'];
        $login_type = 'n';

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

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


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


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

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

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

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

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

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

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

        return $result;
    }

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

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

    public function actionRegistersnew()
    {

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


            if (!empty($email)) {

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

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

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


                $user = new Users();

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

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

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

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

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

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

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


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

                if ($user->save(false)) {
                    ///*send mail via common code you can send via your default code too*/
                    // Yii::$app->apifunction->sendMail('Email Verification', $user->email_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;
    }

    public function actionForgotpassword()
    {
        $required_objs = ['email'];

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

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

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

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

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

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

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

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

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

            $user_type = 'U';

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

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

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


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

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

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

    public function actionVerifyotp()
    {
        //insert all required veriables
        $required_objs = ['otp', 'country_code', 'mobile_number'];
        $login_type = 'n';

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

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

                    return Yii::$app->apifunction->setResponse('mobile_verified_successfully', true, 200, 200, $result);
                    // if($type=='f')//forgot password
                    // {
                    // return Yii::$app->apifunction->setResponse('mobile_verified_successfully',true,200,200);
                    // }
                    // if($type=='e')//From edit profile need to change new phone number
                    // {
                    //     //$model= Users::find()->select('*')->where(['is_deleted'=>'N','id'=>Yii::$app->user->identity->id])->one();
                    //     $data->country_code = $country_code;
                    //     $data->contact_number = $contact_number;
                    //     $data->u_by = Yii::$app->user->identity->id;
                    //     $data->u_date = date('Y-m-d H:i:s');
                    //     $data->save(false);
                    //     $result = Yii::$app->apifunction->apiLogin($data,$device_id, $device_type, '','',false);
                    //     return Yii::$app->apifunction->setResponse('mobile_verified_successfully',true,200,200,$result);
                    // }
                    // else
                    // {
                    //     $result = Yii::$app->apifunction->apiLogin($data,$device_id, $device_type, '','',false);
                    //     return Yii::$app->apifunction->setResponse('mobile_verified_successfully',true,200,200,$result);
                    // }
                } else {
                    return Yii::$app->apifunction->setResponse('mobile_verification_mismatch', false, 200, 400);
                }
            } else {
                return Yii::$app->apifunction->setResponse('error_forgot_password_id_not_found', false, 200, 400);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 200, 400);
        }
        return $result;
    }

    public function actionResendemail()
    {
        $required_objs = ['email'];
        /*CHECK REQUIRED POST VERIABLES WITH VALUES*/
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            extract($_POST);
            $data = Yii::$app->apifunction->getUserDetailOnEmail($email, 'U');
            if (isset($data) && $data != array()) {
                $token = $type = '';

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

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

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

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

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

            $result['terms_and_conditions'] = 'http://admin.gas4u.com.ng/gas4you/web/admin/default/termsandconditions';
            $result['privacy_policy'] = 'http://admin.gas4u.com.ng/gas4you/web/admin/default/privaypolicy';
            $result['faqs'] = 'http://admin.gas4u.com.ng/gas4you/web/admin/default/faq';

            $result['about_us'] = 'http://admin.gas4u.com.ng/gas4you/web/admin/default/about';
            return Yii::$app->apifunction->setResponse('', true, 200, 200, $result);
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }


        return $result;
    }

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

    public function actionUpdateprofile()
    {

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


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

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

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

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

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

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

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

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

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

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

                    //Yii::$app->common->sendsms($data->country_code.$data->contact_number,'Welcome to '.Yii::$app->params['appName'].', One Time Password(OTP) to verify your phone number is :'.$otp);;
                    if (isset($data->email) && $data->email != null) {
                        $content = 'Welcome to ' . Yii::$app->params['appName'] . ', One Time Password(OTP) to verify your phone number is :' . $otp;
                        Yii::$app->common->otpemail($data->email, $data->user_name, $content, 'otp_mail');
                    }
                    $data->mobile_verified = 'N';
                }
            }
            if (isset($_FILES['profile_image']['tmp_name']) && $_FILES['profile_image']['tmp_name'] != null) {
                $image = $_FILES['profile_image']['name'];
                $tmp = $_FILES['profile_image']['tmp_name'];
                $ext = substr(strrchr($image, "."), 1);
                $fileName = md5(rand() * time()) . ".$ext";

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

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

            //update driver detail


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

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

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

    /*API FOR CLEAR BADGE*/
    public function actionClearbadge()
    {

        extract($_POST);

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

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

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

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

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

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

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


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


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

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

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

                /**
                 * Save new Mobile number
                 */

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

                $model->mobile_verified = 'N';

                $model->save(false);

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

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

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


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

    public function actionNotificationsetting()
    {

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


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

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


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


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

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

    public function actionAddeditaddress()
    {

        $this->layout = false;
        /*insert all required veriables*/
        $required_objs = ['full_name', 'mobile_number', 'country_code', 'house_number', 'estate', 'landmark', 'address', 'state', 'zipcode', 'is_default', 'latitude', 'longitude'];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            //check user is guest or not
            // Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
            extract($_POST);
            $userid = Yii::$app->user->id;
            if (isset($address_id) && $address_id != null) {
                $model = UserAddress::findOne($address_id);
                $model->full_name = isset($full_name) ? $full_name : '';
                $model->mobile_number = isset($mobile_number) ? $mobile_number : '';
                $model->country_code = isset($country_code) ? $country_code : '';
                $model->house_number = isset($house_number) ? $house_number : '';
                $model->estate = isset($estate) ? $estate : '';
                $model->area = isset($area) ? $area : '';
                $model->landmark = isset($landmark) ? $landmark : '';
                $model->address = isset($address) ? $address : '';
                $model->zipcode = isset($zipcode) ? $zipcode : '';
                $model->state = isset($state) ? $state : '';
                // $model->is_default = 'N';
                $model->latitude = isset($latitude) ? $latitude : '';
                $model->longitude = isset($longitude) ? $longitude : '';
                $model->u_by = yii::$app->user->id;
                $model->u_date = time();

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

                    return Yii::$app->apifunction->setResponse('address_update_successfully', true, 200, 200);
                }
            } else {

                $model = new UserAddress();
                $model->full_name = isset($full_name) ? $full_name : '';
                $model->user_id = $userid;
                $model->mobile_number = isset($mobile_number) ? $mobile_number : '';
                $model->country_code = isset($country_code) ? $country_code : '';
                $model->house_number = isset($house_number) ? $house_number : '';
                $model->estate = isset($estate) ? $estate : '';
                $model->area = isset($area) ? $area : '';
                $model->landmark = isset($landmark) ? $landmark : '';
                $model->address = isset($address) ? $address : '';
                $model->zipcode = isset($zipcode) ? $zipcode : '';
                $model->state = isset($state) ? $state : '';

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

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


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

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

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

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

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


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


        $addresses = $addresses->all();

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

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

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

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

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

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

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

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

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

    public function actionDeleteaccount()
    {

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

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


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

            $model->is_deleted = 'Y';

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

    public function actionBrandlist()
    {

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

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

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

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

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

        $brand = $brand->all();

        if ($brand) {
            $i = 0;

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

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

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

    public function actionPurchaselist()
    {

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

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

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

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

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

                    $stocklst = 0;
                    $stocks_list = Stock::find()->where(['product_id' => $value->id, 'user_id' => $value->u_by]);
                    if($value->size_id != null && $value->size_id != ""){
                        $stocks_list = $stocks_list->andWhere(['size_id' => $value->size_id])->one();
                    }
                    else{
                        $stocks_list = $stocks_list->one();
                    }

                    if($stocks_list->quantity > 0 ){
                        $stocklst = $stocks_list->quantity;
                    }

                    $result['purchase_list'][$i]['id'] = (int)$value->id;
                    //                        $result['purchase_list'][$i]['discount_price'] = number_format($value->price - (($value->price * $value->discount / 100)), 2);
                    $result['purchase_list'][$i]['discount_price'] = number_format($value->price - (($value->price * $value->discount_percentage / 100)), 2);
                    // $result['purchase_list'][$i]['discount_price']    = round($value->price -  (($value->price*$value->discount/100)),2);
                    $result['purchase_list'][$i]['discount'] = $value->discount ? $value->discount : "0";
                    $result['purchase_list'][$i]['title'] = $value->title;
                    $result['purchase_list'][$i]['product_id'] = $value->id;
                    // $result['purchase_list'][$i]['brand_id'] = $value->brand_id;
                    $result['purchase_list'][$i]['size_id'] = $value->size_id ? $value->size_id : '';
                    $result['purchase_list'][$i]['size'] = $value->size;
                    $result['purchase_list'][$i]['size_image'] = '';
                    $result['purchase_list'][$i]['price'] = number_format($value->price, 2);
                    $result['purchase_list'][$i]['stock'] = $stocklst;
                    $result['purchase_list'][$i]['more_details'] = isset($value->description) ? $value->description : "";

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

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

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

    public function actionNotificationlist()
    {

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

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

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

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

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

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


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


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

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

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

            if ($i >= $limit) {
                unset($result['notifications'][$i - 1]);
                $result['is_last'] = 'N';
            }
            return Yii::$app->apifunction->setResponse('success_notification_list', true, 200, 200, $result);
        } else {
            $result['notification_list'] = [];
            return Yii::$app->apifunction->setResponse('error_no_notificatin_not_found', true, 200, 200, $result);
        }
    } //Notification list end here

    public function actionClearnotificationlist()
    {

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

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

        //Lets first get the all notification list

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

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

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

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

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

    public function actionCancelorder()
    {

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

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

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

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


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

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

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

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

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

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


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

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


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

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

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


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

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

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

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

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

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

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


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

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

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

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

                    if ($device_token_iphone != array())
                        Yii::$app->mycomponent->pushnotification_iphone_array($device_token_iphone, $body_i);
                } else {
                    $noti = new Notification;
                    $noti->from_user = Yii::$app->user->id;
                    $noti->order_id = $order_id;

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

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

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

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

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

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


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

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

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

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

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

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

    public function actionRating()
    {

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

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

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

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

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

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

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

    public function actionAddtocart()
    {

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

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

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

            // if ((isset($size_id) && $size_id != null) && (isset($brand_id) && $brand_id != null)) {
            //     $product = Product::find()->where(['size_id' => $size_id, 'product_type' => 'R', 'brand_id' => $brand_id, 'is_active' => 'Y', 'size' => isset($cylinder_size) ? $cylinder_size : null])->andWhere(['is_active' => 'Y', 'is_deleted' => 'N'])->one();
            //     if (!$product) {
            //         return Yii::$app->apifunction->setResponse('error_in_brand_with_this_size', false, 400, 400);
            //     }
            // }
            $cart = new Cart;
            $cart->user_id = $userId;
            $cart->product_id = isset($product_id) ? $product_id : null;
            // $cart->brand_id   = isset($brand_id) ? $brand_id : null;
            $cart->size_id = isset($size_id) ? $size_id : null;
            $cart->quantity = isset($quantity) ? $quantity : 1;
            $cart->is_refilling = $is_refilling;
            $cart->cylinder_size = isset($cylinder_size) ? $cylinder_size : null;
            $cart->i_by = $userId;
            $cart->i_date = time();

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

    public function actionCartlist()
    {

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

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

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

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

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


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

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

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

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

                $i++;
            }

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

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

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

            $cart = Cart::find()->where(['id' => $item_id, 'is_deleted' => 'N'])->one();
            if (!$cart) {
                return Yii::$app->apifunction->setResponse('error_cart_not_found', false, 400, 400);
            }
            $cart->is_deleted = 'Y';
            $cart->u_by = $userId;
            $cart->u_date = time();
            Uservendor::updateAll(['is_deleted' => 'Y', 'u_by' => $userId, 'u_date' => time()], ['user_id' => $userId]);
            if ($cart->save(false)) {
                return Yii::$app->apifunction->setResponse('success_cart_deleted', true, 200, 200);
            } else {
                return Yii::$app->apifunction->setResponse('error_in_save', false, 400, 400);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    } //Remove cart done here

    public function actionUpdatecart()
    {

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

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

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

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

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

    public function actionApplypromocode()
    {

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

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


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

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

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

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

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


            //First get all cylinder sizes from size_master table
            $sizes = Size::find()->where(['is_deleted' => 'N', 'is_active' => 'Y'])->all();
            if ($sizes) {
                $i = 0;
                foreach ($sizes as $key => $value) {
                    $result['cylinder_size_list'][$i]['id'] = $value->id;
                    $result['cylinder_size_list'][$i]['size'] = $value->wieght;
                    $result['cylinder_size_list'][$i]['size_image'] = $value->size_image ? Url::to('@web/' . $value->size_image, true) : '';
                    $i++;
                }
            } else {
                $result['cylinder_size_list'] = [];
            }

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

            //Flate Fee set by admin
            $flat_fee = Setting::find()->where(['key' => 'flat_fee'])->one();

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

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

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

            $order = $order->orderBy('id DESC')->groupBy('order_id')->all();
            // echo "<pre>";
            // print_r($order);
            // die;
            if ($order) {
                $i = 0;
                foreach ($order as $key => $value) {
                    if ($value->product_id == 9999) {
                        if ($value->order_id != null)
                            $techname = $this->actionGettechname($value->order_id);

                        $result['order_list'][$i]['order_id'] = $value->id;
                        $result['order_list'][$i]['master_id'] = $value->order_id;
                        // $result['order_list'][$i]['order_date']  = $value->i_date;
                        $result['order_list'][$i]['order_status'] = $value->status;
                        $result['order_list'][$i]['order_description'] = "Service Booking for " . $techname;
                        $result['order_list'][$i]['brand_name'] = $techname;
                        $result['order_list'][$i]['brand_image'] = Url::to('@web/' . "img/logo-color.png", true);
                        $result['order_list'][$i]['quantity'] = $value->quantity;
                        $result['order_list'][$i]['total_price'] = number_format($value->total_price, 2);
                        $result['order_list'][$i]['order_date'] = $value->i_date;
                    } else {
                        $result['order_list'][$i]['order_id'] = $value->id;
                        $result['order_list'][$i]['master_id'] = $value->order_id;
                        // $result['order_list'][$i]['order_date']  = $value->i_date;
                        $result['order_list'][$i]['order_status'] = $value->status;
                        $result['order_list'][$i]['order_description'] = isset($value->product->title) ? $value->product->title : "";
                        $result['order_list'][$i]['brand_name'] = isset($value->brand->brand_name) ? $value->brand->brand_name : "";
                        $result['order_list'][$i]['brand_image'] = isset($value->brand->brand_image) ? Url::to('@web/' . $value->brand->brand_image, true) : '';
                        $result['order_list'][$i]['quantity'] = (string) $value->quantity;
                        $result['order_list'][$i]['total_price'] = number_format($value->total_price, 2);
                        $result['order_list'][$i]['order_date'] = $value->i_date;
                    }
                    $result['order_list'][$i]['flat_fee'] = isset($flat_fee->value) ? $flat_fee->value : 0;

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

            //Flate Fee set by admin
            $flat_fee = Setting::find()->where(['key' => 'flat_fee'])->one();

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

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

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

                $result['order_details']['total_price'] = number_format($order_master->total_price + $delivery_charge, 2);
                $result['order_details']['delivery_method'] = $order_master->delivery_method;
                $result['order_details']['flat_fee'] = isset($flat_fee->value) ? $flat_fee->value : 0;


                // 'i_by'=>yii::$app->user->id
                $order_log = Orderlog::find()->where(['order_id' => $master_id, 'status' => '8'])->one();
                if (!$order_log && $order_master->delivery_method == "H" && $order_master->rider_id != null) {
                    $rider = Users::findOne($order_master->rider_id);
                    $result['rider_info']['rider_id'] = $rider->id;
                    $result['rider_info']['rider_name'] = $rider->user_name;
                    $result['rider_info']['vehicle_number'] = $rider->motor_bike_number;
                    $result['rider_info']['latitude'] = $rider->latitude != '' ? $rider->latitude : '';
                    $result['rider_info']['longitude'] = $rider->longitude != '' ? $rider->longitude : '';
                    $result['rider_info']['mobile_number'] = $rider->country_code . ' ' . $rider->mobile_number;
                    $result['rider_info']['rider_image'] = $rider->image != '' ? Url::to('@web/' . $rider->image, true) : '';
                } else {
                    $result['rider_info']['rider_id'] = '';
                    $result['rider_info']['rider_name'] = '';
                    $result['rider_info']['vehicle_number'] = '';
                    $result['rider_info']['latitude'] = '';
                    $result['rider_info']['longitude'] = '';
                    $result['rider_info']['mobile_number'] = '';
                    $result['rider_info']['rider_image'] = '';
                }


                if (isset($order_master->vendor_id) && $order_master->vendor_id != "") {
                    $vendor = Userstore::find()->select("user_stores.*,um.rating as vendor_rating")
                        ->leftJoin('user_master um', 'um.id=user_stores.user_id')
                        ->where(['um.id' => $order_master->vendor_id])->one();
                    if (empty($vendor)) {
                        $result['vendor_details'] = json_decode("{}");
                    } else {
                        $result['vendor_details']['id'] = $vendor->user_id;
                        $result['vendor_details']['shop_name'] = $vendor->shop_name;
                        if ($vendor->vendor_type == 'R')
                            $result['vendor_details']['price'] = number_format($vendor->price, 2);
                        else
                            $result['vendor_details']['price'] = number_format($vendor->price_per_kg, 2);
                        $result['vendor_details']['latitude'] = $vendor->latitude;
                        $result['vendor_details']['longitude'] = $vendor->longitude;
                        $result['vendor_details']['location'] = $vendor->address;
                        $result['vendor_details']['logo'] = $vendor->logo ? Url::to('@web/' . $vendor->logo, true) : "";
                        $result['vendor_details']['rating'] = $vendor->vendor_rating;
                    }
                } else {
                    $result['vendor_details'] = json_decode("{}");
                }
                /**
                 * Let's cehck this driver is rated for this order
                 */
                if (isset($rider) && $rider != null)
                    $rate = UserReview::find()->where(['order_id' => $order_master->id, 'from_id' => yii::$app->user->id, 'to_id' => $rider->id, 'is_deleted' => 'N'])->one();

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

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

                $str = '';

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

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

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

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

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

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

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

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

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

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

                if ($order) {
                    $i = 0;
                    foreach ($order as $key => $value) {
                        $result['order_list'][$i]['id'] = $value->id;
                        // $result['order_list'][$i]['master_id'] = $value->order_id;
                        $result['order_list'][$i]['order_status'] = $value->status;
                        if ($value->product_id == 9999) {
                            $tech_decription = $this->actionGettechname($value->order_id);
                            $result['order_list'][$i]['title'] = "Service Booking";
                            $result['order_list'][$i]['brand_name'] = "$tech_decription";
                            $result['order_list'][$i]['brand_image'] = Url::to('@web/' . "img/logo-color.png", true);
                        } else {
                            $result['order_list'][$i]['title'] = isset($value->product->title) ? $value->product->title : "";
                            $result['order_list'][$i]['brand_name'] = isset($value->brand->brand_name) ? $value->brand->brand_name : "";
                            $result['order_list'][$i]['brand_image'] = isset($value->brand->brand_image) ? Url::to('@web/' . $value->brand->brand_image, true) : '';
                        }

                        $result['order_list'][$i]['discount_percentage'] = $value->product_discount_percentage ? $value->product_discount_percentage : 0;

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

                        $result['order_list'][$i]['quantity'] = (string) $value->quantity;
                        $result['order_list'][$i]['price'] = number_format($value->total_price, 2);
                        $result['order_list'][$i]['type'] = $value->product_type;
                        $i++;
                    }

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

    public function actionDefaultaddress()
    {

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


            extract($_POST);

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

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

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

    public function actionPrevieworder()
    {

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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


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

            $str = '';


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

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

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

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

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

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


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


            $result['is_last'] = 'Y';
            if ($i >= $limit) {
                unset($result['preview_list'][$i - 1]);
                $result['is_last'] = 'N';
            }
            return Yii::$app->apifunction->setResponse('success_preview_list', true, 200, 200, $result);
        } else {
            $result['preview_list'] = [];
            $result['discount'] = 0;
            $result['base_price'] = 0;
            $result['discount_price'] = 0;
            $result['address'] = '';
            return Yii::$app->apifunction->setResponse('error_no_order_preview_found', true, 200, 200, $result);
        }
    } //preview order end here

    public function actionPurchaseorder()
    {

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

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

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

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

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

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

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

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

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

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

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

                $order_detail = new OrderDetail;

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

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

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

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

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

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

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

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

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


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

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

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

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

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

            if ($sett_dis) {
                $distance = $sett_dis->value;
            } else $distance = 10; //static distance 10km

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

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

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

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

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

            //  die(var_dump($vendors));


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

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

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

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

            // }

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

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

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


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

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


                if (!empty($riders))
                    break;

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

            if (empty($riders)) {

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

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

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

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

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

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


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

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

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

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

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

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

            $order = new Order;

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


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

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

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

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

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

            // }

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

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

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

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

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

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

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

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

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

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


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


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


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


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


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


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

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

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

    public function actionIpayprocessing()
    {

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

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

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

            if ($order) {

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

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

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

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

    public function actionIpayresponse()
    {

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

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

                    if ($order) {

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

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


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

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

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

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

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

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


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

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

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

                        if ($device_token_iphone != array())
                            Yii::$app->mycomponent->pushnotification_iphone_array($device_token_iphone, $body_i);
                    } else {
                        return Yii::$app->apifunction->setResponse('Order not found', false, 400, 400);
                    }
                }

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

    public function actionZipcodelist()
    {
        $required_objs = ['state_id'];
        extract($_POST);
        $zipcodes = Zipcode::find()->where(['state_id' => $state_id, 'is_deleted' => 'N', 'is_active' => 'Y'])->all();

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

                $result['zipcodes'][$i]['zipcode_id'] = $zipcode->id;
                $result['zipcodes'][$i]['zipcode_area'] = $zipcode->area_name;
                $result['zipcodes'][$i]['zipcode_code'] = $zipcode->zipcode;
                $i++;
            }
            return Yii::$app->apifunction->setResponse('zipcode_list', true, 200, 200, $result);
        } else {
            $result['zipcode_list'] = [];
            return Yii::$app->apifunction->setResponse('error_zipcode_list_not_found', false, 200, 400, $result);
        }
    }

    public function actionStatelist()
    {
        $zipcodes = State::find()->where(['is_deleted' => 'N', 'is_active' => 'Y'])->all();

        if (isset($zipcodes) && $zipcodes != array()) {
            $i = 0;
            foreach ($zipcodes as $key => $zipcode) {
                $result['states'][$i]['state_id'] = $zipcode->id;
                $result['states'][$i]['state_name'] = $zipcode->state_name;
                $i++;
            }
            return Yii::$app->apifunction->setResponse('state_list', true, 200, 200, $result);
        } else {
            $result['state_list'] = [];
            return Yii::$app->apifunction->setResponse('No state list found', false, 200, 400, $result);
        }
    }

    public function actionChangepaymentmode()
    {

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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

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

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

    public function actionDeleteaddress()
    {

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

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


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

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

                $model->is_deleted = 'Y';

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

            return Yii::$app->apifunction->setResponse('response_text', false, 200, 400);
        }
    } //delete address  end here

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

    public function actionGetbankdetails()
    {
        extract($_POST);
        $userid = Yii::$app->user->id;
        // print_r($userid);
        if (isset(Yii::$app->user->id) && Yii::$app->user->id != "") {
            $model = Bankdetail::findOne(['user_id' => yii::$app->user->id]);
            if (isset($model) && $model != array()) {
                $result = array();
                $result['id'] = $model->id;
                $result['mobile_number'] = $model->mobile_pay_number;
                $result['bank_name'] = $model->bank_name;
                $result['account_name'] = $model->account_name;
                $result['account_number'] = $model->account_number;
                $result['branch'] = $model->branch;
                $result['bank_code'] = $model->bank_code;
                $result['branch_code'] = $model->branch_code;
                $result['swift_code'] = $model->swift_code;
                return Yii::$app->apifunction->setResponse('success_bank_detail', true, 200, 200, $result);
            } else {
                return Yii::$app->apifunction->setResponse('error_bankdetail_not_found', false, 200, 400);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 200, 400);
        }
    }

    public function actionVendors()
    {
        $required_objs = ['latitude', 'longitude', 'type', 'radius'];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            extract($_POST);
            //$flat_fee = Setting::find()->where(['key' => 'distance'])->one();
            //$radius = isset($flat_fee->value) ? $flat_fee->value : 5;
            $radius = 5000000;
            $start = isset($start) ? $start : 0;
            $limit = isset($limit) ? $limit + 1 : 11;
            $vendors = Userstore::find()->select("user_stores.*,um.rating as vendor_rating,( 6371 * acos( cos( radians($latitude) ) * cos( radians( user_stores.latitude) ) * cos( radians( user_stores.longitude) - radians($longitude) ) + sin( radians($latitude) ) * sin( radians( user_stores.latitude ) ) ) ) AS radius")
                ->leftJoin('user_master um', 'um.id=user_stores.user_id')
                ->where(['user_stores.vendor_type' => $type, 'um.user_type' => 'V', 'um.is_deleted' => 'N', 'um.is_active' => 'Y'])
                ->andHaving("radius < $radius")->orderBy(['radius' => SORT_ASC]);
            $vendors = $vendors->offset($start)->limit($limit)->all();
            $result['vendors'] = array();
            $result['is_last'] = 'Y';
            // print_r($vendors);die;
            if (isset($vendors) && $vendors != array()) {
                $i = 0;
                foreach ($vendors as $vendor) {
                    $result['vendors'][$i]['id'] = $vendor->user_id;
                    $result['vendors'][$i]['shop_name'] = $vendor->shop_name;
                    if ($type == 'R')
                        $result['vendors'][$i]['price'] = number_format($vendor->price, 2);
                    else
                        $result['vendors'][$i]['price'] = number_format($vendor->price_per_kg, 2);
                    $result['vendors'][$i]['latitude'] = $vendor->latitude;
                    $result['vendors'][$i]['longitude'] = $vendor->longitude;
                    $result['vendors'][$i]['location'] = $vendor->address;
                    $result['vendors'][$i]['logo'] = $vendor->logo ? Url::to('@web/' . $vendor->logo, true) : "";
                    $result['vendors'][$i]['rating'] = $vendor->vendor_rating;
                    $i++;
                }

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

    public function actionPurchaselistnew()
    {

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

            $stocks = $stocks->orderBy('id DESC')->all();
            // print_r($stocks);
            // die;
            if ($stocks) {
                $i = 0;
                foreach ($stocks as $key => $value) {
                    $stocklst = 0;
                    $stocks_list = Stock::find()->where(['product_id' => $value->id, 'user_id' => $value->u_by]);
                    if($value->size_id != null && $value->size_id != ""){
                        $stocks_list = $stocks_list->andWhere(['size_id' => $value->size_id])->one();
                    }
                    else{
                        $stocks_list = $stocks_list->one();
                    }

                    if($stocks_list->quantity > 0 ){
                        $stocklst = $stocks_list->quantity;
                    }

                    $result['purchase_list'][$i]['id'] = (int)$value->id;
                    $result['purchase_list'][$i]['discount_price'] = number_format($value->price - (($value->price * $value->discount_percentage / 100)), 2);

                    if ($value->discount_percentage != 0.0 && $value->discount_percentage != null) {
                        $result['purchase_list'][$i]['discount'] = number_format($value->discount ? $value->discount : "0", 2);
                    } else {
                        $result['purchase_list'][$i]['discount'] = 0.00;
                    }
                    // $result['purchase_list'][$i]['discount_price']    = round($value->price -  (($value->price*$value->discount/100)),2);

                    $result['purchase_list'][$i]['title'] = $value->title;
                    $result['purchase_list'][$i]['product_id'] = $value->id;
                    $result['purchase_list'][$i]['size_id'] = $value->size_id ? $value->size_id : '';
                    $result['purchase_list'][$i]['size'] = $value->size ? $value->size : "";
                    $result['purchase_list'][$i]['size_image'] = '';
                    $result['purchase_list'][$i]['brand_image'] = '';
                    if ($new_purchase_type == "other") {
                        $result['purchase_list'][$i]['brand_image'] = ($value->accessory_image != '') ? Url::to('@web/' . $value->accessory_image, true) : '';
                        $result['purchase_list'][$i]['size_image'] = ($value->accessory_image != '') ? Url::to('@web/' . $value->accessory_image, true) : '';
                    } else {
                        $result['purchase_list'][$i]['brand_image'] = ($value->size_image != '') ? Url::to('@web/' . $value->size_image, true) : '';
                        $result['purchase_list'][$i]['size_image'] = ($value->size_image != '') ? Url::to('@web/' . $value->size_image, true) : '';
                    }
                    $result['purchase_list'][$i]['price'] = number_format($value->price, 2);
                    $result['purchase_list'][$i]['stock'] = $stocklst;
                    $result['purchase_list'][$i]['more_details'] = $value->description;
                    $i++;
                }
                $result['is_last'] = 'Y';
                if (isset($_REQUEST['limit']) && $_REQUEST['limit'] != null) {
                    if ($i >= $limit) {
                        unset($result['purchase_list'][$i - 1]);
                        $result['is_last'] = 'N';
                    }
                }
                return Yii::$app->apifunction->setResponse('success_purchase_list', true, 200, 200, $result);
            } else {
                $result['purchase_list'] = [];
                return Yii::$app->apifunction->setResponse('error_no_purchase_list', true, 200, 200, $result);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    }

    public function actionTimeslots()
    {
        $required_objs = ['vendor_id',];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            extract($_POST);
            $userid = Yii::$app->user->id;
            $timeslots = Deliverytimeslot::find()->where(['vendor_id' => $vendor_id])->all();
            $result['timeslots'] = array();
            if (isset($timeslots) && $timeslots != array()) {
                $i = 0;
                foreach ($timeslots as $time) {
                    $result['timeslots'][$i]['id'] = $time->id;
                    $stime = date('h:iA', strtotime($time->start_time));
                    $etime = date('h:iA', strtotime($time->end_time));
                    $result['timeslots'][$i]['time'] = $stime . '-' . $etime;
                    $result['timeslots'][$i]['enabled'] = ($time->is_enable == 'Y') ? true : false;
                    $i++;
                }
            }
            return Yii::$app->apifunction->setResponse('', true, 200, 200, $result);
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 200, 400);
        }
    }

    public function actionPreviewordernew()
    {

        $this->layout = false;

        /*insert all required veriables*/
        $required_objs = [];

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

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

        $start = isset($start) ? $start : 0;
        $limit = isset($limit) ? $limit + 1 : 11;
        $carts = $carts->offset($start)->limit($limit);
        $vatPecentage = Setting::find()->where(['key' => 'vat'])->one();

        $carts = $carts->orderBy('id DESC')->all();
        if ($carts) {
            $i = 0;
            $title = '';
            $type = '';
            $price = 0;
            $base_price = 0;
            $discount_price = 0;
            $discount = 1;
            $base_fare = 0;
            $price_per_km = 0;
            $product_ids = [];
            $vendor_id = "";
            $discount_percentage = 0;
            $discounted_price = number_format(0.0, 2);
            $tempdiscounted_price = 0;
            $is_vendor = true;
            foreach ($carts as $key => $value) {
                $result['preview_list'][$i]['id'] = $value->id;

                if (isset($value->vendor_id) && $value->vendor_id != 0 && $vendor_id == "") {
                    $vendor_id = $value->vendor_id;
                }

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

                        if ($product->discount_percentage == 0.0 && $product->discount_percentage == null) {
                            $discount = 0;
                            $discount_percentage = 0;

                            if ($value->csize == null) {
                                $tempdiscounted_price = $value->quantity * $price;
                                $discounted_price = number_format($value->quantity * $price, 2);
                            }
                            else{
                                $tempdiscounted_price = ((float)$value->csize) * $price;
                                $discounted_price = number_format(((float)$value->csize) * $price, 2);
                            }
                        } else {
                            $discount = $product->discount;
                            $discount_percentage = $product->discount_percentage;
                            if ($value->csize == null) {
                                $tempdiscounted_price = $value->quantity * round($price - (($price * $discount_percentage / 100)), 2);
                                $discounted_price = number_format($value->quantity * round($price - (($price * $discount_percentage / 100)), 2), 2);
                            }
                            else{
                                $tempdiscounted_price = ((float)$value->csize) * round($price - (($price * $discount_percentage / 100)), 2);
                                $discounted_price = number_format(((float)$value->csize) * round($price - (($price * $discount_percentage / 100)), 2), 2);
                            }

                        }
                        $product_ids[] = $product->id;
                    }
                } elseif ($value->size_id != null) {
                    $product = Product::find()->where(['size_id' => $value->size_id, 'is_deleted' => 'N', 'product_type' => 'R', 'is_active' => 'Y'])->one();
                    if ($product) {
                        $title = $product->title;
                        $type = $product->product_type;
                        $price = $product->price;
                        if ($product->discount_percentage == 0.0 && $product->discount_percentage == null) {
                            $discount = 0;
                            $discount_percentage = 0;
                            if ($value->csize == null) {
                                $tempdiscounted_price = $value->quantity * $price;
                                $discounted_price = number_format($value->quantity * $price, 2);
                            }
                            else{
                                $tempdiscounted_price = ((float)$value->csize) * $price;
                                $discounted_price = number_format(((float)$value->csize) * $price, 2);
                            }
                        } else {
                            $discount = $product->discount;
                            $discount_percentage = $product->discount_percentage;
                            // $discounted_price = number_format($value->quantity * round($price - (($price * $discount_percentage / 100)), 2), 2);
                            if ($value->csize == null) {
                                $tempdiscounted_price = $value->quantity * round($price - (($price * $discount_percentage / 100)), 2);
                                $discounted_price = number_format($value->quantity * round($price - (($price * $discount_percentage / 100)), 2), 2);
                            }
                            else{
                                $tempdiscounted_price = ((float)$value->csize) * round($price - (($price * $discount_percentage / 100)), 2);
                                $discounted_price = number_format(((float)$value->csize) * round($price - (($price * $discount_percentage / 100)), 2), 2);
                            }
                        }
                        $product_ids[] = $product->id;
                    }
                }

                $result['preview_list'][$i]['title'] = $title;
                $result['preview_list'][$i]['type'] = $type;

                $result['preview_list'][$i]['discount_percentage'] = $discount_percentage ? $discount_percentage : 0;
                $result['preview_list'][$i]['discounted_price'] = $discounted_price;

                if ($value->csize == null) {
                    $result['preview_list'][$i]['price'] = number_format($value->quantity * $price, 2);
                    $result['preview_list'][$i]['quantity'] = number_format($value->quantity, 2);
                }
                else{
                    $result['preview_list'][$i]['price'] = number_format(((float)$value->csize) * $price, 2);
                    $result['preview_list'][$i]['quantity'] = number_format(((float)$value->csize), 2);
                }

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

                if ($value->csize == null) {
                    $base_price = $base_price + $value->quantity * $price;
                    $discount_price = $discount_price + ((($value->quantity * $price) * $discount_percentage) / 100);
                }
                else{
                    $base_price = $base_price + ((float)$value->csize) * $price;
                    $discount_price = $discount_price + (((((float)$value->csize) * $price) * $discount_percentage) / 100);
                }

                $i++;
            }
            $flat_fee = Setting::find()->where(['key' => 'flat_fee'])->one();
            $result['vat_percentage'] = isset($vatPecentage->value) ? $vatPecentage->value : 0;
            $result['vat'] = (string)(isset($flat_fee->value) ? ($vatPecentage->value * $flat_fee->value / 100) : 0);

            $result['discount'] = (float)round(($discount_price * 100) / $base_price, 2);
            $result['base_price'] = (float)$base_price;
            $result['base_fare'] = (float)round($base_fare, 2);
            $result['price_per_km'] = (float)round($price_per_km, 2);

            //Flate Fee set by admin
            $result['flat_fee'] = isset($flat_fee->value) ? $flat_fee->value : 0;
            /**
             * Find the previous cancel order
             */
            $result['cancelation_charge'] = 0;
            $result['next_charge'] = 0;

            $cashPaymentCap = Setting::find()->where(['key' => 'payment_cap'])->one();
            $result['payment_cap'] = isset($cashPaymentCap->value) ? $cashPaymentCap->value : 15000;

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

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

            $address = UserAddress::find()->where(['user_id' => Yii::$app->user->id, 'is_default' => 'Y'])->one();
            $latitude = (isset($address->latitude) && $address->latitude != null) ? $address->latitude : "";
            $longitude = (isset($address->longitude) && $address->longitude != null) ? $address->longitude : "";
            //$result['delivery_charge'] = Yii::$app->common->calculateDelivaryCharge($vendor_id, $latitude, $longitude);
            if (isset($is_direct_pickup) && $is_direct_pickup == 'N') {
                $result['delivery_charge'] = isset($flat_fee->value) ? $flat_fee->value : 0;
            } else {
                $result['delivery_charge'] = isset($flat_fee->value) ? $flat_fee->value : 0;
            }

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

            $str = '';

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

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

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

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

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

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

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

            $vendor = Uservendor::find()->select("us.*,um.rating as vendor_rating")
                ->leftJoin('user_stores us', 'us.user_id=user_vendor.vendor_id')
                ->leftJoin('user_master um', 'um.id=us.user_id')
                ->where(['user_vendor.user_id' => Yii::$app->user->id, 'user_vendor.is_deleted' => 'N', 'user_vendor.is_active' => 'Y'])
                ->one();

            if ($is_vendor) {
                $result['vendor'] = array();
                if (isset($vendor) && $vendor != array()) {
                    $result['vendor']['id'] = $vendor->user_id;
                    $result['vendor']['shop_name'] = $vendor->shop_name;
                    if ($vendor->vendor_type == 'R')
                        $result['vendor']['price'] = number_format($vendor->price, 2);
                    else
                        $result['vendor']['price'] = number_format($vendor->price_per_kg, 2);
                    $result['vendor']['latitude'] = $vendor->latitude;
                    $result['vendor']['longitude'] = $vendor->longitude;
                    $result['vendor']['location'] = $vendor->address;
                    $result['vendor']['logo'] = $vendor->logo ? Url::to('@web/' . $vendor->logo, true) : "";
                    $result['vendor']['rating'] = $vendor->vendor_rating;
                    $result['vendor']['type'] = $vendor->vendor_type;
                }
                else if (!isset($vendor)) {
                    $vendor = Uservendor::find()->select("us.*,um.rating as vendor_rating")
                    ->leftJoin('user_stores us', 'us.user_id=user_vendor.vendor_id')
                    ->leftJoin('user_master um', 'um.id=us.user_id')
                    ->where(['user_vendor.user_id' => Yii::$app->user->id, 'user_vendor.is_active' => 'Y'])
                    ->orderBy('id DESC')
                    ->one();

                    $result['vendor']['id'] = $vendor->user_id;
                    $result['vendor']['shop_name'] = $vendor->shop_name;
                    if ($vendor->vendor_type == 'R')
                        $result['vendor']['price'] = number_format($vendor->price, 2);
                    else
                        $result['vendor']['price'] = number_format($vendor->price_per_kg, 2);
                    $result['vendor']['latitude'] = $vendor->latitude;
                    $result['vendor']['longitude'] = $vendor->longitude;
                    $result['vendor']['location'] = $vendor->address;
                    $result['vendor']['logo'] = $vendor->logo ? Url::to('@web/' . $vendor->logo, true) : "";
                    $result['vendor']['rating'] = $vendor->vendor_rating;
                    $result['vendor']['type'] = $vendor->vendor_type;
                }
            } else {
                $result['vendor'] = null;
            }
            $result['is_last'] = 'Y';

            if ($i >= $limit) {
                unset($result['preview_list'][$i - 1]);
                $result['is_last'] = 'N';
            }
            return Yii::$app->apifunction->setResponse('success_preview_list', true, 200, 200, $result);
        } else {
            $result['preview_list'] = [];
            $result['discount'] = 0;
            $result['base_price'] = 0;
            $result['discount_price'] = 0;
            $result['address'] = '';
            return Yii::$app->apifunction->setResponse('error_no_order_preview_found', true, 200, 200, $result);
        }
    }

    public function actionPurchaseordernew()
    {
        $this->layout = false;
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);

        extract($_POST);
        $user_order = Order::find()->where(['user_id' => yii::$app->user->id, 'status' => ['3', '4']])->one();

         if ($user_order) {
             return Yii::$app->apifunction->setResponse("You have an ongoing order so you can't place new one until it's complete", false, 200, 200);
         }

        $tech_charge_setting = Setting::find()->where(['key' => 'tech_charge'])->one()->value;
        $techcharges = $tech_charge_setting;

        $vatPecentage = Setting::find()->where(['key' => 'vat'])->one();
        $carts = Cart::find()->where(['user_id' => Yii::$app->user->id, 'is_deleted' => 'N', 'is_active' => 'Y', 'is_buy' => 'N']);
        $start = isset($start) ? $start : 0;
        $limit = isset($limit) ? $limit + 1 : 11;
        $carts = $carts->offset($start)->limit($limit);
        $carts = $carts->orderBy('id DESC')->all();
        if ($carts) {
            $i = 0;
            $title = '';
            $image = '';
            $type = '';
            $price = 0;
            $base_price = 0;
            $discount_price = 0;
            $discount = 1;
            $product_id = null;
            $brand_id = null;
            $vendorid = 0;
            $total_quantity = 0;
            $product_type = 'R';
            $order_detail_ids = [];
            $cart_ids = [];
            $product_ids_quantity = [];
            $is_vendor = true;
            $is_tech_id = 0;
            $is_tech_type = 0;
            $is_tech_charge = 0;
            $ftotal = 0;
            $stotal = 0;
            //(2) Find the vendor based on the nearest location (from user to vendor)
            $sett_dis = Setting::find()->where(['key' => 'distance'])->one();

            if ($sett_dis) {
                $distance = $sett_dis->value;
            } else $distance = 100; //static distance 10km

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

                $order_detail = new OrderDetail;

                if ($value->product_id != null) {
                    $product = Product::find()->select(['id', 'title', 'product_type', 'price', 'is_deleted', 'brand_id', 'discount', 'discount_percentage','size_id', 'u_by'])->where(['id' => $value->product_id, 'is_deleted' => 'N', 'is_active' => 'Y'])->one();
                    if ($product) {
                        $stocks_list = Stock::find()->where(['product_id' => $value->product_id, 'user_id' => $product->u_by]);
                        if($product->size_id != null && $product->size_id != ""){
                            $stocks_list = $stocks_list->andWhere(['size_id' => $product->size_id])->one();
                        }
                        else{
                            $stocks_list = $stocks_list->one();
                        }

                        if($stocks_list && $stocks_list->quantity < 0 && $stocks_list->quantity < $value->quantity){
                            return Yii::$app->apifunction->setResponse(" $product->title product is out of stock", false, 400, 400);
                        }

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

                        $stocks_list = Stock::find()->where(['product_id' => $value->product_id, 'user_id' => $product->u_by]);
                        if($product->size_id != null && $product->size_id != ""){
                            $stocks_list = $stocks_list->andWhere(['size_id' => $product->size_id])->one();
                        }
                        else{
                            $stocks_list = $stocks_list->one();
                        }

                        if($stocks_list->quantity < 0 && $stocks_list->quantity < $value->quantity){
                            return Yii::$app->apifunction->setResponse(" $product->title product is out of stock", false, 400, 400);
                        }

                        $title = $product->title;
                        $image = Brand::find()->where(['id' => $product->brand_id])->one()->brand_image;
                        $type = $product->product_type;
                        $price = $product->price;
                        //                            $discount = $product->discount;
                        if ($product->discount_percentage == 0.0 || $product->discount_percentage == null) {
                            $discount = 0;
                        } else {
                            $discount = $product->discount_percentage;
                        }
                        $product_id = $product->id;
                        $brand_id = $product->brand_id;
                        $product_type = $product->product_type;
                    }
                }

                $vendorid = $value->vendor_id;
                $order_detail->product_id = $product_id;
                $order_detail->brand_id = $brand_id;
                $order_detail->user_id = yii::$app->user->id;
                // $order_detail->quantity = $value->quantity;
                $order_detail->quantity = $value->csize;
                $order_detail->unit_price = $price;
                // $order_detail->total_price = $value->quantity * $price;
                $order_detail->total_price = ((float)$value->csize) * $price;
                $order_detail->product_discount_percentage = round($discount, 2);
                // $order_detail->product_discount_price = ((($value->quantity * $price) * $discount) / 100);
                $order_detail->product_discount_price = (((((float)$value->csize) * $price) * $discount) / 100);

                $order_detail->vat_percentage = $vatPecentage->value;
                $order_detail->vat_value = isset($flat_fee->value) ? ($vatPecentage->value * $flat_fee->value / 100) : 0;

                $order_detail->status = '1';
                $order_detail->i_date = time();
                $order_detail->product_type = $product_type ?? 'S';

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

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

                //                    $base_price = $base_price + $value->quantity * $price;

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

                // $stotal += ($value->quantity * $price) - $discount_price;
                // $base_price += ($value->quantity * $price);
                $stotal += (((float)$value->csize) * $price) - $discount_price;
                $base_price += (((float)$value->csize) * $price);
                $i++;
            } //Foreach loop end here for order_details

            $address = UserAddress::find()->where(['user_id' => yii::$app->user->id, 'is_default' => 'Y'])->one();
            foreach ($product_ids_quantity as $pro_id => $qty) {
                $test[] = Stock::find()->where(['product_id' => $pro_id])
                    ->andwhere(['>=', 'quantity', $qty])
                    ->asArray()
                    ->all();
            }
            $final_sort['list'] = [];
            foreach ($test as $object) {
                foreach ($object as $array) {
                    if (in_array($array['product_id'], array_keys($product_ids_quantity))) {
                        $final_sort['list'][$array['user_id']][$array['product_id']] = true;
                    }
                }
            }

            $vendor_ids = [];
            foreach ($final_sort['list'] as $key => $value) {
                if (count($product_ids_quantity) == count($value)){
                    // array_push($vendor_ids, $key);
                    $vendor_ids[] = $key;
                }
            }
            // $log  = "vendors Count: ". date("F j, Y, g:i a") . PHP_EOL .
            // "final_sort Lat: " . json_encode($final_sort['list']) . PHP_EOL .
            // "carts Lat: " . json_encode($carts) . PHP_EOL .
            // "vendorid Lat: " . json_encode($vendorid) . PHP_EOL .
            // "Vendor Lat: " . $address->latitude . PHP_EOL .
            // "Vendor Lon: " . $address->longitude . PHP_EOL .
            // "Vendor id: " . json_encode($vendor_ids) . PHP_EOL .
            // "Rider count: ". count($vendor_ids) . PHP_EOL .
            // "-------------------------" . PHP_EOL;
            // file_put_contents('./Rider Available_2_' . date("j.n.Y") . '.log', $log, FILE_APPEND);

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

            $vendors = Yii::$app->common->checkRiderAvilibilty('V', $address->latitude, $address->longitude, empty($vendor_ids) ? [$vendorid] : $vendor_ids);
            \Yii::info($vendors, 'pushnotification');

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

            //            $vendors = Users::find()->select("*,(6371 * acos( cos( radians($address->latitude) ) * cos( radians( latitude) ) * cos( radians( longitude
            //                    ) - radians($address->longitude) ) + sin( radians($address->latitude) ) * sin( radians( latitude ) ) ) ) AS distance")
            //                ->where(['user_type' => 'V', 'is_deleted' => 'N', 'is_active' => 'Y', 'profile_status' => 'A'])
            //                ->andWhere(['NOT', ['latitude' => null, 'longitude' => null]])
            //                ->andWhere(['id' => $vendor_ids])
            //                ->andHaving("distance < " . $distance)->orderBy(['distance' => SORT_DESC])->all();

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

            $vendors = ArrayHelper::map($vendors, 'latitude', 'longitude', 'id');
            $vendor_id = "";
            $u_lat = (isset($address->latitude) && $address->latitude != "") ? $address->latitude : "";
            $u_long = (isset($address->longitude) && $address->longitude != "") ? $address->longitude : "";
            $delivery_charge = 0;
            $history_ids = [];
            foreach ($vendors as $key => $value) {
                if ($vendor_id == "") {
                    $vendor_id = $key;
                }
                $history = new Vendorhistory;
                $history->vendor_id = $key;
                $history->i_date = time();
                $history->save(false);
                $history_ids[] = $history->id;
            }

            if (isset($delivery_method) && $delivery_method != "D") {

                foreach ($vendors as $vendor => $lat_long) {

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

                    $riders = Yii::$app->common->checkRiderAvilibilty('R', $u_lat, $u_long, [], $vendor);

                    // $riders = Users::find()->select("*,( 6371 * acos( cos( radians($vendor_lat) ) * cos( radians( latitude) ) * cos( radians( longitude
                    // ) - radians($vendor_long) ) + sin( radians($vendor_lat) ) * sin( radians( latitude ) ) ) ) AS distance")
                    //     ->where(['vendor_id' => $vendor, 'is_deleted' => 'N', 'is_active ' => 'Y', 'profile_status' => 'A', 'notification_enabled' => 'Y', 'is_online' => 'Y'])
                    //     ->andWhere(['IN', 'user_type', ['R', '1']])
                    //     ->andWhere(['and', "ongoing_orders>=0", "ongoing_orders<5"])
                    //     ->andWhere(['NOT', ['latitude' => null, 'longitude' => null]])
                    //     ->andHaving("distance < " . $distance)->orderBy(['distance' => SORT_ASC])->one();

                    // $riders = Users::find()->where(['id' => 44])->one();

                    //                    print_r($riders);exit();

                    if ($riders != "")
                        break;

                    //(ii) Here find the nearest rider and exclude those rider which are in order on the way
                    //                    $riders = Users::find()->select("*,( 6371 * acos( cos( radians($vendor_lat) ) * cos( radians( latitude) ) * cos( radians( longitude
                    //                    ) - radians($vendor_long) ) + sin( radians($vendor_lat) ) * sin( radians( latitude ) ) ) ) AS distance")
                    //                        ->where(['vendor_id' => $vendor, 'is_deleted' => 'N', 'is_active' => 'Y', 'profile_status' => 'A', 'notification_enabled' => 'Y', 'is_request_recieve' => 'N', 'is_online' => 'Y'])
                    //                        ->andWhere(['IN', 'user_type', ['R', '1']])
                    //                        ->andWhere(['NOT', ['latitude' => null, 'longitude' => null]])
                    //                        ->andHaving("distance < " . $distance)->orderBy(['distance' => SORT_ASC])->one();
                    //
                    //                    \Yii::info($riders, 'pushnotification');
                    //                    \Yii::info($vendor, 'pushnotification');
                    //
                    //                    if (!empty($riders))
                    //                        break;
                }
                //foreach end here
                //                if (empty($riders)) {
                if ($riders == "") {
                    $noti = new Notification;
                    $noti->from_user = Yii::$app->user->id;
                    $noti->to_user = Yii::$app->user->id;
                    $noti->notification_type = 'no_rider_found';
                    $noti->message = Yii::t('app', Yii::$app->params['rider_not_available_for_order']);
                    $noti->type = 'U';
                    $noti->i_by = Yii::$app->user->id;
                    $noti->i_date = date('Y-m-d H:i:s');
                    $noti->i_datetime = time();
                    $noti->save(false);
                    $body_a = array();
                    $body_a['data']['notification_type'] = 'no_rider_found';
                    $body_a['data']['message'] = Yii::t('app', Yii::$app->params['rider_not_available_for_order']);
                    $body_i = array();
                    $body_i['data'] = array('alert' => Yii::t('app', Yii::$app->params['rider_not_available_for_order']));
                    $body_i['data']['badge'] = 1;
                    $body_i['data']['notification_type'] = 'no_rider_found';
                    $body_i['data']['sound'] = 'default';
                    $body_i['data']['message'] = Yii::t('app', Yii::$app->params['rider_not_available_for_order']);
                    $body_i['data']['alert'] = Yii::t('app', Yii::$app->params['rider_not_available_for_order']);
                    $body_i['data']['text'] = Yii::t('app', Yii::$app->params['rider_not_available_for_order']);
                    $body_i['data']['title'] = Yii::t('app', Yii::$app->params['rider_not_available_for_order']);

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

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

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

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

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

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

                //Distance Calculater
                //$delivery_charge = Yii::$app->common->calculateDelivaryCharge($vendor_id, $u_lat, $u_long);
                $flat_fee = Setting::find()->where(['key' => 'flat_fee'])->one();
                $delivery_charge = isset($flat_fee->value) ? $flat_fee->value : 0;
            }

            $order = new Order;
            $order->user_id = Yii::$app->user->id;
            $order->vendor_id = $vendorid;

            if (isset($delivery_method) && $delivery_method != "D") {
                $order->rider_id = $riders->id;
                $request_recieve = Users::findOne($riders->id);
                if ($request_recieve) {
                    $request_recieve->is_request_recieve = 'Y';
                    $request_recieve->ongoing_orders = $request_recieve->ongoing_orders + 1;
                    $request_recieve->save(false);
                }
            }

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

            // $vatamo = (($base_price - $discount_price) * $vatPecentage->value / 100);
            // $order->vat_percentage = $vatPecentage->value;
            // $order->vat_value = $vatamo;

            $order->base_price = $base_price;
            $order->total_quantity = $total_quantity;
            $order->status = '1';
            $order->admin_receive = '';
            $order->rider_receive = '';
            $order->vendor_receive = '';
            $order->pickup_date = isset($pickup_date) ? $pickup_date : null;

            $order->delivery_method = isset($delivery_method) ? $delivery_method : 'H';
            $vatamo = 0;
            if (isset($delivery_method) && $delivery_method == "H") {
                $order->delivery_charge = $delivery_charge;
                $flat_fee = Setting::find()->where(['key' => 'flat_fee'])->one();
                $order->vat_percentage = isset($vatPecentage->value) ? $vatPecentage->value : 0;
                $vatamo = isset($flat_fee->value) ? ($vatPecentage->value * $flat_fee->value / 100) : 0;
                $order->vat_value = $vatamo;
                $order->timeslot_id = isset($timeslot_id) ? $timeslot_id : "";
            }
            if (isset($delivery_method) && $delivery_method == "D") {
                $order->delivery_charge = 0;
                $order->timeslot_id = isset($timeslot_id) ? $timeslot_id : "";
                $order->vat_percentage = 0;
                $order->vat_value = 0;
            }


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

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

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

            $order->i_date = time();
            $order->u_date = time();
            //$promo_code_price = (float)((($base_price * $total_quantity) * $order->promocode_discount) / 100);
            $order->total_price = $stotal + $cancelation_charge + $vatamo;
            $order->timer = time() + 51;
            $order->save(false);

            $order_log = new Orderlog;
            $order_log->order_id = $order->id;
            $order_log->status = $order->status;
            $order_log->i_by = $order->rider_id;
            $order_log->i_date = $order->i_date;
            $order_log->save(false);

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

            if ($delivery_method == "D") {
                $orderid = $order->id;
                $noti = new Notification;
                $noti->from_user = Yii::$app->user->id;
                $noti->to_user = $order->vendor_id;
                $noti->order_id = $orderid;
                $noti->notification_type = 'direct_pickup_order';
                $noti->message = "New direct pickup order #$orderid scheduled";
                $noti->type = 'V';
                $noti->i_by = Yii::$app->user->id;
                $noti->i_date = date('Y-m-d H:i:s');
                $noti->i_datetime = time();
                $noti->save(false);
                $body_a = array();
                $body_a['data']['notification_type'] = 'direct_pickup_order';
                $body_a['data']['message'] = "New direct pickup order #$orderid scheduled";;
                $body_i = array();
                $body_i['data'] = array('alert' => "New direct pickup order #$orderid scheduled");
                $body_i['data']['badge'] = 1;
                $body_i['data']['notification_type'] = 'direct_pickup_order';
                $body_i['data']['sound'] = 'default';
                $body_i['data']['message'] = "New direct pickup order #$orderid scheduled";
                $body_i['data']['alert'] = "New direct pickup order #$orderid scheduled";
                $body_i['data']['text'] = "New direct pickup order #$orderid scheduled";
                $body_i['data']['title'] = "New direct pickup order #$orderid scheduled";

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

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

                        foreach ($uDeviceDetail as $u) {

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

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

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

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

            \Yii::info("===================Before Notification==============", 'pushnotification');
            \Yii::info($order, 'pushnotification');
            \Yii::info("===================Before Notification==============", 'pushnotification');
            if ($delivery_method != "D")
                Yii::$app->mycomponent->newOrderNotification($order);

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

    public function actionSetcartvendor()
    {
        $required_objs = ['vendor_id',];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            extract($_POST);
            $userid = Yii::$app->user->id;
            $setvendor = Uservendor::find()->where(['vendor_id' => $vendor_id, 'user_id' => $userid, 'is_deleted' => 'N', 'is_active' => 'Y'])->one();
            if (!empty($setvendor) && $setvendor != array()) {
                $setvendor->u_by = $userid;
                $setvendor->u_date = time();
            } else {
                $setvendor = new Uservendor();
                $setvendor->u_by = $userid;
                $setvendor->u_date = time();
                $setvendor->i_by = $userid;
                $setvendor->i_date = time();
            }
            $setvendor->user_id = $userid;
            $setvendor->vendor_id = $vendor_id;
            $setvendor->save();
            Cart::updateAll(['vendor_id' => $vendor_id], ['user_id' => $userid]);
            return Yii::$app->apifunction->setResponse('vendor_set', true, 200, 200);
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 200, 400);
        }
    }

    public function actionGetcartvendor()
    {
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
        extract($_POST);
        $userid = Yii::$app->user->id;
        $vendor = Uservendor::find()->select("us.*,um.rating as vendor_rating")
            ->leftJoin('user_stores us', 'us.user_id=user_vendor.vendor_id')
            ->leftJoin('user_master um', 'um.id=us.user_id')
            ->where(['user_vendor.user_id' => $userid, 'user_vendor.is_deleted' => 'N', 'user_vendor.is_active' => 'Y'])
            ->one();
        // print_r($vendor);die;
        $result['vendor'] = null;

        $sett_dis = Setting::find()->where(['key' => 'distance'])->one();

        if ($sett_dis) {
            $distance = $sett_dis->value;
        } else $distance = 10; //static distance 10km

        if (!empty($vendor) && $vendor != array()) {
            $result['vendor']['id'] = $vendor->user_id;
            $result['vendor']['shop_name'] = $vendor->shop_name;
            if ($vendor->vendor_type == 'R')
                $result['vendor']['price'] = number_format($vendor->price, 2);
            else
                $result['vendor']['price'] = number_format($vendor->price_per_kg, 2);
            $result['vendor']['latitude'] = $vendor->latitude;
            $result['vendor']['longitude'] = $vendor->longitude;
            $result['vendor']['location'] = $vendor->address;
            $result['vendor']['logo'] = $vendor->logo ? Url::to('@web/' . $vendor->logo, true) : "";
            $result['vendor']['rating'] = $vendor->vendor_rating;
            $result['vendor']['type'] = $vendor->vendor_type;
        }
        else{
            $result['vendor']['id'] = 0;
            $result['vendor']['shop_name'] = "";
            $result['vendor']['price'] = 0;
            $result['vendor']['latitude'] = "0.0";
            $result['vendor']['longitude'] = "0.0";
            $result['vendor']['location'] = "";
            $result['vendor']['logo'] = "";
            $result['vendor']['rating'] = "0";
            $result['vendor']['type'] = "";
        }
        $result['vendor']['distance'] = $distance;
        return Yii::$app->apifunction->setResponse('', true, 200, 200, $result);
    }

    public function actionClearcart()
    {
        $this->layout = false;
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
        extract($_POST);
        $userId = Yii::$app->user->id;
        $cart = Cart::updateAll(['is_deleted' => 'Y', 'u_by' => $userId, 'u_date' => time()], ['user_id' => $userId, 'is_deleted' => 'N']);
        Uservendor::updateAll(['is_deleted' => 'Y', 'u_by' => $userId, 'u_date' => time()], ['user_id' => $userId]);
        return Yii::$app->apifunction->setResponse('clear_cart', true, 200, 200);
    }

    public function actionCartlistnew()
    {
        $this->layout = false;
        /*insert all required veriables*/
        $required_objs = [];

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

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

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

        $carts = $carts->orderBy('id DESC')->all();
        $result['cart_item_list'] = [];
        $result['is_last'] = 'Y';

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

                $title = '';
                $description = '';
                $image = '';
                $type = '';
                $brand_name = '';
                $price = 0;
                $tmpPrice= 0;
                $discount = 0;
                $discount_percentage = 0;
                $discounted_price = number_format(0.0, 2);
                $qtyies = 0;

                if ($value->product_id != null) {
                    if ($value->product_id == 9999) {
                        $user = Users::findOne($value->vendor_id);
                        $Usertype_master = Usertype_master::findOne($user->user_type);

                        $title = "Service Booking";
                        $type = "Service";
                        $price = $user->rider_charge;
                        $description = "Service Booking for " . $Usertype_master->name;
                        $discount = 0;
                        $discount_percentage = 0;
                        $discounted_price = number_format(1 * round($price, 2), 2);
                    } else {
                        $product = Product::find()->where(['id' => $value->product_id, 'is_deleted' => 'N', 'is_active' => 'Y'])->one();
                        if ($product) {
                            $title = $product->title;
                            $type = $product->product_type;
                            $price = $product->price;
                            $description = $product->description;
                            $discount = $product->discount;
                            $discount_percentage = $product->discount_percentage;
                            if($value->csize == null){
                                $discounted_price = number_format($value->quantity * round($price - (($price * $discount_percentage / 100)), 2), 2);
                                $qtyies = $value->quantity;
                                $tmpPrice = number_format($value->quantity * $price, 2);
                            }
                            else{
                                $discounted_price = number_format(((float) $value->csize) * round($price - (($price * $discount_percentage / 100)), 2), 2);
                                $qtyies = $value->csize;
                                $tmpPrice = number_format(((float) $value->csize) * $price, 2);
                            }
                        }
                    }
                }

                if (empty($product->id) && $value->product_id != 9999) {
                    unset($result['cart_item_list'][$i]);
                    continue;
                }




                $result['cart_item_list'][$i]['title'] = (isset($title) && $title != null) ? $title : "";
                $result['cart_item_list'][$i]['type'] = $type;
                $result['cart_item_list'][$i]['discount_percentage'] = $discount_percentage ? $discount_percentage : 0;
                $result['cart_item_list'][$i]['description'] = $description ? $description : "";
                $result['cart_item_list'][$i]['price'] = $tmpPrice;
                $result['cart_item_list'][$i]['product_id'] = $product->id ?? 9999;
                $result['cart_item_list'][$i]['discounted_price'] = $discounted_price;
                $result['cart_item_list'][$i]['quantity'] = $qtyies;
                $result['cart_item_list'][$i]['is_cylinder'] = $value->is_cylinder;
                $i++;
            }
            //                die;
            $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 {
            return Yii::$app->apifunction->setResponse('error_no_carts_found', true, 200, 200, $result);
        }
    }

    public function actionGetvendorprice()
    {
        $required_objs = ['vendor_id'];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
            extract($_POST);
            $userid = Yii::$app->user->id;
            $product = Product::find()->select('product_master.*')
                ->where(['product_master.vendor_type' => 'F', 'product_master.is_bulk_lpg' => 'Y', 'product_master.vendor_id' => $vendor_id])->one();
            if (!empty($product)) {
                $stocklst = 0;
                $stocks_list = Stock::find()->where(['product_id' => $product->id, 'user_id' => $product->u_by]);
                if($product->size_id != null && $product->size_id != ""){
                    $stocks_list = $stocks_list->andWhere(['size_id' => $product->size_id])->one();
                }
                else{
                    $stocks_list = $stocks_list->one();
                }

                if($stocks_list->quantity > 0 ){
                    $stocklst = $stocks_list->quantity;
                }

                $result['bulk_lpg']['id'] = $product->id;
                $result['bulk_lpg']['price'] = $product->price;
                $result['bulk_lpg']['stock'] = $stocklst;
                $result['bulk_lpg']['discount_percentage'] = (int)$product->discount_percentage;
                $result['bulk_lpg']['discounted_price'] = $product->discount;
                return Yii::$app->apifunction->setResponse('', true, 200, 200, $result);
            } else {
                return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    }

    public function actionCylinderlist()
    {
        $required_objs = ['vendor_id'];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
            extract($_POST);
            $userid = Yii::$app->user->id;
            $stocks_list = Product::find()->alias('P')->select('P.*,sh.quantity as stock,sm.size_image,sm.wieght as size')
                // ->leftJoin('stock_history sh', 'sh.user_id=P.vendor_id')
                ->leftJoin('stock_history sh', 'sh.product_id=P.id')
                ->leftJoin('size_master sm', 'sm.id=P.size_id')
                ->where(['P.is_active' => 'Y', 'P.product_type' => 'R', 'P.is_deleted' => 'N', 'P.is_bulk_lpg' => 'N', 'P.vendor_id' => $vendor_id])
                ->andWhere(['<>', 'P.size_id', ''])
                ->groupBy('P.size_id')->all();
            $result['cylinder_list'] = array();
            if (!empty($stocks_list)) {
                $i = 0;
                foreach ($stocks_list as $stocks) {
                    $stocklst = 0;
                    $stockslist = Stock::find()->where(['product_id' => $stocks->id, 'user_id' => $stocks->u_by]);
                    if($stocks->size_id != null && $stocks->size_id != ""){
                        $stockslist = $stockslist->andWhere(['size_id' => $stocks->size_id])->one();
                    }
                    else{
                        $stockslist = $stockslist->one();
                    }

                    if($stockslist->quantity > 0 ){
                        $stocklst = $stockslist->quantity;
                    }

                    $result['cylinder_list'][$i]['id'] = $stocks->id;
                    $result['cylinder_list'][$i]['price'] = $stocks->price;
                    $result['cylinder_list'][$i]['size_id'] = isset($stocks->size_id) ? $stocks->size_id : 0;
                    $result['cylinder_list'][$i]['discount_percentage'] = $stocks->discount_percentage;
                    $result['cylinder_list'][$i]['discounted_price'] = $stocks->discount;
                    $result['cylinder_list'][$i]['size_image'] = ($stocks->size_image != '') ? Url::to('@web/' . $stocks->size_image, true) : '';
                    // $result['cylinder_list'][$i]['stock'] = ($stocks->stock != "" && isset($stocks->stock)) ? (int)$stocks->stock : 0;
                    $result['cylinder_list'][$i]['stock'] = $stocklst;
                    $result['cylinder_list'][$i]['size'] = ($stocks->size != "" && isset($stocks->size)) ? $stocks->size : 0;
                    $i++;
                }
            }
            return Yii::$app->apifunction->setResponse('cylinder_list', true, 200, 200, $result);
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 400, 400);
        }
    }

    public function actionAddtocartnew()
    {
        extract($_POST);
        if (($is_service == "N" || $is_service == "n")) {
            $required_objs = ['product_id', 'quantity', 'is_refilling', 'is_cylinder'];
            if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
                Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);

                $userId = Yii::$app->user->id;
                if($is_refilling == "Y"){
                    $product = Product::find()->where(['id' => $product_id, 'product_type' => 'R','is_deleted' => 'N'])->andWhere(['is_active' => 'Y'])->one();
                }
                else{
                    $product = Product::find()->where(['id' => $product_id])->andWhere(['is_active' => 'Y'])->one();
                }

                if (!$product) {
                    return Yii::$app->apifunction->setResponse('error_in_size', false, 400, 400);
                }

                if($product){
                    $stocks_list = Stock::find()->where(['product_id' => $product_id, 'user_id' => $product->u_by]);
                    if($product->size_id != null && $product->size_id != ""){
                        $stocks_list = $stocks_list->andWhere(['size_id' => $product->size_id])->one();
                    }
                    else{
                        $stocks_list = $stocks_list->one();
                    }

                    if($stocks_list->quantity < 0 && $stocks_list->quantity < $quantity){
                        return Yii::$app->apifunction->setResponse('Product is out of stock', false, 400, 400);
                    }
                }

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

                $setvendor = Uservendor::find()->where(['vendor_id' => $product->vendor_id, 'user_id' => $userId, 'is_deleted' => 'N', 'is_active' => 'Y'])->one();
                if (!empty($setvendor) && $setvendor != array()) {
                    $setvendor->u_by = $userId;
                    $setvendor->u_date = time();
                } else {
                    $setvendor = new Uservendor();
                    $setvendor->u_by = $userId;
                    $setvendor->u_date = time();
                    $setvendor->i_by = $userId;
                    $setvendor->i_date = time();
                }
                $setvendor->user_id = $userId;
                $setvendor->vendor_id = $product->vendor_id;
                $setvendor->save();

                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);
            }
        }
        else {
            $required_objs = ['is_service', 'technician_id'];
            if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
                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 = 9999;
                $cart->size_id = null;
                $cart->quantity = 1;
                $cart->is_refilling = "N";
                $cart->is_cylinder = "N";
                $cart->cylinder_size = null;
                $cart->vendor_id = $technician_id;
                $cart->i_by = $userId;
                $cart->i_date = time();

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

    public function actionPaymentprocess()
    {
        $required_objs = ['order_id','type','payment_option'];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
            $user = Users::findOne(Yii::$app->user->id);
            extract($_POST);
            /**
             * From order id find require information
             */
            $order = Order::find()->alias('O')->where(['O.id' => $order_id, 'O.user_id' => $user->id])->one();

            if ($order) {
                $oid = $order->id;
                $ordertype = OrderDetail::find()->where(['order_id' => $order_id])->one();
                $amount = $order->total_price + $order->delivery_charge;
                if ($ordertype->product_id == 9999)
                    $url = Yii::$app->common->paymentProcess($oid, $amount, $user->email, "T", $type, $payment_option);
                else
                    $url = Yii::$app->common->paymentProcess($oid, $amount, $user->email, "", $type, $payment_option);

                $url = json_decode($url);

                if ($url != '') {
                    if($type == "P"){
                        $result['url'] = $url->data->authorization_url;
                        $result['access_code'] = $url->data->access_code;
                        $result['reference'] = $url->data->reference;

                        $order->access_code = $url->data->access_code;
                        $order->reference = $url->data->reference;
                        $order->save(false);
                        return Yii::$app->apifunction->setResponse('Payment url', true, 200, 200, $result);
                    }
                    else if($type == "F" && $url->status == "success"){
                        $result['url'] = $url->data->link;
                        $result['access_code'] = "";
                        $result['reference'] = "";
                        return Yii::$app->apifunction->setResponse('Payment url', true, 200, 200, $result);
                    }

                    exit;
                } else {
                    // print_r("asdfasd");
                    die;
                    return Yii::$app->apifunction->setResponse('Url not found', false, 400, 400);
                }
            } else {
                return Yii::$app->apifunction->setResponse('Order not found', false, 400, 400);
            }
        } else {
            return Yii::$app->apifunction->setResponse('response_text', false, 200, 400);
        }
    }

    public function actionPaymentresponsesuccess()
    {
        $required_objs = ['order_id'];
        if (Yii::$app->request->post() && Yii::$app->apifunction->checkIsPost($required_objs, $_POST)) {
            //Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);

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

            if($tx_ref == "" || $transaction_id == "" ){
                $url1 = Yii::$app->common->verifiedPayment($order->reference);
                $url = json_decode($url1);

                \Yii::info("===================Before Notification verifiedPayment==============", 'pushnotification');
                \Yii::info($url1, 'pushnotification');
                \Yii::info("===================Before Notification verifiedPayment==============", 'pushnotification');

                if ($url->data->status == "success" && ($url->data->gateway_response == "Approved" || $url->data->gateway_response == "Successful")) {
                    if (isset($order_id) && $order_id != '') {
                        $order = Order::find()->where(['id' => $order_id])->one();
                        $orderde = OrderDetail::find()->where(['order_id' => $order_id])->one();
                        if ($orderde->product_id == 9999) {
                            //Yii::$app->mycomponent->newOrderNotification($order, "S");
                            if ($order) {
                                try {
                                    $payment = new Paymentresponse;
                                    $payment->order_id = $order_id;
                                    $payment->amount = isset($url->data->amount) ? ($url->data->amount / 100) : "";
                                    $payment->currency = isset($url->data->currency) ? $url->data->currency : "";
                                    $payment->status = isset($url->data->status) ? $url->data->status : "";
                                    $payment->card_holder_name = "";
                                    $payment->pan = "";
                                    $payment->scheme = "";
                                    $payment->status_description = "";
                                    $payment->approval_code = "";
                                    $payment->transaction_date = isset($url->data->start_time) ? $url->data->start_time : "";

                                    $payment->user_id = $order->user_id;
                                    $payment->transaction_id = $url->data->id;
                                    $payment->response = $url1;
                                    $payment->save(false);
                                } catch (\Exception $e) {
                                    print_r($e->getMessage());
                                    die;
                                }

                                $order->payment_log = $url1;
                                $order->is_payment_received = 'Y';
                                $order->save(false);
                                $result['order_id'] = $order->id;
                                $result['is_done'] = true;
                                if($order->rider_id != null){
                                    $rider = Users::findOne($order->rider_id);
                                    $rider->is_available = 'Y';
                                    $rider->save(false);
                                }
                                /**
                                 * And may be I have to fire one more notification to rider for payment recieved
                                 */
                                /**
                                 * send payment notification to rider as well as his vendor
                                 */
                                $noti = new Notification;
                                $noti->from_user = Yii::$app->user->id;

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

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

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

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

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


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

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

                                if ($device_token_iphone != array()) {
                                    Yii::$app->mycomponent->pushnotification_iphone_array($device_token_iphone, $body_i);
                                }
                            } else {
                                return Yii::$app->apifunction->setResponse('Order not found', false, 400, 400);
                            }

                        }
                        else{
                            if ($order) {
                                try {
                                    $payment = new Paymentresponse;
                                    $payment->order_id = $order_id;
                                    $payment->amount = isset($url->data->amount) ? ($url->data->amount / 100) : "";
                                    $payment->currency = isset($url->data->currency) ? $url->data->currency : "";
                                    $payment->status = isset($url->data->status) ? $url->data->status : "";
                                    $payment->card_holder_name = "";
                                    $payment->pan = "";
                                    $payment->scheme = "";
                                    $payment->status_description = "";
                                    $payment->approval_code = "";
                                    $payment->transaction_date = isset($url->data->start_time) ? $url->data->start_time : "";

                                    $payment->user_id = $order->user_id;
                                    $payment->transaction_id = $url->data->id;
                                    $payment->response = $url1;
                                    $payment->save(false);
                                } catch (\Exception $e) {
                                    print_r($e->getMessage());
                                    die;
                                }

                                $order->payment_log = $url1;
                                $order->is_payment_received = 'Y';
                                $order->save(false);
                                $result['order_id'] = $order->id;
                                $result['is_done'] = true;
                                if($order->rider_id != null){
                                    $rider = Users::findOne($order->rider_id);
                                    $rider->is_available = 'Y';
                                    $rider->save(false);
                                }
                                /**
                                 * And may be I have to fire one more notification to rider for payment recieved
                                 */
                                /**
                                 * send payment notification to rider as well as his vendor
                                 */
                                $noti = new Notification;
                                $noti->from_user = Yii::$app->user->id;

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

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

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

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

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

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

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

                                if ($device_token_iphone != array()) {
                                    Yii::$app->mycomponent->pushnotification_iphone_array($device_token_iphone, $body_i);
                                }
                            } else {
                                return Yii::$app->apifunction->setResponse('Order not found', false, 400, 400);
                            }
                        }
                    }
                    return Yii::$app->apifunction->setResponse('success_payment', true, 200, 200, $result);
                } else {
                    $result['is_done'] = false;
                    return Yii::$app->apifunction->setResponse('failed_payment', false, 200, 400, $result);
                }
            }
            else{
                $order->access_code = $tx_ref;
                $order->reference = $transaction_id;
                //                $order->payment_log = $url1;
                $order->save(false);

                $url1 = Yii::$app->common->verifiedPaymentfultterwave($transaction_id);
                //                print_r($url1);
                //                exit();

                \Yii::info("===================Before Notification verifiedPaymentfultterwave==============", 'pushnotification');
                \Yii::info($tx_ref, 'pushnotification');
                \Yii::info($transaction_id, 'pushnotification');
                \Yii::info($url1, 'pushnotification');
                \Yii::info("===================Before Notification verifiedPaymentfultterwave==============", 'pushnotification');
                $url = json_decode($url1);

                if ($url->status == "success" && $url->data->status == "successful" && ($url->data->processor_response == "Approved" || $url->data->processor_response == "successful" || $url->data->processor_response == "Approved by Financial Institution" || strpos($url->data->processor_response, "Approve")  !== false)) {
                    if (isset($order_id) && $order_id != '') {

                        $order = Order::find()->where(['id' => $order_id])->one();
                        $orderde = OrderDetail::find()->where(['order_id' => $order_id])->one();
                        if ($orderde->product_id == 9999) {
                            // Yii::$app->mycomponent->newOrderNotification($order, "S");
                            if ($order) {
                                try {
                                    $payment = new Paymentresponse;
                                    $payment->order_id = $order_id;
                                    $payment->amount = isset($url->data->amount) ? $url->data->amount : "";
                                    $payment->currency = isset($url->data->currency) ? $url->data->currency : "";
                                    $payment->status = isset($url->data->status) ? $url->data->status : "";
                                    $payment->card_holder_name = "";
                                    $payment->pan = "";
                                    $payment->scheme = "";
                                    $payment->status_description = "";
                                    $payment->approval_code = "";
                                    $payment->transaction_date = isset($url->data->created_at) ? $url->data->created_at : "";

                                    $payment->user_id = $order->user_id;
                                    $payment->transaction_id = $url->data->id;
                                    $payment->response = $url1;
                                    $payment->save(false);
                                } catch (\Exception $e) {
                                    print_r($e->getMessage());
                                    die;
                                }

                                $order->payment_log = $url1;
                                $order->is_payment_received = 'Y';
                                $order->save(false);
                                $result['order_id'] = $order->id;
                                $result['is_done'] = true;
                                if($order->rider_id != null){
                                    $rider = Users::findOne($order->rider_id);
                                    $rider->is_available = 'Y';
                                    $rider->save(false);
                                }
                                /**
                                 * And may be I have to fire one more notification to rider for payment recieved
                                 */
                                /**
                                 * send payment notification to rider as well as his vendor
                                 */
                                $noti = new Notification;
                                $noti->from_user = Yii::$app->user->id;

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

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

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

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

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


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

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

                                if ($device_token_iphone != array()) {
                                    Yii::$app->mycomponent->pushnotification_iphone_array($device_token_iphone, $body_i);
                                }
                            } else {
                                return Yii::$app->apifunction->setResponse('Order not found', false, 400, 400);
                            }
                        }
                        else{
                            if ($order) {
                                try {
                                    $payment = new Paymentresponse;
                                    $payment->order_id = $order_id;
                                    $payment->amount = isset($url->data->amount) ? $url->data->amount : "";
                                    $payment->currency = isset($url->data->currency) ? $url->data->currency : "";
                                    $payment->status = isset($url->data->status) ? $url->data->status : "";
                                    $payment->card_holder_name = "";
                                    $payment->pan = "";
                                    $payment->scheme = "";
                                    $payment->status_description = "";
                                    $payment->approval_code = "";
                                    $payment->transaction_date = isset($url->data->created_at) ? $url->data->created_at : "";

                                    $payment->user_id = $order->user_id;
                                    $payment->transaction_id = $url->data->id;
                                    $payment->response = $url1;
                                    $payment->save(false);
                                } catch (\Exception $e) {
                                    print_r($e->getMessage());
                                    die;
                                }

                                $order->payment_log = $url1;
                                $order->is_payment_received = 'Y';
                                $order->save(false);
                                $result['order_id'] = $order->id;
                                $result['is_done'] = true;
                                if($order->rider_id != null){
                                    $rider = Users::findOne($order->rider_id);
                                    $rider->is_available = 'Y';
                                    $rider->save(false);
                                }
                                /**
                                 * And may be I have to fire one more notification to rider for payment recieved
                                 */
                                /**
                                 * send payment notification to rider as well as his vendor
                                 */
                                $noti = new Notification;
                                $noti->from_user = Yii::$app->user->id;

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

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

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

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

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


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

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

                                if ($device_token_iphone != array()) {
                                    Yii::$app->mycomponent->pushnotification_iphone_array($device_token_iphone, $body_i);
                                }
                            } else {
                                return Yii::$app->apifunction->setResponse('Order not found', false, 400, 400);
                            }
                        }
                    }
                    return Yii::$app->apifunction->setResponse('success_payment', true, 200, 200, $result);
                } else {
                    $result['is_done'] = false;
                    return Yii::$app->apifunction->setResponse('failed_payment', false, 200, 400, $result);
                }
            }
        }


        // if (isset($_REQUEST['status']) && $_REQUEST['status']) {
        //     if ($_REQUEST['status'] == 'APPROVED' && $_REQUEST['approved'] == true) {
        //         $result['is_done'] = true;
        //         /**
        //          * In all condition I have to process the order data which is comming in desctiption as a order_id
        //          *
        //          */
        //         $transactionId = $_REQUEST['trxId'];
        //         $url = "https://test.payarena.com/Status/$transactionId";
        //         $json = file_get_contents($url); // this WILL do an http request for you
        //         $data = json_decode($json);

        //         // $order_id = (isset($data->{'Description'}) && $data->{'Description'} != "") ? $data->{'Description'} : "";
        //         $order_id = (isset($_REQUEST['order_id']) && $_REQUEST['order_id'] != "") ? $_REQUEST['order_id'] : "";
        //         if (isset($order_id) && $order_id != '') {

        //             $order = Order::find()->where(['id' => $order_id])->one();
        //             $orderde = OrderDetail::find()->where(['order_id' => $order_id])->one();
        //             if ($orderde->product_id == 9999) {
        //                 Yii::$app->mycomponent->newOrderNotification($order, "S");
        //             }

        //             if ($order) {
        //                 Yii::$app->common->savePaymentResponse($data, $order->user_id, $transactionId);
        //                 $order->is_payment_received = 'Y';
        //                 $order->save(false);
        //                 $result['order_id'] = $order->id;

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

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

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

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

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

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

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


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

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

        //                 if ($device_token_iphone != array()) {
        //                     Yii::$app->mycomponent->pushnotification_iphone_array($device_token_iphone, $body_i);
        //                 }
        //             } else {
        //                 return Yii::$app->apifunction->setResponse('Order not found', false, 400, 400);
        //             }
        //         }
        //         return Yii::$app->apifunction->setResponse('success_payment', false, 200, 200, $result);
        //     } else {
        //         $result['is_done'] = false;
        //         return Yii::$app->apifunction->setResponse('failed_payment', false, 200, 400, $result);
        //     }
        // } else {
        //     $result['is_done'] = false;
        //     return Yii::$app->apifunction->setResponse('failed_payment', false, 200, 400, $result);
        // }
    }

    public function actionTestsms()
    {
        $otp = Yii::$app->common->generate_otp_code();
        Yii::$app->common->sendsms("123456", 'Your '.Yii::$app->params['appName'].', confirmation code is :'.$otp.'. It expires in 30 minutes, one-time use only.');
        print_r("Done");
        die;
    }

    public function actionGettechname($order_id)
    {
        $order = Order::find()->where(['id' => $order_id])->one();

        $tech_id = $order->rider_id;
        $technicians = Users::find()->where(['id' => $tech_id])->one();
        $tech = isset($technicians->user_type) ? (int)$technicians->user_type : 1;
        $idarray = Usertype_master::find()->select('name')->where(['id' => $tech])->one();
        return $idarray->name;
    }

    public function actionPurchaseordernewservice($technician_id)
    {
        $this->layout = false;
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);

        extract($_POST);
        $user_order = Order::find()->where(['user_id' => yii::$app->user->id, 'status' => ['3', '4']])->one();

        if ($user_order) {
            return Yii::$app->apifunction->setResponse("You have an ongoing order so you can't place new one until it's complete", false, 200, 200);
        }

        $tech_charge_setting = Setting::find()->where(['key' => 'tech_charge'])->one()->value;
        $techcharges = $tech_charge_setting;

        $vat_dis = Setting::find()->where(['key' => 'vat'])->one();

        $carts = Cart::find()->where(['user_id' => yii::$app->user->id, 'product_id' => 9999, 'is_deleted' => 'N', 'is_active' => 'Y', 'is_buy' => 'N']);
        $start = isset($start) ? $start : 0;
        $limit = isset($limit) ? $limit + 1 : 11;
        $carts = $carts->offset($start)->limit($limit);
        $carts = $carts->orderBy('id DESC')->all();
        if ($carts) {
            $i = 0;
            $title = '';
            $image = '';
            $type = '';
            $price = 0;
            $base_price = 100;
            $discount_price = 0;
            $discount = 1;
            $product_id = null;
            $brand_id = null;
            $total_quantity = 0;
            $product_type = 'R';
            $order_detail_ids = [];
            $cart_ids = [];
            $product_ids_quantity = [];
            $is_vendor = true;
            $is_tech_id = $technician_id;
            $is_tech_type = 0;
            $is_tech_charge = 0;
            //(2) Find the vendor based on the nearest location (from user to vendor)
            $sett_dis = Setting::find()->where(['key' => 'distance'])->one();

            if ($sett_dis) {
                $distance = $sett_dis->value;
            } else $distance = 100; //static distance 10km

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

                $order_detail = new OrderDetail;

                if ($value->product_id != null) {
                    if ($value->product_id == 9999) {
                        $techcharge = Users::findOne($technician_id);

                        if ($techcharge->rider_charge == "0" || $techcharge->rider_charge == "0.00") {
                            $techcharges = $tech_charge_setting;
                        } else {
                            $techcharges = $techcharge->rider_charge;
                        }
                        $Usertype_master = Usertype_master::findOne($techcharge->user_type);
                        $is_vendor = false;
                        $title = "Service Booking";
                        $image = Url::to('@web/' . "/img/logo-color.png", true);
                        $type = "Service";
                        $price = $techcharges;
                        $description = "Service Booking for " . $Usertype_master->name;
                        $discount = 0;
                        $is_tech_charge = $techcharges;
                        $base_price = 0;
                        $product_id = 9999;
                        $brand_id = 0;
                        $is_tech_id = $technician_id;
                        $is_tech_type = $techcharge->user_type;
                        $product_type = "S";
                        $discount_percentage = 0;
                        $discounted_price = number_format(1 * round($price, 2), 2);
                    }
                }

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

                $order_detail->vat_percentage = $vat_dis->value;
                $order_detail->vat_value = ((($value->quantity * $price) * $vat_dis->value) / 100);

                $order_detail->status = '1';
                $order_detail->i_date = time();
                $order_detail->product_type = $product_type ?? 'S';

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

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

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

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

            $vendors = Users::find()->where(['id' => $is_tech_id, 'is_deleted' => 'N', 'is_active' => 'Y', 'profile_status' => 'A', 'notification_enabled' => 'Y', 'is_request_recieve' => 'N', 'is_online' => 'Y'])
                ->andWhere(['NOT', ['latitude' => null, 'longitude' => null]])->one();

            if (is_object($vendors)) {
                $vendors = ArrayHelper::map($vendors, 'latitude', 'longitude', 'id');
                $vendor_id = "";
                $u_lat = (isset($address->latitude) && $address->latitude != "") ? $address->latitude : "";
                $u_long = (isset($address->longitude) && $address->longitude != "") ? $address->longitude : "";
                $delivery_charge = 0;
                $history_ids = [];
                foreach ($vendors as $key => $value) {
                    if ($vendor_id == "") {
                        $vendor_id = $key;
                    }
                    $history = new Vendorhistory;
                    $history->vendor_id = $key;
                    $history->i_date = time();
                    $history->save(false);
                    $history_ids[] = $history->id;
                }
                if (isset($delivery_method) && $delivery_method != "D") {
                    $delivery_charge = Yii::$app->common->calculateDelivaryCharge($vendor_id, $u_lat, $u_long);
                }

                $order = new Order;
                $order->user_id = Yii::$app->user->id;
                $order->vendor_id = null;
                $order->rider_id = $is_tech_id;

                $request_recieve = Users::findOne($is_tech_id);
                if ($request_recieve) {
                    $request_recieve->is_request_recieve = 'Y';
                    $request_recieve->save(false);
                }

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

                if(!isset($address)){
                    if ($request_recieve) {
                        $request_recieve->is_request_recieve = 'N';
                        $request_recieve->save(false);
                    }
                    return Yii::$app->apifunction->setResponse('Sorry location not found please add address then after contunue booking...', false, 400, 400);
                }


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

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

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

                $order->i_date = time();
                $order->u_date = time();
                $promo_code_price = (float)(($base_price * $order->promocode_discount) / 100);
                $vtAmount = ((($base_price - ($promo_code_price + $order->product_discount_price)) * $vat_dis->value) / 100);
                $order->vat_percentage = $vat_dis->value;
                $order->vat_value = $vtAmount;



                $order->total_price = $base_price - ($promo_code_price + $order->product_discount_price) + $cancelation_charge + $vtAmount;

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

                $order_log = new Orderlog;
                $order_log->order_id = $order->id;
                $order_log->status = $order->status;
                $order_log->i_by = $order->rider_id;
                $order_log->i_date = $order->i_date;
                $order_log->save(false);

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

                //Now Clear the cart List;
                Cart::updateAll(['is_buy' => 'Y'], ['id' => $cart_ids]);
                $result['order_id'] = $order->id;
                //                    \Yii::info("===================Before Notification==============", 'pushnotification');
                //                    \Yii::info($order, 'pushnotification');
                //                    \Yii::info("===================Before Notification==============", 'pushnotification');

                Yii::$app->mycomponent->newOrderNotification($order,"S");
                //Yii::$app->mycomponent->descriptionParameter($order->id, $order->total_price, "T");
                return Yii::$app->apifunction->setResponse('success_place_order', true, 200, 200, $result);
            } else {
                $noti = new Notification;
                $noti->from_user = Yii::$app->user->id;
                $noti->to_user = Yii::$app->user->id;
                $noti->notification_type = 'no_rider_found';
                $noti->message = Yii::t('app', Yii::$app->params['rider_not_available_for_order']);
                $noti->type = 'U';
                $noti->i_by = Yii::$app->user->id;
                $noti->i_date = date('Y-m-d H:i:s');
                $noti->i_datetime = time();
                $noti->save(false);
                $body_a = array();
                $body_a['data']['notification_type'] = 'no_rider_found';
                $body_a['data']['message'] = Yii::t('app', Yii::$app->params['rider_not_available_for_order']);
                $body_i = array();
                $body_i['data'] = array('alert' => Yii::t('app', Yii::$app->params['rider_not_available_for_order']));
                $body_i['data']['badge'] = 1;
                $body_i['data']['notification_type'] = 'no_rider_found';
                $body_i['data']['sound'] = 'default';
                $body_i['data']['message'] = Yii::t('app', Yii::$app->params['rider_not_available_for_order']);
                $body_i['data']['alert'] = Yii::t('app', Yii::$app->params['rider_not_available_for_order']);
                $body_i['data']['text'] = Yii::t('app', Yii::$app->params['rider_not_available_for_order']);
                $body_i['data']['title'] = Yii::t('app', Yii::$app->params['rider_not_available_for_order']);


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

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

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

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

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

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

    public function actionPaymentprocesstech($order_id)
    {
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
        $user = Users::findOne(Yii::$app->user->id);

        $order = Order::find()->alias('O')->where(['O.id' => $order_id, 'O.user_id' => $user->id])->one();
        if ($order) {
            $oid = $order->id;
            $amount = $order->total_price;
            $url = Yii::$app->common->paymentProcess($oid, $amount, "T");
            if ($url != '') {
                return $url;
            } else {
                return "";
            }
        } else {
            return "";
        }
    }

    public function actionOrderpayment(){

        $connection = Yii::$app->getDb();
        $command = $connection->createCommand("select user_id from user_vendor where vendor_id = 4 AND is_active = 'Y' AND is_deleted = 'N' GROUP BY user_id");
        $result = $command->queryAll();

        echo count($result);

    }

    public function actionReview()
    {

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

        //check user is guest or not
        Yii::$app->apifunction->checkLoggeduser(Yii::$app->user->identity->accessToken);
        extract($_POST);
        $result['overall_rating'] = Users::findOne($tech_id)->rating;
        $result['review_count'] = (int)Review::find()->where(['to_id' => $tech_id])->count();

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


        //Lets  gets all review  list
        $reviews = Review::find()->where(['to_id' => $tech_id, '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
}
