<?php
namespace backend\controllers;

use Yii;
use common\models\LoginForm;
use common\models\User;
use yii\web\Response;
use backend\models\FoodItems;
use backend\models\GoalType;
use backend\models\FavoriteFood;
use backend\models\DailyFeedback;
use backend\models\WeeklyData;
use backend\models\Meal;
use backend\models\Clients;
use backend\models\Recipes;
use backend\models\ApprovedFood;
use backend\models\FavoriteMeal;
use backend\models\FavoriteRecipe;
use backend\models\RelaxationTechniques;
use backend\models\WeeklyPhotos;
use backend\models\CommunityForums;

use backend\components\Utils;
use stdClass;

class ApiController extends \yii\web\Controller
{

    public $enableCsrfValidation = false;
    public $token = 'dOalTNY3QEazP2gBkrL3jx:APA91bFZM-M_GFXF4ADXP4wRSXAHti-vGy8iTutXVC1odYpq3GxixwyVF3a5JwKJdrWemoCzrfjcwTx65YmeDlr_FL_0r5L0VoXb_nFGBGnGocyJCLBq6NumP-BxTGKcTMPnA9Vm6ffj';
    public $server_id = 'AAAApnsbVak:APA91bEc-LPwQry2_f2XJd2Q3gJGLmopSCjR93N9_8ZlPqtRR7LD5yttdicgMqI_Dah1QbsLtQiojO306h05KQn0LM3g1cmo7qkAfK92FURFAs5ULrkky_Ruzqx_OOsZxeC3WxDtrXE7';
    private $nutrition_app_id = 'b5ec4327';
    private $nutrition_app_key = 'df0be84f2a833f1c3e279b498c6d14c6';
    /**
     * User login for login user in app
     *
     * @param string $username of user.
     * @param string $password of user.
     * @return array of user information
     */
    public function actionUserlogin()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $model = new LoginForm();
        $postdata = file_get_contents("php://input");
        $postdata = json_decode($postdata, true);
        $model->attributes = $postdata;

        $url = 'https://trackapi.nutritionix.com/v2/auth/signin';
        $headers = array(
            'x-app-id:' . $this->nutrition_app_id,
            'x-app-key:' . $this->nutrition_app_key,
            'accept: application/json',
            'content-type: application/json'
        );
        $data = json_encode(
            array(
                "email" => 'prefusion-' . $postdata['username'],
                "password" => Utils::$nutritionix_password_for_user,
                // "first_name"  => explode(' ',$postdata['name'])[0]
            )
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $response = curl_exec($ch);

        curl_close($ch);
        $response = json_decode($response);

        $testing_users = ['bryan.jonas@gmail.com', 'sethtest11@yahoo.com', 'sethtest13@yahoo.com', 'srdtest@yahoo.com'];
        // $testing_users = [];
        // for login without pass
        if (in_array(strtolower($model->username), $testing_users)) {
            goto abc;
        }

        if ($model->login()) {
            $user = User::find()->where(['username' => $model->username])->orWhere(['email' => $model->username])->one();

            // --------------

            if (isset($response->message) && ($response->message == "There is no existing account that matches provided information")) {
                $url = 'https://trackapi.nutritionix.com/v2/auth/signup';
                $headers = array(
                    'x-app-id:' . $this->nutrition_app_id,
                    'x-app-key:' . $this->nutrition_app_key,
                    'accept: application/json',
                    'content-type: application/json'
                );
                $data = json_encode(
                    array(
                        "email" => 'prefusion-' . $user->email,
                        "password" => Utils::$nutritionix_password_for_user,
                        //$postdata['password']
                        "first_name" => $user->name
                    )
                );
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

                $response = curl_exec($ch);

                curl_close($ch);
                $response = json_decode($response);
            }

            // --------------
            // for login without pass
            if (in_array($model->username, $testing_users)) {
                abc:
                $user = User::find()->where(['username' => $model->username])->orWhere(['email' => $model->username])->one();
            }

            if (isset($postdata['fb_token']) && !empty($postdata['fb_token'])) {
                $user->fb_token = $postdata['fb_token'];

            }
            if (isset($response) && !empty($response->user) && !empty($response->{'x-user-jwt'})) {
                $user->nutritionix_user_id = $response->user->id;
                $user->nutritionix_user_jwt = $response->{'x-user-jwt'};
            }
            $user->save(false);

            $innerdata = new \stdClass();
            $restrict_array = array('verification_token', 'role', 'created_at', 'updated_at', 'auth_key', 'password_hash', 'password_reset_token', 'firstname', 'lastname', 'phone');
            foreach ($user as $key => $value) {
                if (in_array($key, $restrict_array)) {
                    continue;
                }

                if ($value === null) {
                    $value = '';
                }

                $innerdata->$key = (string) $value;
            }
            $innerdata->goal_type = GoalType::find()->select(['id', 'name'])->where(['id' => $innerdata->goal_type])->one();
            if (!empty($user->image)) {
                $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/user_logo/' . $user->image;
            } else {
                $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/user_logo/' . "my_default_picture.png";
            }

            $innerdata->image = $img;
            $innerdata->nutrition_app_id = $this->nutrition_app_id;
            $innerdata->nutrition_app_key = $this->nutrition_app_key;
            // suggestion for reverce page in app
            $innerdata->suggestion = false;
            foreach ($innerdata as $key => $value) {
                if (in_array($key, ['dob', 'height', 'c_weight'])) {
                    if ($value == '') {
                        $innerdata->suggestion = true;
                        break;
                    }
                }
                if (in_array($key, ['goal_type', 'fat_percentage'])) {
                    if ($value == '') {
                        $innerdata->suggestion = true;
                        break;
                    }
                }
            }
            return array('status' => 200, 'message' => 'Login successfully', 'data' => $innerdata);
        } else {
            $errors = $model->getErrors();
            $error = '';
            foreach ($errors as $val) {
                $error = isset($val[0]) ? $val[0] : '';
                break;
            }
            $data = new \stdClass();

            return array('status' => 400, 'message' => $error, 'data' => $data);
        }
    }
    public function actionUserlogout()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = file_get_contents("php://input");
        $postdata = json_decode($postdata, true);
        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            $user = User::find()->where(['id' => $postdata['uid']])->one();
            if (!$user) {
                $data = new \stdClass();
                return array('status' => 200, 'message' => 'User logout', 'data' => $data);
            }
            $user->fb_token = NULL;
            $user->save(false);
            $data = new \stdClass();
            return array('status' => 200, 'message' => 'User logout', 'data' => $data);
        } else {
            $data = new \stdClass();
            return array('status' => 200, 'message' => 'User logout', 'data' => $data);
        }
    }
    public function actionUsercreate()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }

        $model = new User();
        $model->attributes = $postdata;
        $model->password_hash = Yii::$app->security->generatePasswordHash($model->password);


        if (!empty($model) && $model->validate()) {
            if (isset($postdata['isenrolled']) && !empty($postdata['isenrolled'])) {
                if (isset($postdata['client_code']) && !empty($postdata['client_code'])) {
                    $client = Clients::find()->where(['client_id' => trim($postdata['client_code'])])->one();
                    if (!empty($client)) {
                        $model->height = $client->height;
                        $model->dob = $client->dob;
                        $model->calories_macro = $client->calories_macro;
                        $model->carbo_percentage = $client->carbs_percentage;
                        $model->fat_percentage = $client->fat_percentage;
                        $model->protein_percentage = $client->protein_percentage;
                        $model->c_weight = $client->weight;
                        $model->goal_type = $client->goal_type;
                    } else {
                        $data = new \stdClass();
                        return array('status' => 400, 'message' => 'Client code is not correct', 'data' => $data);
                    }
                } else {
                    $data = new \stdClass();
                    return array('status' => 400, 'message' => 'client code not found', 'data' => $data);
                }
            }
            $model->auth_key = Yii::$app->security->generateRandomString();
            $model->generateEmailVerificationToken();
            $model->status = '10';
            $model->role = '1';
            $model->last_login_time = time();

            $url = 'https://trackapi.nutritionix.com/v2/auth/signup';
            $headers = array(
                'x-app-id:' . $this->nutrition_app_id,
                'x-app-key:' . $this->nutrition_app_key,
                'accept: application/json',
                'content-type: application/json'
            );
            $data = json_encode(
                array(
                    "email" => 'prefusion-' . $postdata['email'],
                    "password" => Utils::$nutritionix_password_for_user,
                    "first_name" => explode(' ', $postdata['name'])[0]
                )
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            $response = curl_exec($ch);

            curl_close($ch);
            $response = json_decode($response);

            if (isset($response) && !empty($response->user) && !empty($response->{'x-user-jwt'})) {
                $model->nutritionix_user_id = $response->user->id;
                $model->nutritionix_user_jwt = $response->{'x-user-jwt'};
            } else {
                $data = new \stdClass();
                return array('status' => 400, 'message' => $response->message, 'data' => $data);
            }

            $model->save(false);
            $innerdata = new \stdClass();
            $restrict_array = array(
                'verification_token',
                'created_at',
                'updated_at',
                'auth_key',
                'password_hash',
                'password_reset_token'
            );
            foreach ($model as $key => $value) {
                if (in_array($key, $restrict_array)) {
                    continue;
                }
                if ($value === null) {
                    $value = '';
                }
                $innerdata->$key = (string) $value;
            }

            $innerdata->goal_type = GoalType::find()->select(['id', 'name'])->where(['id' => $innerdata->goal_type])->one();

            if (!empty($model->image)) {
                $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/user_logo/' . $model->image;
            } else {
                $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/user_logo/' . "my_default_picture.png";
            }
            $innerdata->image = $img;
            $innerdata->nutrition_app_id = $this->nutrition_app_id;
            $innerdata->nutrition_app_key = $this->nutrition_app_key;
            $innerdata->nutritionix = $response;

            return array('status' => 200, 'message' => 'User signed up successfully', 'data' => $innerdata);
        } else {
            $errors = $model->getErrors();
            $error = '';
            foreach ($errors as $val) {
                $error = isset($val[0]) ? $val[0] : '';
                break;
            }
            $data = new \stdClass();
            return array('status' => 400, 'message' => $error, 'data' => $data);
        }
    }
    public function actionUserupdate()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        try {
            if (isset($postdata['uid']) && !empty($postdata['uid'])) {
                $model = User::find()->where(['id' => $postdata['uid']])->one();
                if (!empty($model)) {
                    // $model->scenario = 'api_userupdate';
                    $email = $model->email;
                    $username = $model->username;
                    $model->attributes = $postdata;
                    if ($email != $model->email) {
                        if (User::findByEmail($model->email)) {
                            return array('status' => 400, 'message' => 'Email exists!', 'data' => $data);
                        }
                    }
                    if ($username != $model->username) {
                        if (User::findByUsername($model->username)) {
                            return array('status' => 400, 'message' => 'Username exists!', 'data' => $data);
                        }
                    }
                    if (isset($postdata['password']) && !empty($postdata['password'])) {
                        $model->password_hash = Yii::$app->security->generatePasswordHash($postdata['password']);
                    }
                    if ($model->c_fat != NULL && $model->c_fat_change != NULL) {
                        $model->g_fat = $model->c_fat + (integer) explode('lbs', $model->c_fat_change)[0];
                    }
                    if ($model->c_lean != NULL && $model->c_lean_change != NULL) {
                        $model->g_lean = $model->c_lean + (integer) explode('lbs', $model->c_lean_change)[0];
                    }
                    if (isset($postdata['c_weight']) && !empty($postdata['c_weight'])) {
                        $wdata = WeeklyData::findOne(['uid' => $postdata['uid'], 'date' => date('m/d/Y')]);

                        if ($wdata) {
                            $wdata->weight = $model->c_weight;
                            $wdata->save(false);
                        }
                    }
                    $model->updated_at = time();
                    $model->save(false);
                    $innerdata = new \stdClass();
                    $restrict_array = array(
                        'verification_token',
                        'created_at',
                        'updated_at',
                        'auth_key',
                        'password_hash',
                        'password_reset_token'
                    );
                    foreach ($model as $key => $value) {
                        if (in_array($key, $restrict_array)) {
                            continue;
                        }
                        if ($value === null) {
                            $value = '';
                        }
                        $innerdata->$key = (string) $value;
                    }
                    $innerdata->goal_type = GoalType::find()->select(['id', 'name'])->where(['id' => $innerdata->goal_type])->one();
                    if (!empty($model->image)) {
                        $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/user_logo/' . $model->image;
                    } else {
                        $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/user_logo/' . "my_default_picture.png";
                    }
                    $innerdata->image = $img;
                    return array('status' => 200, 'message' => 'Updation done', 'data' => $innerdata);
                } else {
                    return array('status' => 400, 'message' => 'User not found', 'data' => $data);
                }
            } else {
                return array('status' => 400, 'message' => 'Uid not found', 'data' => $data);
            }
        } catch (Exception $e) {
            echo 'Message: ' . $e->getMessage();
            $fp = fopen(Yii::getAlias('@uploads/') . '/../files/error.txt', 'a'); //opens file in append mode  
            fwrite($fp, "\n user-update : ");
            fwrite($fp, "\n" . json_encode('Message: ' . $e->getMessage()));
            fwrite($fp, date("l jS \of F Y h:i:s A e"));
            fclose($fp);
        }
    }
    public function actionUserdelete()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            $user = User::find()->where(['id' => $postdata['uid']])->one();
            if (!empty($user)) {
                $weekly_data_all = WeeklyData::find()->where(['uid' => $user->id])->all();
                foreach ($weekly_data_all as $weekly_data) {
                    $weekly_data->delete();
                }
                @unlink(Yii::getAlias('@user_logo') . $user->image);
                $user->delete();
                return array('status' => 200, 'message' => 'User deleted', 'data' => $data);
            } else {
                return array('status' => 400, 'message' => 'User doesn\'t exists', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'uid not found', 'data' => $data);
        }
    }
    public function actionUserprofile()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->get();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            $model = User::find()->where(['id' => $postdata['uid']])->one();
            if ($model) {
                $innerdata = new \stdClass();
                $restrict_array = array(
                    'verification_token',
                    'business_type',
                    'created_at',
                    'updated_at',
                    'auth_key',
                    'password_hash',
                    'password_reset_token'
                );
                foreach ($model as $key => $value) {
                    if (in_array($key, $restrict_array)) {
                        continue;
                    }
                    if ($value === null) {
                        $value = '';
                    }
                    $innerdata->$key = (string) $value;
                }
                $innerdata->goal_type = GoalType::find()->select(['id', 'name'])->where(['id' => $innerdata->goal_type])->one();
                if (!empty($model->image)) {
                    $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/user_logo/' . $model->image;
                } else {
                    $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/user_logo/' . "my_default_picture.png";
                }
                $innerdata->image = $img;
                return array('status' => 200, 'message' => 'User found', 'data' => $innerdata);
            } else {
                return array('status' => 400, 'message' => 'User not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'uid not found', 'data' => $data);
        }
    }
    public function actionUserlist()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = array();

        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            $model = User::find()->where(['id' => $postdata['uid']])->exists();
            if ($model) {
                $models = User::find()->all();
                $listing = array();
                $restrict_array = array(
                    'verification_token',
                    'business_type',
                    'created_at',
                    'updated_at',
                    'auth_key',
                    'password_hash',
                    'password_reset_token'
                );
                foreach ($models as $model) {

                    $innerdata = new \stdClass();
                    foreach ($model as $key => $value) {
                        if (in_array($key, $restrict_array)) {
                            continue;
                        }
                        if ($value === null) {
                            $value = '';
                        }
                        $innerdata->$key = (string) $value;
                    }
                    if (!empty($model->image)) {
                        $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/user_logo/' . $model->image;
                    } else {
                        $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/user_logo/' . "my_default_picture.png";
                    }
                    $innerdata->image = $img;
                    array_push($listing, $innerdata);
                }
                return array('status' => 200, 'message' => count($models) . ' users found', 'data' => $listing);
            } else {
                return array('status' => 400, 'message' => 'Item not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'uid not found', 'data' => $data);
        }
    }
    public function actionUserimage()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = \Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();
        if (isset($postdata['uid']) && !empty($postdata['uid'])) {


            $model = User::find()->where(['id' => $postdata['uid']])->one();
            if (!empty($model)) {
                $file_name = '';
                $userimg = isset($_FILES['image']) ? $_FILES['image'] : [];
                if (!empty($userimg)) {
                    $file_name = $userimg['name'];
                    $im_ext = explode('.', $userimg['name']);
                    $profile_image = time() . '.' . end($im_ext);
                    if ($file_name == '') {
                        return array('status' => 400, 'message' => 'Image not found', 'data' => $data);
                    }
                    if ($im_ext[1] != 'png' && $im_ext[1] != 'jpg' && $im_ext[1] != 'jpeg') {
                        return array('status' => 400, 'message' => 'only .png, .jpg and .jpeg are allowed', 'data' => $data);
                    }
                    if ($model->image != NULL) {
                        @unlink(Yii::getAlias('@user_logo') . $model->image);
                    }
                    if (move_uploaded_file($userimg['tmp_name'], Yii::getAlias('@user_logo') . '' . $profile_image)) {
                        $model->image = $profile_image;
                        $model->save(false);
                    }
                    $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/user_logo/';
                    $data->image = $img . $model->image;
                    return array('status' => 200, 'message' => 'Image added', 'data' => $data);

                } else {
                    return array('status' => 400, 'message' => 'Image not found', 'data' => $data);
                }
            } else {
                return array('status' => 400, 'message' => 'User not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid not found', 'data' => $data);
        }

    }

    public function actionForgotpassword()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = array();

        if (isset($postdata['email']) && !empty($postdata['email'])) {
            $model = User::find()->where(['email' => $postdata['email']])->one();

            if ($model) {

                $link = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseurl . "/public/forgot_password?id=$model->id";

                $body = "Hi $model->name,
                    <br>
                    <br>
                    This is your Password reset link.
                    <br>
                    <br>

                    $link
                    <br>
                    <br>

                    Don't share this link with anyone. Our customer service team will never ask you for your password, OTP, credit card, or banking info.
                    <br>
                    <br>

                    Regards,
                    <br>
                    Prefusion team,
                    <br>
                    <br>

                "; {
                    // send mail to user--------------

                    Utils::sendMail($postdata['email'], $model->name, $body);

                }

                return array('status' => 200, 'message' => 'Email has been sent to your registered Email id.', 'data' => $data);
            } else {
                return array('status' => 400, 'message' => 'User not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Email Required', 'data' => $data);
        }
    }

    public function actionClientdata()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();
        if (isset($postdata['client_id']) && !empty($postdata['client_id'])) {
            $client = Clients::find()->where(['client_id' => $postdata['client_id']])->one();
            $restrict_array = array(
                'verification_token',
                'business_type',
                'created_at',
                'created_by',
                'updated_at',
                'auth_key',
                'password_hash',
                'password_reset_token'
            );
            if ($client) {
                $innerdata = new \stdClass();
                foreach ($client as $key => $value) {
                    if (in_array($key, $restrict_array)) {
                        continue;
                    }
                    if ($value == null) {
                        $value = '';
                    }
                    $innerdata->$key = (string) $value;
                }
                return array('status' => 200, 'message' => 'Client details', 'data' => $innerdata);
            } else {
                return array('status' => 400, 'message' => 'Client not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Client id not found', 'data' => $data);
        }
    }
    public function actionUsercalories()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            $model = User::find()->where(['id' => $postdata['uid']])->one();
            if (!empty($model)) {
                if (
                    isset($postdata['goal_type']) && !empty($postdata['goal_type']) &&
                    isset($postdata['carbo']) && !empty($postdata['carbo']) &&
                    isset($postdata['fat']) && !empty($postdata['fat']) &&
                    isset($postdata['protein']) && !empty($postdata['protein']) &&
                    isset($postdata['calories']) && !empty($postdata['calories'])
                ) {
                    $model->goal_type = $postdata['goal_type'] ? $postdata['goal_type'] : 1;
                    $model->carbo_percentage = $postdata['carbo'];
                    $model->fat_percentage = $postdata['fat'];
                    $model->protein_percentage = $postdata['protein'];
                    $model->calories_macro = $postdata['calories'];

                    $model->carbo_macro = round(($model->calories_macro * $postdata['carbo']) / 100);
                    $model->fat_macro = round(($model->calories_macro * $postdata['fat']) / 100);
                    $model->protein_macro = round(($model->calories_macro * $postdata['protein']) / 100);

                    $model->save(false);
                } else {
                    return array('status' => 400, 'message' => 'Given details are not enough', 'data' => $data);
                }
                $innerdata = new \stdClass();
                $restrict_array = array(
                    'verification_token',
                    'created_at',
                    'updated_at',
                    'auth_key',
                    'password_hash',
                    'password_reset_token'
                );
                foreach ($model as $key => $value) {
                    if (in_array($key, $restrict_array)) {
                        continue;
                    }
                    if ($value == null) {
                        $value = '';
                    }
                    $innerdata->$key = (string) $value;
                }
                if (!empty($model->image)) {
                    $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/user_logo/' . $model->image;
                } else {
                    $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/user_logo/' . "my_default_picture.png";
                }
                $innerdata->image = $img;
                return array('status' => 200, 'message' => 'Updation done', 'data' => $innerdata);
            } else {
                return array('status' => 400, 'message' => 'User not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid not found', 'data' => $data);
        }
    }
    public function actionFoodcreate()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }

        $model = new FoodItems();
        $model->attributes = $postdata;
        $data = new \stdClass();

        if (!empty($model) && $model->validate()) {
            if (isset($postdata['quantity']) && $postdata['quantity'] <= 0) {
                $postdata['quantity'] = 1;
            }
            //--------------------------------
            if (!$model->food_id) {
                return array('status' => 400, 'message' => 'food_id', 'data' => $data);
            }
            $app_user = User::find()->where(['id' => $postdata['created_by']])->one();
            if (!$app_user) {
                return array('status' => 400, 'message' => 'User not found', 'data' => $data);
            }

            // $file_name = '';
            $userimg = isset($_FILES['image']) ? $_FILES['image'] : [];
            if (!empty($userimg)) {
                // $file_name = $userimg['name'];
                $im_ext = explode('.', $userimg['name']);
                $food_image = time() . '.' . end($im_ext);
                if ($im_ext[1] != 'png' && $im_ext[1] != 'jpg' && $im_ext[1] != 'jpeg') {
                    return array('status' => 400, 'message' => 'only .png, .jpg and .jpeg are allowed', 'data' => $data);
                }
                if ($model->image != NULL) {
                    @unlink(Yii::getAlias('@food_images') . $model->image);
                }
                if (move_uploaded_file($userimg['tmp_name'], Yii::getAlias('@food_images') . '' . $food_image)) {
                    $model->image = $food_image;
                    $model->save(false);
                }
                $data->image = $model->image;
            }
            $model->carbs = isset($postdata['carbs']) ? $postdata['carbs'] : NULL;
            $model->fat = isset($postdata['fat']) ? $postdata['fat'] : NULL;
            $model->protein = isset($postdata['protein']) ? $postdata['protein'] : NULL;
            $model->serving_weight_grams = isset($postdata['serving_weight_grams']) && !empty($postdata['serving_weight_grams']) ? $postdata['serving_weight_grams'] : NULL;

            if ($model->quantity == 0 || $model->quantity == '' || $model->quantity == NULL) {
                $model->quantity = 1;
            }

            if (!$model->calories) {
                $model->calories = ($model->carbs * 4) + ($model->fat * 9) + ($model->protein * 4);
            }

            $model->serving_weight_grams = isset($postdata['serving_weight_grams']) && !empty($postdata['serving_weight_grams']) ? $postdata['serving_weight_grams'] : NULL;

            $model->carbs = isset($postdata['carbs']) ? $postdata['carbs'] : 0;
            $model->fat = isset($postdata['fat']) ? $postdata['fat'] : 0;
            $model->protein = isset($postdata['protein']) ? $postdata['protein'] : 0;

            $model->fiber = isset($postdata['fiber']) ? $postdata['fiber'] : 0;
            $model->created_at = time();
            $model->updated_at = time();

            // $already_created = FoodItems::find()->where(['food_id' => $model->food_id])->one();

            $model->save(false);

            //--------------------------------
            if ($app_user->food_id == NULL) {
                $app_user->food_id = $model->id;
            } else {
                $array = explode(',', $app_user->food_id);
                if (!in_array($model->id, $array)) {
                    array_push($array, $model->id);
                }
                $app_user->food_id = implode(',', $array);
            }
            $app_user->save(false);
            //------------------------------------
            $innerdata = new \stdClass();
            $restrict_array = array(
                'verification_token',
                'created_at',
                'updated_at',
                'auth_key',
                'password_hash',
                'password_reset_token'
            );
            foreach ($model as $key => $value) {
                if (in_array($key, $restrict_array)) {
                    continue;
                }
                if ($value == null) {
                    $value = '';
                }
                $innerdata->$key = (string) $value;
            }
            if (!empty($model->image)) {
                if (substr($model->image, 0, 4) == 'http') {
                    $img = $model->image;
                } else {
                    $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $model->image;
                }
            } else {
                $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/default-food.png';
            }
            $innerdata->carbs = $this->bucketarraysingle(((integer) $innerdata->carbs), 20);
            $innerdata->fat = $this->bucketarraysingle(((integer) $innerdata->fat), 10);
            $innerdata->protein = $this->bucketarraysingle(((integer) $innerdata->protein), 20, true);
            $innerdata->image = $img;

            $sample_object = new \stdClass();
            $sample_object->thumb = $img;

            $innerdata->food_name = $innerdata->name;
            $innerdata->nf_calories = $innerdata->calories;
            $innerdata->nf_protein = $model->protein;
            $innerdata->serving_unit = $innerdata->unit;
            $innerdata->nf_total_carbohydrate = $model->carbs;
            $innerdata->nf_total_fat = $model->fat;
            $innerdata->note = '';
            $innerdata->nf_dietary_fiber = '0';
            $innerdata->serving_qty = $innerdata->quantity;
            $innerdata->photo = $sample_object;
            $innerdata->nix_item_id = $innerdata->food_id;

            return array('status' => 200, 'message' => 'Food added', 'data' => $innerdata);
        } else {
            $errors = $model->getErrors();
            $error = '';
            foreach ($errors as $val) {
                $error = isset($val[0]) ? $val[0] : '';
                break;
            }
            return array('status' => 400, 'message' => $error, 'data' => $data);
        }
    }
    public function actionFoodupdate()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['id']) && !empty($postdata['id'])) {
            $model = FoodItems::find()->where(['id' => $postdata['id']])->one();
            if (!empty($model)) {

                $model->attributes = $postdata;
                $model->carbs = isset($postdata['carbs']) ? $postdata['carbs'] : $model->carbs;
                $model->fat = isset($postdata['fat']) ? $postdata['fat'] : $model->fat;
                $model->protein = isset($postdata['protein']) ? $postdata['protein'] : $model->protein;
                $model->updated_at = time();
                $model->save(false);
                $innerdata = new \stdClass();
                $restrict_array = array(
                    'verification_token',
                    'created_at',
                    'updated_at',
                    'auth_key',
                    'password_hash',
                    'password_reset_token'
                );
                foreach ($model as $key => $value) {
                    if (in_array($key, $restrict_array)) {
                        continue;
                    }
                    if ($value == null) {
                        $value = '';
                    }
                    $innerdata->$key = (string) $value;
                }
                $innerdata->nf_total_carbohydrate = $innerdata->carbs;
                $innerdata->nf_protein = $innerdata->protein;
                $innerdata->nf_total_fat = $innerdata->fat;

                $innerdata->carbs = $this->bucketarraysingle(((integer) $innerdata->carbs), 20);
                $innerdata->fat = $this->bucketarraysingle(((integer) $innerdata->fat), 10);
                $innerdata->protein = $this->bucketarraysingle(((integer) $innerdata->protein), 20, true);
                if (!empty($model->image)) {
                    if (substr($model->image, 0, 4) == 'http') {
                        $img = $model->image;
                    } else {
                        $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $model->image;
                    }
                } else {
                    $img = '';
                }
                $innerdata->image = $img;
                return array('status' => 200, 'message' => 'Updation done', 'data' => $innerdata);
            } else {
                return array('status' => 400, 'message' => 'Item not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Id not found', 'data' => $data);
        }
    }
    public function actionFoodprofile()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->get();
        $data = new \stdClass();

        if (isset($postdata['id']) && !empty($postdata['id'])) {
            $model = FoodItems::find()->where(['id' => $postdata['id']])->one();
            if ($model) {
                $innerdata = new \stdClass();
                $restrict_array = array(
                    'verification_token',
                    'business_type',
                    'created_at',
                    'updated_at',
                    'auth_key',
                    'password_hash',
                    'password_reset_token'
                );
                foreach ($model as $key => $value) {
                    if (in_array($key, $restrict_array)) {
                        continue;
                    }
                    if ($value == null) {
                        $value = '';
                    }
                    $innerdata->$key = (string) $value;
                }
                $innerdata->nf_total_carbohydrate = $innerdata->carbs;
                $innerdata->nf_protein = $innerdata->protein;
                $innerdata->nf_total_fat = $innerdata->fat;

                $innerdata->carbs = $this->bucketarraysingle(((integer) $innerdata->carbs), 20);
                $innerdata->fat = $this->bucketarraysingle(((integer) $innerdata->fat), 10);
                $innerdata->protein = $this->bucketarraysingle(((integer) $innerdata->protein), 20, true);
                if (!empty($model->image)) {
                    if (substr($model->image, 0, 4) == 'http') {
                        $img = $model->image;
                    } else {
                        $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $model->image;
                    }
                } else {
                    $img = '';
                }
                $innerdata->image = $img;
                return array('status' => 200, 'message' => 'Item found', 'data' => $innerdata);
            } else {
                return array('status' => 400, 'message' => 'Item not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Id not found', 'data' => $data);
        }
    }
    public function actionFoodlist()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['id']) && !empty($postdata['id'])) {
            $model = User::find()->where(['id' => $postdata['id']])->exists();
            if ($model) {
                $models = FoodItems::find()->where(['created_by' => $postdata['id']])->orderBy(['created_at' => SORT_DESC])->all();
                if (isset($postdata['search']) && !empty($postdata['search'])) {
                    $models = FoodItems::find()
                        ->filterWhere(['like', 'name', $postdata['search']])
                        ->andWhere(['created_by' => $postdata['id']])
                        ->orderBy(['created_at' => SORT_DESC])
                        ->all();
                }
                $listing = array();
                $restrict_array = array(
                    'verification_token',
                    'business_type',
                    'created_at',
                    'updated_at',
                    'auth_key',
                    'password_hash',
                    'password_reset_token'
                );
                foreach ($models as $model) {
                    $innerdata = new \stdClass();
                    $innerdata->customFood = false;
                    $isCustom = explode('/', $model->food_id);
                    if (count($isCustom) > 1 && $isCustom[1] == 'app') {
                        $innerdata->customFood = true;
                    } else {
                        continue;
                    }
                    foreach ($model as $key => $value) {
                        if (in_array($key, $restrict_array)) {
                            continue;
                        }
                        if ($value === null) {
                            $value = '';
                        }
                        $innerdata->$key = $value;
                    }

                    $innerdata->nf_total_carbohydrate = $innerdata->carbs;
                    $innerdata->nf_protein = $innerdata->protein;
                    $innerdata->nf_total_fat = $innerdata->fat;

                    $innerdata->carbs = $this->bucketarraysingle(((integer) $innerdata->carbs), 20);
                    $innerdata->fat = $this->bucketarraysingle(((integer) $innerdata->fat), 10);
                    $innerdata->protein = $this->bucketarraysingle(((integer) $innerdata->protein), 20, true);
                    if (!empty($model->image)) {
                        if (substr($model->image, 0, 4) == 'http') {
                            $img = $model->image;
                        } else {
                            $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $model->image;
                        }
                    } else {
                        $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/default-food.png';
                    }
                    if (FavoriteFood::findOne(['uid' => $postdata['id'], 'food_id' => $innerdata->id])) {
                        $innerdata->favorite = 1;
                    } else {
                        $innerdata->favorite = 0;
                    }
                    $innerdata->image = $img;

                    $sample_object = new \stdClass();
                    $sample_object->thumb = $img;

                    $innerdata->food_name = $innerdata->name;
                    $innerdata->nf_calories = $innerdata->calories;
                    $innerdata->serving_unit = $innerdata->unit;

                    $innerdata->note = '';
                    $innerdata->nf_dietary_fiber = '0';
                    $innerdata->serving_qty = $innerdata->quantity;
                    $innerdata->photo = $sample_object;
                    $innerdata->nix_item_id = $innerdata->food_id;

                    array_push($listing, $innerdata);
                }
                if (isset($postdata['date']) && !empty($postdata['date'])) {
                    $incremented_meal_number = Meal::find()->where(['uid' => $postdata['id'], 'date' => $postdata['date']])->max('meal');
                    $data->meal_number = ++$incremented_meal_number;
                }
                $data->food = $listing;
                return array('status' => 200, 'message' => count($models) . ' Items found', 'data' => $data);
            } else {
                return array('status' => 400, 'message' => 'User not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Id not found', 'data' => $data);
        }
    }
    public function actionFoodimage()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['id']) && !empty($postdata['id'])) {
            $model = FoodItems::find()->where(['id' => $postdata['id']])->one();
            if (!empty($model)) {
                $file_name = '';
                $userimg = isset($_FILES['image']) ? $_FILES['image'] : [];
                if (!empty($userimg)) {
                    $file_name = $userimg['name'];
                    $im_ext = explode('.', $userimg['name']);
                    $food_image = time() . '.' . end($im_ext);
                    if ($file_name == '') {
                        return array('status' => 400, 'message' => 'Image not found', 'data' => $data);
                    }
                    if ($im_ext[1] != 'png' && $im_ext[1] != 'jpg' && $im_ext[1] != 'jpeg') {
                        return array('status' => 400, 'message' => 'only .png, .jpg and .jpeg are allowed', 'data' => $data);
                    }
                    if ($model->image != NULL) {
                        @unlink(Yii::getAlias('@food_images') . $model->image);
                    }
                    if (move_uploaded_file($userimg['tmp_name'], Yii::getAlias('@food_images') . '' . $food_image)) {
                        $model->image = $food_image;
                        $model->save(false);
                    }
                    $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $model->image;
                    $data->image = $img;
                    return array('status' => 200, 'message' => 'Image added', 'data' => $data);

                } else {
                    return array('status' => 400, 'message' => 'Image not found', 'data' => $data);
                }
            } else {
                return array('status' => 400, 'message' => 'Item not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Id not found', 'data' => $data);
        }
    }
    public function actionFooddelete()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();
        if (isset($postdata['id']) && !empty($postdata['id'])) {
            $user = FoodItems::find()->where(['id' => $postdata['id']])->one();
            if (!empty($user)) {
                @unlink(Yii::getAlias('@food_images') . $user->image);
                $user->delete();
                return array('status' => 200, 'message' => 'Item deleted', 'data' => $data);
            } else {
                return array('status' => 400, 'message' => 'Item doesn\'t exists', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Id not found', 'data' => $data);
        }
    }
    // ---------------------------------
    public function actionFavoritefoodadd()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $model = new FavoriteFood();
        $model->attributes = $postdata;
        $data = new \stdClass();

        if (!empty($model) && $model->validate()) {
            if (FavoriteFood::findOne(['uid' => $model->uid, 'food_id' => $model->food_id])) {
                return array('status' => 400, 'message' => 'Food added already! ', 'data' => $data);
            }
            $food = FoodItems::findOne(['id' => $model->food_id]);
            if (!$food) {
                return array('status' => 400, 'message' => 'Food not found! ', 'data' => $data);
            }
            $model->created_at = time();
            $model->updated_at = time();
            $model->save(false);
            $innerdata = new \stdClass();
            $restrict_array = array(
                'verification_token',
                'created_at',
                'updated_at',
                'auth_key',
                'password_hash',
                'password_reset_token'
            );
            foreach ($model as $key => $value) {
                if (in_array($key, $restrict_array)) {
                    continue;
                }
                if ($value == null) {
                    $value = '';
                }
                $innerdata->$key = (string) $value;
            }
            foreach ($food as $key => $value) {
                if (in_array($key, ['id', 'created_by', 'created_at', 'updated_at'])) {
                    continue;
                }
                if ($value == null) {
                    $value = '';
                }
                $innerdata->$key = (string) $value;
            }
            return array('status' => 200, 'message' => 'Food adding successfully', 'data' => $innerdata);
        } else {
            $errors = $model->getErrors();
            $error = '';
            foreach ($errors as $val) {
                $error = isset($val[0]) ? $val[0] : '';
                break;
            }
            return array('status' => 400, 'message' => $error, 'data' => $data);
        }
    }
    public function actionFavoritefoodremove()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['food_id']) && !empty($postdata['food_id'])) {
            $item = FavoriteFood::find()->where(['uid' => $postdata['uid'], 'food_id' => $postdata['food_id']])->one();
            if (!empty($item)) {
                $item->delete();
                return array('status' => 200, 'message' => 'Item removed', 'data' => $data);
            } else {
                return array('status' => 400, 'message' => 'Entry doesn\'t exists', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid or Food Id not found', 'data' => $data);
        }
    }
    public function actionFavoritefoodlist()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = array();

        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            $items = FavoriteFood::find()->where(['uid' => $postdata['uid']])->orderBy(['created_at' => SORT_DESC])->all();

            if ($items) {
                $listing = array();
                $restrict_array = array(
                    'verification_token',
                    'business_type',
                    'created_at',
                    'updated_at',
                    'auth_key',
                    'password_hash',
                    'password_reset_token'
                );
                foreach ($items as $item) {
                    $innerdata = new \stdClass();
                    $food = FoodItems::findOne(['id' => $item->food_id]);
                    if (isset($postdata['search']) && !empty($postdata['search'])) {
                        $food = FoodItems::find()
                            ->filterWhere(['like', 'name', $postdata['search']])
                            ->andWhere(['id' => $item->food_id])
                            ->one();
                        if (!$food) {
                            continue;
                        }
                    }
                    if (!$food) {
                        continue;
                    }
                    foreach ($food as $key => $value) {
                        if (in_array($key, $restrict_array)) {
                            continue;
                        }

                        if ($value == null) {
                            $value = '';
                        }
                        $innerdata->$key = (string) $value;
                    }
                    if ($innerdata->image != '') {
                        if (substr($innerdata->image, 0, 4) == 'http') {
                            $img = $innerdata->image;
                        } else {
                            $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $innerdata->image;
                        }
                    } else {
                        $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/default-food.png';
                    }
                    $innerdata->image = $img;
                    $innerdata->carbs = $this->bucketarraysingle(((integer) $innerdata->carbs), 20);
                    $innerdata->fat = $this->bucketarraysingle(((integer) $innerdata->fat), 10);
                    $innerdata->protein = $this->bucketarraysingle(((integer) $innerdata->protein), 20, true);

                    $sample_object = new \stdClass();
                    $sample_object->thumb = $img;

                    $innerdata->food_name = $innerdata->name;
                    $innerdata->nf_calories = $innerdata->calories;
                    $innerdata->nf_protein = $food->protein;
                    $innerdata->serving_unit = $innerdata->unit;
                    $innerdata->nf_total_carbohydrate = $food->carbs;
                    $innerdata->nf_total_fat = $food->fat;
                    $innerdata->note = '';
                    $innerdata->nf_dietary_fiber = '0';
                    $innerdata->serving_qty = $innerdata->quantity;
                    $innerdata->photo = $sample_object;
                    $innerdata->nix_item_id = $innerdata->food_id;
                    $innerdata->customFood = false;
                    $isCustom = explode('/', $innerdata->food_id);
                    if (count($isCustom) > 1 && $isCustom[1] == 'app') {
                        $innerdata->customFood = true;
                    }
                    array_push($listing, $innerdata);
                }
                return array('status' => 200, 'message' => count($listing) . ' Items found', 'data' => $listing);
            } else {
                return array('status' => 400, 'message' => 'Item not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid not found', 'data' => $data);
        }
    }
    public function actionFavoritefooditem()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->get();
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['food_id']) && !empty($postdata['food_id'])) {
            $item = FavoriteFood::find()->where(['uid' => $postdata['uid'], 'food_id' => $postdata['food_id']])->one();
            if ($item) {
                $item = FoodItems::find()->where(['id' => $postdata['food_id']])->one();
                return array('status' => 200, 'message' => 'Items found', 'data' => $item);
            } else {
                return array('status' => 400, 'message' => 'Item not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid or Food Id not found', 'data' => $data);
        }
    }
    // ------------------------------
    public function actionFavoritemealaddnew()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['meal_id']) && !empty($postdata['meal_id'])) {

            $fav_meal = Meal::find()->where(['id' => $postdata['meal_id'], 'favorite' => 1])->one();
            if ($fav_meal) {
                if ($fav_meal->favorite_meal && isset($postdata['fav_id'])) {

                    $favs = json_decode($fav_meal->favorite_meal);

                    foreach ($favs as $fav) {
                        if ($fav->fav_id == $postdata['fav_id']) {
                            $fav_meal->food_id = $fav->food_id;
                            $fav_meal->quantity = $fav->quantity;
                        }
                    }
                }
                $meal_date = explode(',', $postdata['date'])[0];
                $meal = Meal::findOne(['uid' => $fav_meal->uid, 'meal_name' => $postdata['meal_name'], 'date' => $meal_date ? $meal_date : date('m/d/Y'), 'status' => 1]);

                if ($meal) {
                    $foods = explode(',', $fav_meal->food_id);
                    $quantities = explode(',', $fav_meal->quantity);

                    $old_foods = explode(',', $meal->food_id);
                    $old_quantities = explode(',', $meal->quantity);

                    foreach ($foods as $key => $food) {
                        if (in_array($food, $old_foods)) {
                            foreach ($old_foods as $key1 => $old_food) {
                                if ($old_food == $food) {
                                    $old_quantities[$key1] += $quantities[$key];
                                }
                            }
                        } else {
                            array_push($old_foods, $food);
                            array_push($old_quantities, $quantities[$key]);
                        }
                    }
                    $meal->food_id = implode(',', $old_foods);
                    $meal->quantity = implode(',', $old_quantities);

                    $meal->save(false);

                    $wdataUpdated = Utils::weekDataUpdate($postdata['uid'], $meal_date);

                } else {
                    $meal = new Meal();
                    $meal->uid = $fav_meal->uid;
                    $meal->food_id = $fav_meal->food_id;
                    $meal->quantity = $fav_meal->quantity;
                    $meal->meal_name = $postdata['meal_name'] ? $postdata['meal_name'] : $fav_meal->meal_name;
                    $meal->favorite = 0;
                    $meal->date = $meal_date ? $meal_date : date('m/d/Y');
                    $meal->created_at = time();
                    $meal->updated_at = time();
                    $meal_number = Meal::find()->where(['uid' => $postdata['uid'], 'date' => $meal_date ? $meal_date : date('m/d/Y')])->max('meal');
                    $meal->meal = ++$meal_number;

                    $meal->save(false);

                    $wdataUpdated = Utils::weekDataUpdate($postdata['uid'], $meal_date);

                }
                return array('status' => 200, 'message' => 'Meal added', 'data' => $meal);
            } else {
                return array('status' => 400, 'message' => 'This Meal is not Favorite', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid or Meal Id not found', 'data' => $data);
        }
    }
    public function actionFavoritemealadd()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $model = new FavoriteMeal();
        $model->attributes = $postdata;
        $data = new \stdClass();

        if (!empty($model) && $model->validate()) {
            if (FavoriteMeal::findOne(['uid' => $model->uid, 'food_id' => $model->food_id])) {
                return array('status' => 400, 'message' => 'Food added already! ', 'data' => $data);
            }
            $foods = explode(',', $model->food_id);
            foreach ($foods as $key => $food) {
                $food_item = FoodItems::findOne(['id' => $food]);
                if (!$food_item) {
                    return array('status' => 400, 'message' => 'Food not found! ', 'data' => $data);
                }
            }
            $model->created_at = time();
            $model->updated_at = time();
            $model->save(false);
            $restrict_array = array(
                'verification_token',
                'created_at',
                'updated_at',
                'auth_key',
                'password_hash',
                'password_reset_token'
            );
            $innerdata = new \stdClass();
            foreach ($model as $key => $value) {
                if (in_array($key, $restrict_array)) {
                    continue;
                }
                if ($value == null) {
                    $value = '';
                }
                $innerdata->$key = (string) $value;
            }
            $data->favorite_meal = $innerdata;
            $data->foods = array();
            foreach ($foods as $food) {
                $food_item = FoodItems::findOne(['id' => $food]);
                $innerdata = new \stdClass();
                foreach ($food_item as $key => $value) {
                    if (in_array($key, $restrict_array)) {
                        continue;
                    }
                    if ($value == null) {
                        $value = '';
                    }
                    $innerdata->$key = (string) $value;
                }
                if (!empty($innerdata->image)) {
                    if (substr($innerdata->image, 0, 4) == 'http') {
                        $img = $innerdata->image;
                    } else {
                        $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $innerdata->image;
                    }
                } else {
                    $img = '';
                }
                $innerdata->image = $img;
                array_push($data->foods, $innerdata);
            }

            return array('status' => 200, 'message' => 'Food adding successfully', 'data' => $data);
        } else {
            $errors = $model->getErrors();
            $error = '';
            foreach ($errors as $val) {
                $error = isset($val[0]) ? $val[0] : '';
                break;
            }
            return array('status' => 400, 'message' => $error, 'data' => $data);
        }
    }
    public function actionFavoritemealremove()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['fav_meal_id']) && !empty($postdata['fav_meal_id'])) {
            $item = FavoriteMeal::find()->where(['uid' => $postdata['uid'], 'id' => $postdata['fav_meal_id']])->one();
            if (!empty($item)) {
                $item->delete();
                return array('status' => 200, 'message' => 'Item removed', 'data' => $data);
            } else {
                return array('status' => 400, 'message' => 'Entry doesn\'t exists', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid or Favorite Meal Id not found', 'data' => $data);
        }
    }
    public function actionFavoritemeallist()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = array();

        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            $items = Meal::find()->where(['uid' => $postdata['uid'], 'favorite' => "1"])->orderBy(['created_at' => SORT_DESC])->all();

            $meals = array();
            foreach ($items as $item) {
                if ($item->favorite_meal) {
                    $favorite_meal = json_decode($item->favorite_meal);
                    foreach ($favorite_meal as $meal) {
                        $meal->id = $item->id;
                        if (!isset($meal->meal_name) || empty($meal->meal_name)) {
                            $meal->meal_name = $item->meal_name;
                        }
                        array_push($meals, $meal);
                    }
                }
            }
            $items = $meals;
            if ($items) {
                $listing = array();
                $restrict_array = array('verification_token', 'business_type', 'created_at', 'updated_at', 'auth_key', 'password_hash', 'password_reset_token');
                foreach ($items as $item) {
                    $foods = explode(',', $item->food_id);
                    $innerdata = new \stdClass();
                    $names = array();
                    $innerdata->id = $item->id;
                    $innerdata->meal_name = $item->meal_name;
                    $innerdata->fav_id = $item->fav_id;
                    $innerdata->image = '';
                    foreach ($foods as $food) {
                        $food = FoodItems::findOne(['id' => $food]);
                        if ($food) {
                            if ($food->name)
                                array_push($names, $food->name);
                            if (!empty($food->image)) {
                                if (substr($food->image, 0, 4) == 'http') {
                                    $img = $food->image;
                                } else {
                                    $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $food->image;
                                }
                            }
                        }
                    }
                    $innerdata->names = implode(', ', $names);
                    $index = strrpos($innerdata->names, ",");
                    if ($index)
                        $innerdata->names[$index] = '&';
                    $innerdata->food_id = explode(',', $item->food_id);
                    $innerdata->quantity = explode(',', $item->quantity);
                    if (empty($innerdata->image)) {
                        $innerdata->image = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/recipes/default-food.png';
                    }
                    array_push($listing, $innerdata);
                }

                return array('status' => 200, 'message' => count($listing) . ' Items found', 'data' => $listing);
            } else {
                return array('status' => 200, 'message' => '0 item found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid not found', 'data' => $data);
        }
    }
    public function actionFavoritemealitem()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->get();
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['fav_meal_id']) && !empty($postdata['fav_meal_id'])) {
            $item = Meal::find()->where(['uid' => $postdata['uid'], 'id' => $postdata['fav_meal_id']])->one();
            if ($item) {
                // $item = FoodItems::find()->where(['id'=>$postdata['fav_meal_id']])->one();
                return array('status' => 200, 'message' => 'Items found', 'data' => $item);
            } else {
                return array('status' => 400, 'message' => 'Item not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid or Favorite Meal id not found', 'data' => $data);
        }
    }

    //changes by rishpal




    public function actionFeedbackupdate()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            if (isset($postdata['date']) && !empty($postdata['date'])) {
                $model = DailyFeedback::find()->where(['uid' => $postdata['uid'], 'date' => $postdata['date']])->one();
                if (!empty($model)) {

                    $model->attributes = $postdata;

                    // $model->updated_at = time();
                    $model->save(false);
                    $innerdata = new \stdClass();
                    foreach ($model as $key => $value) {
                        if ($value == null) {
                            $value = '';
                        }
                        $innerdata->$key = (string) $value;
                    }
                    return array('status' => 200, 'message' => 'Updation done', 'data' => $innerdata);
                } else {
                    return array('status' => 400, 'message' => 'Item not found', 'data' => $data);
                }
            } else {
                return array('status' => 400, 'message' => 'Date not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid not found', 'data' => $data);
        }
    }
    public function actionFeedback_range_list()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = array();

        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            if (isset($postdata['start']) && !empty($postdata['start'])) {
                $start = strtotime($postdata['start']);
                if (isset($postdata['end']) && !empty($postdata['end'])) {
                    $end = strtotime($postdata['end']);
                } else {
                    $end = time();
                }
                $items = DailyFeedback::find()
                    ->where(['uid' => $postdata['uid']])
                    ->andWhere(['between', 'created_at', $start, $end])
                    ->orderBy(['created_at' => SORT_ASC])
                    ->all();
                if ($items) {
                    return array('status' => 200, 'message' => count($items) . ' Items found', 'data' => $items);
                } else {
                    return array('status' => 400, 'message' => 'Item not found', 'data' => $data);
                }
            } else {
                return array('status' => 400, 'message' => 'start date not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid not found', 'data' => $data);
        }
    }
    public function actionFeedbacklist()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = array();

        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            $items = DailyFeedback::find()
                ->where(['uid' => $postdata['uid']])
                ->orderBy(['created_at' => SORT_ASC])
                ->all();
            if ($items) {
                return array('status' => 200, 'message' => count($items) . ' Items found', 'data' => $items);
            } else {
                return array('status' => 400, 'message' => 'Item not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid not found', 'data' => $data);
        }
    }
    public function actionFeedback()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->get();
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['date']) && !empty($postdata['date'])) {
            $items = DailyFeedback::find()
                ->where(['uid' => $postdata['uid'], 'date' => $postdata['date']])
                ->orderBy(['created_at' => SORT_ASC])
                ->one();
            if ($items) {
                return array('status' => 200, 'message' => 'Item found', 'data' => $items);
            } else {
                return array('status' => 400, 'message' => 'Item not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid or Date not found', 'data' => $data);
        }
    }
    public function actionWeekdataadd()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $model = new WeeklyData();
        $model->attributes = $postdata;
        $data = new \stdClass();


        if (!empty($model) && $model->validate()) {
            if (WeeklyData::findOne(['uid' => $model->uid, 'week' => $model->week, 'day' => $model->day])) {
                return array('status' => 400, 'message' => 'Data added already! ', 'data' => $data);
            }
            if (WeeklyData::find()->where(['uid' => $model->uid, 'week' => $model->week])->count() > 6) {
                return array('status' => 400, 'message' => 'Week\'s entries completed! ', 'data' => $data);
            }
            $model->created_at = time();
            $model->save(false);
            $innerdata = new \stdClass();
            foreach ($model as $key => $value) {
                if ($value == null) {
                    $value = '';
                }
                $innerdata->$key = (string) $value;
            }
            return array('status' => 200, 'message' => 'Data added successfully', 'data' => $innerdata);
        } else {
            $errors = $model->getErrors();
            $error = '';
            foreach ($errors as $val) {
                $error = isset($val[0]) ? $val[0] : '';
                break;
            }
            return array('status' => 400, 'message' => $error, 'data' => $data);
        }
    }
    public function actionWeekdataupdate()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['day']) && !empty($postdata['day']) && isset($postdata['week']) && !empty($postdata['week'])) {
            $model = WeeklyData::find()->where(['uid' => $postdata['uid'], 'day' => $postdata['day'], 'week' => $postdata['week']])->one();
            if (!empty($model)) {

                $model->attributes = $postdata;

                // $model->updated_at = time();
                $model->save(false);
                $innerdata = new \stdClass();
                foreach ($model as $key => $value) {
                    if ($value == null) {
                        $value = '';
                    }
                    $innerdata->$key = (string) $value;
                }
                return array('status' => 200, 'message' => 'Updation done', 'data' => $innerdata);
            } else {
                return array('status' => 400, 'message' => 'Item not found', 'data' => $data);
            }

        } else {
            return array('status' => 400, 'message' => 'Uid, Week or Day not found', 'data' => $data);
        }
    }
    public function actionWeekdatalist()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = array();

        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            $items = WeeklyData::find()
                ->where(['uid' => $postdata['uid']])
                ->orderBy(['created_at' => SORT_DESC])
                ->all();
            if ($items) {
                return array('status' => 200, 'message' => count($items) . ' Items found', 'data' => $items);
            } else {
                return array('status' => 400, 'message' => 'Item not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid not found', 'data' => $data);
        }
    }
    public function actionWeekdatainfo()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }

        // $fp = fopen(Yii::getAlias('@uploads/').'/../files/homepage.txt', 'a');//opens file in append mode  
        // fwrite($fp, "\n".json_encode($postdata));  
        // fwrite($fp, date("l jS \of F Y h:i:s A e"));  
        // fclose($fp);

        $data = new \stdClass();
        $filled = $remaining = 0;
        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['date']) && !empty($postdata['date'])) {
            $given_date = explode(',', $postdata['date'])[0];
            $wdata = WeeklyData::findOne(['uid' => $postdata['uid'], 'date' => $given_date]);
            if (!$wdata) {
                $wdata = new WeeklyData();
            }

            $user = User::findOne(['id' => $postdata['uid']]);

            if (!$user) {
                return array('status' => 400, 'message' => 'User not found.', 'data' => $data);
            }

            $wdataUpdated = Utils::weekDataUpdate($postdata['uid'], $given_date);

            $data->carbs_value_day = round($wdataUpdated['weekdata_carbs']);
            $data->fat_value_day = round($wdataUpdated['weekdata_fat']);
            $data->protein_value_day = round($wdataUpdated['weekdata_protein']);


            $data->goal_type = $user->goal_type;
            $user->last_login_time = time();
            $user->current_date = isset($postdata['current_date']) ? $postdata['current_date'] : NULL;

            if (
                $user->carbo_macro == '' || $user->carbo_macro == NULL ||
                $user->fat_macro == '' || $user->fat_macro == NULL ||
                $user->protein_macro == '' || $user->protein_macro == NULL
                // || $user->c_weight == '' || $user->c_weight == NULL
            ) {
                return array('status' => 400, 'message' => 'Please Select your Goal First!', 'data' => $data);
            }

            $water = $this->bucketarray($wdata->water, 1, 20);

            $data->calories = $wdata->calories = round($wdataUpdated['calories']);

            $data->fat_iteration = round(($user->fat_macro / 9) / 10);

            $carbs = $this->bucketarray_withgrey(($wdataUpdated['carbs_buckets'] * 20), 20, round(($user->carbo_macro / 4) / 20), false, true);
            $fat = $this->bucketarray_withgrey(($wdataUpdated['fat_buckets'] * 10), 10, round(($user->fat_macro / 9) / 10));
            $protein = $this->bucketarray_withgrey(($wdataUpdated['protein_buckets'] * 20), 20, round(($user->protein_macro / 4) / 20), false, true);

            $veggies = $this->bucketarray($wdata->veggies, 1, 5);

            $data->filled = $data->remaining = 0;
            $data->filled += $carbs['filled'];
            $data->filled += $fat['filled'];
            $data->filled += $protein['filled'];

            $data->remaining += round(($user->carbo_macro / 4) / 20) - $carbs['filled'];
            $data->remaining += round(($user->fat_macro / 9) / 10) - $fat['filled'];
            $data->remaining += round(($user->protein_macro / 4) / 20) - $protein['filled'];

            $data->remaining_data_value = round(($data->remaining / (($data->filled + $data->remaining) ? ($data->filled + $data->remaining) : 1)) * 100);
            $data->filled_data_value = round(($data->filled / (($data->filled + $data->remaining) ? ($data->filled + $data->remaining) : 1)) * 100);


            $data->carbs = $carbs['array'];
            $data->fat = $fat['array'];
            $data->protein = $protein['array'];
            // $data->water = Utils::completeArray(Utils::numberToBucketsInOne($wdata->water), 10);
            // $data->veggies = Utils::completeArray(Utils::numberToBucketsInOne($wdata->veggies), 3);

            $data->water = Utils::completeArray(Utils::numberToBuckets($wdata->water), 6);
            $data->veggies = Utils::completeArray(Utils::numberToBuckets($wdata->veggies), 3);

            // if(end($carbs['array']) == 100 && end($fat['array']) == 100 && end($protein['array']) == 100){

            //     $data->filled = array_sum(Utils::bucketsInNumber($wdata->carbs,$wdata->fat,$wdata->protein));

            // }

            // ------------Goal fat and lean calculation---------------
            // $user->g_lean = $user->c_lean + (integer)explode('lbs',$user->c_lean_change)[0];
            // $user->g_fat = $user->c_fat + (integer)explode('lbs',$user->c_fat_change)[0];
            $user->save(false);
            // ---------------------------

            $today_date = strtotime($user->current_date ? explode(',', $user->current_date)[0] : date('m/d/y'));

            $data->date = Utils::weekDates($today_date);
            $data->week = Utils::getWeekDates($given_date);
            $data->searchedDate = $given_date;
            $data->id = $postdata['uid'];
            

            if (Yii::$app->request->isAjax) {

                $array = ['html' => $this->renderPartial('//clients/app_view', [
                    'data' => $data
                ]),
                'data'=> $data
                ];

                // return $this->renderPartial('//clients/app_view', [
                //     'data' => $data
                // ]);

                return $array;

            }else{
                return array('status' => 200, 'message' => 'Daily info Updated. Carbs, fat and protein are in buckets', 'data' => $data);

            }

        } else {
            return array('status' => 400, 'message' => 'Uid or Date not found', 'data' => $data);
        }
    }
    public function actionWeekdays()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        // $data = array();
        $weekdata = array();
        $year = date('o', time());
        $week = date('W', time());
        for ($i = 0; $i < 5; $i++) {

            if ($week == 0) {
                $week = 52;
                --$year;
            }
            array_push($weekdata, $this->getdate($week, $year));
            --$week;
        }
        return array('status' => 200, 'message' => 'Weekdays', 'data' => $weekdata);
    }
    public function actionWeekdatarange()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();
        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['start_date']) && !empty($postdata['start_date']) && isset($postdata['end_date']) && !empty($postdata['end_date'])) {
            $user = User::findOne(['id' => $postdata['uid']]);
            $items = array();
            $data->weekDataUpdate = [];
            $data->test2 = [];
            // $data->test3 = $postdata['start_date'];
            // $data->test4 = $postdata['end_date'];
            for ($i = strtotime($postdata['start_date']); $i <= strtotime($postdata['end_date']); ) {
                array_push($data->test2, $i);
                // $data->test4 = 5;
                $i = date("m/d/Y", $i);

                $item = WeeklyData::find()->where(['uid' => $postdata['uid']])->andWhere(['date' => $i])->one();
                if ($item == NULL) {
                    $item = new WeeklyData();
                    $item->got_sleep = $item->feel_energetic = $item->exercise = $item->relaxation_technique = NULL;
                    $item->calories = $item->carbs = $item->fat = $item->protein = 0;
                }
                if (strtotime(date($i)) > strtotime(date("m/d/Y"))) {
                    $item->calories = $item->carbs = $item->fat = $item->protein = 0;
                }

                $weekdata = Utils::weekDataUpdate($postdata['uid'], $i);

                $weekdata_utils = new \stdClass();
                $weekdata_utils->calories = $weekdata['calories'];
                $weekdata_utils->carbsBucket = $weekdata['carbs_buckets'];
                $weekdata_utils->fatBucket = $weekdata['fat_buckets'];
                $weekdata_utils->proteinBucket = $weekdata['protein_buckets'];

                array_push($data->weekDataUpdate, $weekdata_utils);

                array_push($items, $item);

                $date = new \DateTime($i);
                $date->modify('+1 days');
                $i = strtotime($date->format('m/d/Y'));
            }
            $got_sleep = new \stdClass();
            $feel_energetic = new \stdClass();
            $exercise = new \stdClass();
            $relax_tech = new \stdClass();
            $got_sleep->yes = $got_sleep->no = $got_sleep->no_response = $feel_energetic->yes = $feel_energetic->no = $feel_energetic->no_response = $exercise->yes = $exercise->no = $exercise->no_response = $relax_tech->yes = $relax_tech->no = $relax_tech->no_response = 0;
            foreach ($items as $item) {
                if ($item->got_sleep === NULL) {
                    ++$got_sleep->no_response;
                } elseif ($item->got_sleep === 0) {
                    ++$got_sleep->no;
                } elseif ($item->got_sleep === 1) {
                    ++$got_sleep->yes;
                }
                if ($item->feel_energetic === NULL) {
                    ++$feel_energetic->no_response;
                } elseif ($item->feel_energetic === 0) {
                    ++$feel_energetic->no;
                } elseif ($item->feel_energetic === 1) {
                    ++$feel_energetic->yes;
                }
                if ($item->exercise === NULL) {
                    ++$exercise->no_response;
                } elseif ($item->exercise === 1) {
                    ++$exercise->yes;
                } elseif ($item->exercise === 0) {
                    ++$exercise->no;
                }
                if ($item->relaxation_technique == NULL) {
                    ++$relax_tech->no_response;
                } elseif ($item->relaxation_technique !== Null && $item->relaxation_technique !== 'No') {
                    ++$relax_tech->yes;
                } elseif ($item->relaxation_technique == 'No') {
                    ++$relax_tech->no;
                }
            }
            $data->got_sleep = $got_sleep;
            $data->feel_energetic = $feel_energetic;
            $data->exercise = $exercise;
            $data->relaxation_technique = $relax_tech;

            // $data->test = $data;


            // ------------------

            $data->weekDataUpdate_calories = 0;
            $data->weekDataUpdate_carbs = 0;
            $data->weekDataUpdate_fat = 0;
            $data->weekDataUpdate_protein = 0;

            foreach ($data->weekDataUpdate as $dayData) {

                $data->weekDataUpdate_calories += $dayData->calories;
                $data->weekDataUpdate_carbs += $dayData->carbsBucket;
                $data->weekDataUpdate_fat += $dayData->fatBucket;
                $data->weekDataUpdate_protein += $dayData->proteinBucket;

            }

            $data->weekDataUpdate_carbs = $data->weekDataUpdate_carbs * 20;
            $data->weekDataUpdate_fat = $data->weekDataUpdate_fat * 10;
            $data->weekDataUpdate_protein = $data->weekDataUpdate_protein * 20;

            // ------------------
            $data->test1 = $items;


            $calories_array = $carbs_array = $fat_array = $protein_array = $fiber_array = array();
            $calories_average = $carbs_average = $fat_average = $protein_average = $fiber_average = 0;
            if ($items) {
                foreach ($items as $item) {
                    array_push($calories_array, $item->calories);
                    $calories_average += $item->calories;
                    array_push($carbs_array, $item->carbs);
                    $carbs_average += $item->carbs;
                    array_push($fat_array, $item->fat);
                    $fat_average += $item->fat;
                    array_push($protein_array, $item->protein);
                    $protein_average += $item->protein;
                }
            } else {
                $calories_array = $carbs_array = $fat_array = $protein_array = $fiber_array = [0, 0, 0, 0, 0, 0, 0];
                $data->calories_array = $calories_array;
                $data->carbs_array = $carbs_array;
                $data->fat_array = $fat_array;
                $data->protein_array = $protein_array;
            }
            $data->testKey = [];

            $weekDay = date("w") == 0 ? 7 : date("w");

            $calories_average = $carbs_average = $fat_average = $protein_average = $fiber_average = 0;
            if ($items) {
                foreach ($items as $key => $item) {
                    array_push($data->testKey, $key);
                    if (date("W") == date("W", strtotime($postdata['start_date'])) && $key == ($weekDay - 1)) {
                        $data->key = $key;
                        break;
                    }
                    $calories_average += $item->calories;
                    $carbs_average += $item->carbs;
                    $fat_average += $item->fat;
                    $protein_average += $item->protein;
                }
            }
            $data->test = $calories_array;


            $data->averageOfDays = date("W") == date("W", strtotime($postdata['start_date'])) ? (($weekDay - 1) ? ($weekDay - 1) : 1) : count($calories_array);

            $data->total_calories_in_week = $calories_average;
            $data->calories_average = round($calories_average / ($data->averageOfDays));

            $data->total_carbs_in_week = $carbs_average;
            $data->carbs_average = round($carbs_average / ($data->averageOfDays));
            $data->carbs_average_array = $this->bucketarray($data->carbs_average, 20, ($user->carbo_macro / 4) / 20)['array'];


            $data->total_fat_in_week = $fat_average;
            $data->fat_average = round($fat_average / ($data->averageOfDays));
            $data->fat_average_array = $this->bucketarray($data->fat_average, 10, ($user->fat_macro / 9) / 10)['array'];

            $data->total_protein_in_week = $protein_average;
            $data->protein_average = round($protein_average / ($data->averageOfDays));
            $data->protein_average_array = $this->bucketarray($data->protein_average, 20, ($user->protein_macro / 4) / 20, true)['array'];

            $data->calories_array = $calories_array;
            $data->carbs_array = $carbs_array;
            $data->fat_array = $fat_array;
            $data->protein_array = $protein_array;



            for ($i = count($data->calories_array); $i < 7; $i++) {
                array_push($data->calories_array, 0);
            }
            for ($i = count($data->carbs_array); $i < 7; $i++) {
                array_push($data->carbs_array, 0);
            }
            for ($i = count($data->fat_array); $i < 7; $i++) {
                array_push($data->fat_array, 0);
            }
            for ($i = count($data->protein_array); $i < 7; $i++) {
                array_push($data->protein_array, 0);
            }

            $data->calories_goal = $user->calories_macro;
            if ($user->calories_macro == NULL) {
                $data->calories_goal = 0;
            }

            $data->carbs_goal = round($user->carbo_macro / 4);

            $data->fat_goal = round($user->fat_macro / 9);

            $data->protein_goal = round($user->protein_macro / 4);

            $nutrition = Utils::bucketsInNumber($data->carbs_goal, $data->fat_goal, $data->protein_goal);

            $data->carbs_goal_array = Utils::numberToBuckets($nutrition['carbs']);

            $data->fat_goal_array = Utils::numberToBuckets($nutrition['fat']);

            $data->protein_goal_array = Utils::numberToBuckets($nutrition['protein']);


            // --------Weight Section-----------//
            $weight = array();
            $weight_labels = array();
            $date = new \DateTime(date('m/d/Y'));
            $previous_nonzero_weight = 0;
            for ($i = 7; $i > 0; $i--) {

                $item = WeeklyData::find()->where(['uid' => $postdata['uid']])->andWhere(['date' => $date->format('m/d/Y')])->one();
                if ($item == NULL) {

                    $date1_condition = date('m/d/Y', strtotime('last sunday', strtotime($date->format('m/d/Y'))));
                    $date1 = new \DateTime($date->format('m/d/Y'));

                    for ($date1->modify('-1 days'); $date1->format('m/d/Y') != $date1_condition; ) {
                        $item = WeeklyData::find()->where(['uid' => $postdata['uid']])->andWhere(['date' => $date1->format('m/d/Y')])->one();
                        if ($item == NULL) {
                            $date1->modify('-1 days');
                        } else {
                            break;
                        }
                    }
                }
                if ($item == NULL) {
                    $item = new WeeklyData();
                    $item->weight = NULL;
                }
                $weight_item = $item->weight === NULL ? 0 : $item->weight; //$previous_nonzero_weight : $item->weight;
                array_push($weight, $weight_item);
                array_push($weight_labels, 'Week ' . $i);
                $date->modify('-7 days');
            }

            $previous_nonzero_weight = 0;
            foreach ($weight as $key => $weight_value) {
                if ($weight_value != 0) {
                    $previous_nonzero_weight = $weight_value;
                }
                if ($weight_value == 0) {
                    $weight[$key] = $previous_nonzero_weight;
                }
            }
            $data->weight = array_reverse($weight);

            $previous_nonzero_weight = 0;
            foreach ($data->weight as $key => $weight) {
                if ($previous_nonzero_weight == 0) {
                    $previous_nonzero_weight = $weight;
                }
                if ($weight == 0) {
                    $data->weight[$key] = $previous_nonzero_weight;
                }
            }

            $data->weight_labels = array_reverse($weight_labels);

            $old_weight = 0;
            for ($i = (count($data->weight) - 1); $i >= 0; $i--) {
                if ($old_weight == 0) {
                    $old_weight = $data->weight[$i];
                } else {
                    break;
                }
            }
            if ($old_weight == 0) {
                $old_weight = $user->c_weight;
            }

            $data->weight_change = -($data->weight[5] - $data->weight[6]);

            return array('status' => 200, 'message' => 'Items found', 'data' => $data);
        } else {
            return array('status' => 400, 'message' => 'Uid, Start Date or End Date not found', 'data' => $data);
        }
    }
    public function actionAddwater()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();
        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['date']) && !empty($postdata['date']) && isset($postdata['amount']) && $postdata['amount'] != "" ) {
            $wdata = WeeklyData::findOne(['uid' => $postdata['uid'], 'date' => $postdata['date']]);
            if (!$wdata) {
                $wdata = new WeeklyData();
                $wdata->uid = $postdata['uid'];
                $wdata->date = $postdata['date'];
                $wdata->created_at = time();
            }
            if (is_numeric($postdata['amount'])) {
                $wdata->water = (float) $postdata['amount'];
            } else {
                $data = new \stdClass();
                return array('status' => 400, 'message' => 'Invalid Amount', 'data' => $data);
            }
            $wdata->updated_at = time();
            $wdata->save(false);
            $user = User::findOne(['id' => $postdata['uid']]);
            $user->current_date = isset($postdata['current_date']) ? $postdata['current_date'] : $user->current_date;
            $user->save(false);
            $data->water = Utils::completeArray(Utils::numberToBuckets($wdata->water), ceil(($user->c_weight / 2) / 8)); //$this->bucketarray($wdata->water,1,ceil(($user->c_weight/2)/8))['array'];
            return array('status' => 200, 'message' => 'Glass added', 'data' => $data);
        } else {
            return array('status' => 400, 'message' => 'Uid or Date or Amount not found', 'data' => $data);
        }
    }
    public function actionShowwater()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = array();
        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['date']) && !empty($postdata['date'])) {
            $wdata = WeeklyData::findOne(['uid' => $postdata['uid'], 'date' => $postdata['date']]);
            if (!$wdata) {
                return array('status' => 400, 'message' => 'data not found', 'data' => $data);
            }
            $data = Utils::completeArray(Utils::numberToBucketsInOne($wdata->water), 6); //$this->bucketarray($wdata->water,1,20)['array'];
            return array('status' => 200, 'message' => 'Water detail', 'data' => $data);
        } else {
            return array('status' => 400, 'message' => 'Uid or Date not found', 'data' => $data);
        }
    }
    public function actionRemovewater()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();
        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['date']) && !empty($postdata['date'])) {
            $wdata = WeeklyData::findOne(['uid' => $postdata['uid'], 'date' => $postdata['date']]);
            if (!$wdata) {
                $wdata = new WeeklyData();
                $wdata->uid = $postdata['uid'];
                $wdata->date = $postdata['date'];
                $wdata->created_at = time();
            }
            if ($wdata->water == '' || $wdata->water == NULL) {
                $wdata->water = 0;
            } else {
                $wdata->water -= 1;
            }
            $wdata->updated_at = time();
            $wdata->save(false);
            $user = User::findOne(['id' => $postdata['uid']]);
            $data->water = $this->bucketarray($wdata->water, 1, ceil(($user->c_weight / 2) / 8))['array'];
            return array('status' => 200, 'message' => 'Glass removed', 'data' => $data);
        } else {
            return array('status' => 400, 'message' => 'Uid or Date not found', 'data' => $data);
        }
    }
    public function actionAddveggie()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();
        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['date']) && !empty($postdata['date']) && isset($postdata['amount']) && $postdata['amount'] != "" ) {
            $wdata = WeeklyData::findOne(['uid' => $postdata['uid'], 'date' => $postdata['date']]);
            if (!$wdata) {
                $wdata = new WeeklyData();
                $wdata->uid = $postdata['uid'];
                $wdata->date = $postdata['date'];
                $wdata->created_at = time();
                $wdata->updated_at = time();
            }
            // if($wdata->veggies == '' || $wdata->veggies == NULL){
            //     $wdata->veggies = 1;
            // } else {
            //     $wdata->veggies += 1;
            // }
            if (is_numeric($postdata['amount'])) {
                $wdata->veggies = (float) $postdata['amount'];
            } else {
                $data = new \stdClass();
                return array('status' => 400, 'message' => 'Invalid Amount', 'data' => $data);
            }
            $wdata->updated_at = time();
            $wdata->save(false);
            $user = User::findOne(['id' => $postdata['uid']]);
            $user->current_date = isset($postdata['current_date']) ? $postdata['current_date'] : $user->current_date;
            $user->save(false);
            $data->veggies = Utils::completeArray(Utils::numberToBuckets($wdata->veggies), 5); //$this->bucketarray($wdata->veggies,1,5)['array'];
            return array('status' => 200, 'message' => 'Veggie added', 'data' => $data);
        } else {
            return array('status' => 400, 'message' => 'Uid or Date or Amount not found', 'data' => $data);
        }
    }
    public function actionShowveggies()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = array();
        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['date']) && !empty($postdata['date'])) {
            $wdata = WeeklyData::findOne(['uid' => $postdata['uid'], 'date' => $postdata['date']]);
            if (!$wdata) {
                return array('status' => 400, 'message' => 'User not found', 'data' => $data);
            }
            $data = Utils::completeArray(Utils::numberToBucketsInOne($wdata->veggies), 3); //$this->bucketarray($wdata->veggies,1,5)['array'];
            return array('status' => 200, 'message' => 'Veggies Details', 'data' => $data);
        } else {
            return array('status' => 400, 'message' => 'Uid or Date not found', 'data' => $data);
        }
    }
    public function actionRemoveveggie()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();
        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['date']) && !empty($postdata['date'])) {
            $wdata = WeeklyData::findOne(['uid' => $postdata['uid'], 'date' => $postdata['date']]);
            if (!$wdata) {
                $wdata = new WeeklyData();
                $wdata->uid = $postdata['uid'];
                $wdata->date = $postdata['date'];
                $wdata->created_at = time();
            }
            if ($wdata->veggies == '' || $wdata->veggies == NULL) {
                $wdata->veggies = 0;
            } else {
                $wdata->veggies -= 1;
            }
            $wdata->updated_at = time();
            $wdata->save(false);
            $data->veggies = $this->bucketarray($wdata->veggies, 1, 5)['array'];
            return array('status' => 200, 'message' => 'Veggie removed', 'data' => $data);
        } else {
            return array('status' => 400, 'message' => 'Uid or Date not found', 'data' => $data);
        }
    }
    public function actionFeedbackadd()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['date']) && !empty($postdata['date'])) {
            $model = WeeklyData::findOne(['uid' => $postdata['uid'], 'date' => $postdata['date']]);
            if (!$model) {
                $model = new WeeklyData();
                $model->created_at = time();
                $model->updated_at = time();
            }
            $model->scenario = 'daily_feedback';
            $model->attributes = $postdata;

            if (!empty($model) && $model->validate()) {

                $user = User::findOne(['id' => $postdata['uid']]);
                if ($user) {
                    $user->current_date = isset($postdata['current_date']) ? $postdata['current_date'] : $user->current_date;
                    $user->save(false);
                }

                $model->updated_at = time();
                $model->save(false);
                $innerdata = new \stdClass();
                $restrict_array = array(
                    'weight',
                    'created_at',
                    'updated_at',
                    'calories',
                    'carbs',
                    'fat',
                    'protein',
                    'water',
                    'veggies'
                );
                foreach ($model as $key => $value) {
                    if (in_array($key, $restrict_array)) {
                        continue;
                    }
                    if ($value == null) {
                        $value = '';
                    }
                    $innerdata->$key = (string) $value;
                }
                return array('status' => 200, 'message' => 'Feedback added successfully', 'data' => $innerdata);
            } else {
                $errors = $model->getErrors();
                $error = '';
                foreach ($errors as $val) {
                    $error = isset($val[0]) ? $val[0] : '';
                    break;
                }
                return array('status' => 400, 'message' => $error, 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid and date are required', 'data' => $data);
        }
    }
    public function actionFeedbackview()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['date']) && !empty($postdata['date'])) {
            $model = WeeklyData::findOne(['uid' => $postdata['uid'], 'date' => $postdata['date']]);
            if (!$model) {
                $model = new WeeklyData();
                $model->created_at = time();
                $model->updated_at = time();
            }
            $innerdata = new \stdClass();
            $allowed_array = array(
                'got_sleep',
                'feel_energetic',
                'exercise',
                'relaxation_technique'
            );

            foreach ($model as $key => $value) {
                if (in_array($key, $allowed_array)) {
                    if ($value === null) {
                        $value = '';
                    }
                    $innerdata->$key = (string) $value;
                }
            }
            return array('status' => 200, 'message' => 'Feedback Details', 'data' => $innerdata);
        } else {
            return array('status' => 400, 'message' => 'Uid and date are required', 'data' => $data);
        }
    }
    public function actionRelaxationtechnique()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }

        $data = RelaxationTechniques::find()->all();

        return array('status' => 200, 'message' => 'Relaxation Techniques', 'data' => $data);
    }
    public function actionMealadd()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }

        $meal_date = explode(',', $postdata['date'])[0];

        $old_meal = Meal::findOne(['uid' => $postdata['uid'], 'meal_name' => $postdata['meal_name'], 'date' => $meal_date, 'status' => 1]);
        if ($old_meal) {
            $foods = explode(',', $postdata['food_id']);
            $quantities = explode(',', $postdata['quantity']);

            $old_foods = explode(',', $old_meal->food_id);
            $old_quantities = explode(',', $old_meal->quantity);

            foreach ($foods as $key => $food) {
                if (!FoodItems::findOne(['id' => $food])) {
                    $data = new \stdClass();
                    return array('status' => 400, 'message' => 'Food not found', 'data' => $data);
                }
                if (in_array($food, $old_foods)) {
                    foreach ($old_foods as $key1 => $old_food) {
                        if ($old_food == $food) {
                            $old_quantities[$key1] += $quantities[$key];
                        }
                    }
                } else {
                    array_push($old_foods, $food);
                    array_push($old_quantities, $quantities[$key]);
                }
            }
            $old_meal->food_id = implode(',', $old_foods);
            $old_meal->quantity = implode(',', $old_quantities);

            $old_meal->save(false);
            $innerdata = new \stdClass();
            $restrict_array = array(
                'verification_token',
                'created_at',
                'updated_at',
                'auth_key',
                'password_hash',
                'password_reset_token'
            );
            foreach ($old_meal as $key => $value) {
                if (in_array($key, $restrict_array)) {
                    continue;
                }
                if ($value == null) {
                    $value = '';
                }
                $innerdata->$key = (string) $value;
            }
            $food_array = array();
            foreach ($old_foods as $food) {
                $food = FoodItems::findOne(['id' => $food]);
                if ($food) {
                    $food_data = new \stdClass();
                    foreach ($food as $key => $value) {
                        if (in_array($key, $restrict_array)) {
                            continue;
                        }
                        if ($value == null) {
                            $value = '';
                        }
                        $food_data->$key = (string) $value;
                    }
                    if (!empty($food->image)) {
                        if (substr($food->image, 0, 4) == 'http') {
                            $img = $food->image;
                        } else {
                            $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $food->image;
                        }
                    } else {
                        $img = '';
                    }
                    $food_data->image = $img;
                    array_push($food_array, $food_data);
                }

            }
            $innerdata->food = $food_array;

            return array('status' => 200, 'message' => 'Meal added', 'data' => $innerdata);
        }

        $meal = new Meal();
        $meal->attributes = $postdata;
        $data = new \stdClass();

        if (!empty($meal) && $meal->validate()) {
            if (!User::findOne(['id' => $meal->uid])) {
                return array('status' => 400, 'message' => 'User not found', 'data' => $data);
            }
            $foods = explode(',', $meal->food_id);

            foreach ($foods as $food) {
                if (!FoodItems::findOne(['id' => $food])) {
                    return array('status' => 400, 'message' => 'Food not found', 'data' => $data);
                }
            }
            if (Meal::findOne(['uid' => $meal->uid, 'meal' => $meal->meal, 'date' => $meal->date, 'status' => 1])) {
                return array('status' => 400, 'message' => 'Meal ' . $meal->meal . ' is already added', 'data' => $data);
            }
            if (isset($postdata['quantity']) && !empty($postdata['quantity'])) {
                $foods = explode(',', $postdata['food_id']);
                $quantity = explode(',', $postdata['quantity']);

                if (count($foods) != count($quantity)) {
                    return array('status' => 400, 'message' => 'Number of food and quantity are not equal', 'data' => $data);
                }
            }
            $incremented_meal_number = Meal::find()->where(['uid' => $postdata['uid'], 'date' => $meal_date])->max('meal');
            $meal->meal = ++$incremented_meal_number;
            $meal->date = $meal_date;
            $meal->status = 1;
            $meal->created_at = time();
            $meal->updated_at = time();
            $meal->save(false);

            $innerdata = new \stdClass();
            $restrict_array = array(
                'verification_token',
                'created_at',
                'updated_at',
                'auth_key',
                'password_hash',
                'password_reset_token'
            );
            foreach ($meal as $key => $value) {
                if (in_array($key, $restrict_array)) {
                    continue;
                }
                if ($value == null) {
                    $value = '';
                }
                $innerdata->$key = (string) $value;
            }
            $food_array = array();
            foreach ($foods as $food) {
                $food = FoodItems::findOne(['id' => $food]);
                $food_data = new \stdClass();
                foreach ($food as $key => $value) {
                    if (in_array($key, $restrict_array)) {
                        continue;
                    }
                    if ($value == null) {
                        $value = '';
                    }
                    $food_data->$key = (string) $value;
                }
                if (!empty($food->image)) {
                    if (substr($food->image, 0, 4) == 'http') {
                        $img = $food->image;
                    } else {
                        $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $food->image;
                    }
                } else {
                    $img = '';
                }
                $food_data->image = $img;
                array_push($food_array, $food_data);
            }
            $innerdata->food = $food_array;

            $wdataUpdated = Utils::weekDataUpdate($postdata['uid'], $meal_date);

            return array('status' => 200, 'message' => 'Meal added', 'data' => $innerdata);
        } else {
            $errors = $meal->getErrors();
            $error = '';
            foreach ($errors as $val) {
                $error = isset($val[0]) ? $val[0] : '';
                break;
            }
            return array('status' => 400, 'message' => $error, 'data' => $data);
        }
    }
    public function actionFavMealUpdate()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();
        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['meal_id']) && !empty($postdata['meal_id']) && isset($postdata['fav_id']) && isset($postdata['fav_id'])) {
            $meal = Meal::findOne(['id' => $postdata['meal_id']]);
            if ($meal) {
                if ($meal->favorite_meal) {
                    $fav_meals = json_decode($meal->favorite_meal);
                    // echo "<pre>";
                    // print_r($fav_meals);
                    // die;
                    if (isset($postdata['food_id']) && isset($postdata['quantity'])) {
                        $fav_meals_for_change = [];
                        $check_fav = 0;
                        foreach ($fav_meals as $fav_meal) {
                            if ($fav_meal->fav_id == $postdata['fav_id']) {
                                $check_fav = 1;
                                if (isset($postdata['meal_name']) && !empty($postdata['meal_name'])) {
                                    $fav_meal->meal_name = $postdata['meal_name'];
                                }
                                $fav_meal->food_id = $postdata['food_id'];
                                $fav_meal->quantity = $postdata['quantity'];
                            }
                            array_push($fav_meals_for_change, $fav_meal);
                        }
                        if ($check_fav) {
                            $meal->favorite_meal = json_encode($fav_meals_for_change);
                            $meal->save(false);

                            $wdataUpdated = Utils::weekDataUpdate($postdata['uid'], $meal->date);

                            return array('status' => 200, 'message' => 'Fav meal updated', 'data' => $data);
                        } else {
                            return array('status' => 400, 'message' => 'Fav Meal not found', 'data' => $data);
                        }
                    } else {
                        return array('status' => 400, 'message' => 'food_id or quantity not found', 'data' => $data);
                    }

                } else {
                    return array('status' => 400, 'message' => 'Fav Meal not found', 'data' => $data);
                }
            } else {
                return array('status' => 400, 'message' => 'Fav Meal not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'uid or meal_id or fav_id not found', 'data' => $data);
        }
    }
    public function actionMealupdate()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }

        $data = new \stdClass();
        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['meal_id']) && !empty($postdata['meal_id'])) {
            if (!User::findOne(['id' => $postdata['uid']])) {
                return array('status' => 400, 'message' => 'User not found', 'data' => $data);
            }
            $meal = Meal::findOne(['id' => $postdata['meal_id']]);
            if (!empty($meal)) {
                if (isset($postdata['favorite_seperation'])) {
                    if (isset($postdata['favorite'])) {
                        if ($postdata['favorite'] == 1) {
                            $meal->favorite = 1;
                            $fav_meals = array();
                            if ($meal->favorite_meal) {
                                $fav_meals = json_decode($meal->favorite_meal);
                            }
                            if (isset($postdata['food_id']) && isset($postdata['quantity'])) {
                                $flag = 1;
                                foreach ($fav_meals as $fav_meal) {
                                    if ($fav_meal->food_id == $postdata['food_id'] && $fav_meal->quantity == $postdata['quantity']) {
                                        $flag = 0;
                                        break;
                                    }
                                }
                                if ($flag) {
                                    $fav = new \stdClass();
                                    $fav->fav_id = substr((string) time(), 5);
                                    $fav->food_id = $postdata['food_id'];
                                    $fav->quantity = $postdata['quantity'];
                                    $fav->created_at = time();
                                    array_push($fav_meals, $fav);
                                }
                            }
                            $meal->favorite_meal = json_encode($fav_meals);
                        } else if ($postdata['favorite'] == 0) {
                            $fav_meals = $fav_mealss = array();
                            if ($meal->favorite_meal) {
                                $fav_meals = json_decode($meal->favorite_meal);
                            }
                            foreach ($fav_meals as $fav_meal) {
                                if ($fav_meal->fav_id == $postdata['fav_id']) {
                                    continue;
                                }
                                array_push($fav_mealss, $fav_meal);
                            }
                            if (count($fav_mealss) == 0) {
                                $meal->favorite = 0;
                            }
                            $meal->favorite_meal = json_encode($fav_mealss);
                            if ($meal->favorite == 0) {
                                $meal->delete(); // meal delete
                            }
                        }
                    }
                } else {
                    if (isset($postdata['food_id']) && isset($postdata['quantity'])) {
                        $foods = explode(',', $postdata['food_id']);
                        $quantity = explode(',', $postdata['quantity']);

                        if (count($foods) != count($quantity)) {
                            return array('status' => 400, 'message' => 'Number of food and quantity are not equal', 'data' => $data);
                        }
                        $meal->food_id = $postdata['food_id'];
                        $meal->quantity = $postdata['quantity'];
                    }
                }

                if (isset($postdata['meal_name']) && !empty($postdata['meal_name'])) {
                    $meal->meal_name = $postdata['meal_name'];
                }

                $meal->save(false);
                $innerdata = new \stdClass();
                $restrict_array = array(
                    'verification_token',
                    'created_at',
                    'updated_at',
                    'auth_key',
                    'password_hash',
                    'password_reset_token'
                );
                foreach ($meal as $key => $value) {
                    if (in_array($key, $restrict_array)) {
                        continue;
                    }
                    if ($value == null) {
                        $value = '';
                    }
                    $innerdata->$key = (string) $value;
                }
                $foods = explode(',', $meal->food_id);
                $food_array = array();
                foreach ($foods as $food) {
                    $food = FoodItems::findOne(['id' => $food]);
                    if (!$food) {
                        continue;
                    }
                    $food_data = new \stdClass();
                    foreach ($food as $key => $value) {
                        if (in_array($key, $restrict_array)) {
                            continue;
                        }
                        if ($value == null) {
                            $value = '';
                        }
                        $food_data->$key = (string) $value;
                    }
                    if (!empty($food->image)) {
                        if (substr($food->image, 0, 4) == 'http') {
                            $img = $food->image;
                        } else {
                            $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $food->image;
                        }
                    } else {
                        $img = '';
                    }
                    $food_data->image = $img;
                    array_push($food_array, $food_data);
                }
                $innerdata->food = $food_array;

                $wdataUpdated = Utils::weekDataUpdate($postdata['uid'], $meal->date);

                return array('status' => 200, 'message' => 'Meal updated', 'data' => $innerdata);
            } else {
                return array('status' => 400, 'message' => 'Meal not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid or Meal Id not found', 'data' => $data);
        }
    }
    public function actionMealremove()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['meal_id']) && !empty($postdata['meal_id'])) {
            $model = Meal::find()->where(['id' => $postdata['meal_id'], 'uid' => $postdata['uid']])->one();
            if ($model) {
                if ($model->favorite == 0) {
                    $model->delete();
                } else {
                    $model->status = 0;
                    $model->save(false);
                }

                return array('status' => 200, 'message' => 'Meal Deleted', 'data' => $data);
            } else {
                return array('status' => 200, 'message' => 'Meal Deleted', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid or Meal Id not found', 'data' => $data);
        }
    }
    public function actionMeallist()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = array();

        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            $meals = Meal::find()->where(['uid' => $postdata['uid'], 'status' => 1])->orderBy(['created_at' => SORT_DESC])->all();
            if (isset($postdata['date']) && !empty($postdata['date'])) {
                $meals = Meal::find()->where(['uid' => $postdata['uid'], 'date' => $postdata['date'], 'status' => 1])->orderBy(['created_at' => 'DESC'])->all();
            }
            if ($meals) {
                $listing = array();
                $restrict_array = array(
                    'verification_token',
                    'business_type',
                    'created_at',
                    'updated_at',
                    'auth_key',
                    'password_hash',
                    'password_reset_token'
                );
                foreach ($meals as $food) {
                    $innerdata = new \stdClass();
                    $food_data = new \stdClass();
                    $foods = FoodItems::findOne(['id' => $food->food_id]);
                    foreach ($food as $key => $value) {
                        if (in_array($key, $restrict_array)) {
                            continue;
                        }
                        if ($value == null) {
                            $value = '';
                        }
                        $innerdata->$key = (string) $value;
                    }
                    foreach ($foods as $key => $value) {
                        if (in_array($key, $restrict_array)) {
                            continue;
                        }
                        if ($value == null) {
                            $value = '';
                        }
                        $food_data->$key = (string) $value;
                    }
                    if (!empty($food_data->image)) {
                        if (substr($food_data->image, 0, 4) == 'http') {
                            $img = $food_data->image;
                        } else {
                            $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $food_data->image;
                        }
                    } else {
                        $img = '';
                    }
                    $food_data->image = $img;
                    $innerdata->food = $food_data;
                    array_push($listing, $innerdata);
                }
                return array('status' => 200, 'message' => count($meals) . ' Meals found', 'data' => $listing);
            } else {
                return array('status' => 400, 'message' => 'Meal not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid not found', 'data' => $data);
        }
    }
    public function actionMealinfo()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['meal_id']) && !empty($postdata['meal_id'])) {
            $meal_data = Meal::find()->where(['id' => $postdata['meal_id'], 'status' => 1])->one();
            if (!$meal_data) {
                return array('status' => 400, 'message' => 'Meal not found', 'data' => $data);
            }
            $user = User::find()->where(['id' => $meal_data->uid])->one();
            if (!$user) {
                return array('status' => 400, 'message' => 'User not found', 'data' => $data);
            } else {
                $meal = array();
                $carbs = $fat = $protein = $caloriesss = 0;
                $restrict_array = array(
                    'verification_token',
                    'created_at',
                    'updated_at',
                    'auth_key',
                    'password_hash',
                    'password_reset_token'
                );
                if (isset($meal_data->quantity) && !empty($meal_data->quantity)) {
                    $foods = explode(',', $meal_data->food_id);
                    $quantitys = explode(',', $meal_data->quantity);
                    if (count($foods) != count($quantitys)) {
                        return array('status' => 400, 'message' => 'Number of food and quantity are not equal', 'data' => $data);
                    }
                    foreach ($foods as $key => $food) {
                        $food = FoodItems::findOne(['id' => $food]);
                        if (!$food) {
                            return array('status' => 400, 'message' => 'Food item not found', 'data' => $data);
                        }
                        $food_data = new \stdClass();
                        $food_data->favorite = '0';
                        if (FavoriteFood::findOne(['uid' => $meal_data->uid, 'food_id' => $food->id])) {
                            $food_data->favorite = '1';
                        }
                        foreach ($food as $abc => $value) {
                            if (in_array($abc, $restrict_array)) {
                                continue;
                            }
                            if ($value == null) {
                                $value = '';
                            }
                            $food_data->$abc = (string) $value;
                        }
                        if (!empty($food->image)) {
                            if (substr($food->image, 0, 4) == 'http') {
                                $img = $food->image;
                            } else {
                                $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $food->image;
                            }
                        } else {
                            $img = '';
                        }

                        $food_data->calories = (integer) $food_data->calories;
                        $food_data->carbs = (integer) $food_data->carbs;
                        $food_data->fat = (integer) $food_data->fat;
                        $food_data->protein = (integer) $food_data->protein;
                        $food_data->quantity = (integer) $food_data->quantity;

                        $food_data->image = $img;
                        if (!$quantitys[$key]) {
                            $quantitys[$key] = $food_data->quantity;
                        }
                        $quantity = $quantitys[$key] / $food_data->quantity;

                        $calories = $food_data->calories * $quantity;
                        $carbs += $carbss = $food_data->carbs * $quantity;
                        $fat += $fats = $food_data->fat * $quantity;
                        $protein += $proteins = $food_data->protein * $quantity;

                        $food_data->carbs = $this->bucketarraysingle(($carbss), 20);
                        $food_data->fat = $this->bucketarraysingle(($fats), 10);
                        $food_data->protein = $this->bucketarraysingle(($proteins), 20, true);
                        $food_data->calories = $calories;
                        array_push($meal, $food_data);
                    }
                } else {
                    $foods = explode(',', $meal_data->food_id);
                    foreach ($foods as $food) {
                        $std_food = new \stdClass();
                        $food = FoodItems::findOne(['id' => $food]);
                        if (!$food) {
                            return array('status' => 400, 'message' => 'Food item not found', 'data' => $data);
                        }
                        $food_data = new \stdClass();
                        $food_data->favorite = '0';
                        if (FavoriteFood::findOne(['uid' => $meal_data->uid, 'food_id' => $food->id])) {
                            $food_data->favorite = '1';
                        }
                        foreach ($food as $key => $value) {
                            if (in_array($key, $restrict_array)) {
                                continue;
                            }
                            if ($value == null) {
                                $value = '';
                            }
                            $food_data->$key = (string) $value;
                        }
                        if (!empty($food->image)) {
                            if (substr($food->image, 0, 4) == 'http') {
                                $img = $food->image;
                            } else {
                                $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $food->image;
                            }
                        } else {
                            $img = '';
                        }
                        $food_data->image = $img;

                        $food_data->carbs = (integer) $food_data->carbs;
                        $food_data->fat = (integer) $food_data->fat;
                        $food_data->protein = (integer) $food_data->protein;

                        $carbs += $food_data->carbs;
                        $fat += $food_data->fat;
                        $protein += $food_data->protein;

                        $food_data->carbs = $this->bucketarraysingle(($food_data->carbs), 20);
                        $food_data->fat = $this->bucketarraysingle(($food_data->fat), 10);
                        $food_data->protein = $this->bucketarraysingle(($food_data->protein), 20, true);
                        array_push($meal, $food_data);
                    }
                }
                $macro = new \stdClass();
                $macro->carbs = $this->bucketarraysingle(($carbs), 20);
                $macro->fat = $this->bucketarraysingle(($fat), 10);
                $macro->protein = $this->bucketarraysingle(($protein), 20, true);

                foreach ($meal_data as $key => $value) {
                    if (in_array($key, $restrict_array)) {
                        continue;
                    }
                    if ($value == null) {
                        $value = '';
                    }
                    $data->$key = (string) $value;
                }
                $data->food_id = new \stdClass();
                $data->food_id->foods = $meal;
                $data->food_id->macro = $macro;

                return array('status' => 200, 'message' => 'Calories counted', 'data' => $data);

            }
        } else {
            return array('status' => 400, 'message' => 'Meal Id not found', 'data' => $data);
        }

    }
    public function actionMeal_history()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();
        $meal_array = array();
        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['date']) && !empty($postdata['date'])) {
            $meals = Meal::find()->where(['uid' => $postdata['uid'], 'date' => $postdata['date'], 'status' => 1])->all();
            $calories_total = $calories = $carbs = $fat = $protein = 0;
            $restrict_array = array('created_by', 'created_at', 'updated_at');
            foreach ($meals as $meal) {
                $food_array = explode(',', $meal->food_id);
                $quantity_array = explode(',', $meal->quantity);

                $innerdata = new \stdClass();
                $innerdata->meal = 'Meal ' . $meal->meal;
                $innerdata->meal_name = $meal->meal_name;
                $innerdata->meal_time = date("h:i a", $meal->created_at);
                $innerdata->food = [];
                foreach ($food_array as $key => $food) {
                    $food = FoodItems::findOne(['id' => $food]);
                    $food_data = new \stdClass();
                    foreach ($food as $name => $value) {
                        if (in_array($name, $restrict_array)) {
                            continue;
                        }
                        if ($value === null) {
                            $value = '';
                        }
                        $food_data->$name = $value;
                    }

                    $quantity = $quantity_array[$key] / $food_data->quantity;
                    $food_data->calories = round($food_data->calories * $quantity);
                    $food_data->carbs = $this->bucketarraysingle(($food_data->carbs * $quantity), 20);
                    $food_data->fat = $this->bucketarraysingle(($food_data->fat * $quantity), 10);
                    $food_data->protein = $this->bucketarraysingle(($food_data->protein * $quantity), 20, true);
                    $food_data->favorite = '0';
                    if (FavoriteFood::findOne(['uid' => $postdata['uid'], 'food_id' => $food_data->id])) {
                        $food_data->favorite = '1';
                    }
                    if (!empty($food_data->image)) {
                        if (substr($food_data->image, 0, 4) == 'http') {
                        } else {
                            $food_data->image = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $food_data->image;
                        }
                    } else {
                        $food_data->image = '';
                    }
                    array_push($innerdata->food, $food_data);
                }
                array_push($meal_array, $innerdata);
            }
            $innerdata = new \stdClass();
            $innerdata->meal_array = $meal_array;
            return array('status' => 200, 'message' => 'Daily Dairy', 'data' => $innerdata);
        } else {
            return array('status' => 400, 'message' => 'Uid or Date not found', 'data' => $data);
        }
    }
    //-------------------------------------------------------------------------------
    public function actionCaloriescounter()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['goal_type']) && !empty($postdata['goal_type'])) {
            $user = User::find()
                ->where(['id' => $postdata['uid']])
                ->one();
            if (!$user) {
                return array('status' => 400, 'message' => 'User not found', 'data' => $data);
            } else {
                if (
                    $user->c_weight == '' || $user->c_weight == NULL ||
                    $user->height == '' || $user->height == NULL ||
                    $user->age == '' || $user->age == NULL
                ) {
                    return array('status' => 400, 'message' => 'Please update Weight, height and age', 'data' => $data);
                }
                $weight = ($user->c_weight * 0.453592);
                $ft = explode('ft', $user->height);
                $in = explode('in', $ft[1]);
                $height = (((integer) $ft[0] * 30.48) + ((integer) $in[0] * 2.54));
                $age = round($user->age);
                $calories = 1;

                if ($user->gender == '' || $user->gender == NULL) {
                    return array('status' => 400, 'message' => 'Gender not specified', 'data' => $data);
                }
                if ($user->gender == 'Male') {
                    $calories = 88.362 + (13.397 * $weight) + (4.799 * $height) - (5.677 * $age);
                }
                if ($user->gender == 'Female') {
                    $calories = 447.593 + (9.247 * $weight) + (3.098 * $height) - (4.330 * $age);
                }
                if ($calories == 1) {
                    return array('status' => 400, 'message' => 'Gender not matched', 'data' => $data);
                }
                $user->rmr = round($calories);
                $user->save(false);
                if ($user->gender == 'Female' || $user->gender == 'Male') {

                    if ($postdata['goal_type'] == 4) {
                        $postdata['goal_type'] = 6;
                    }

                    $goal_type = GoalType::find()->select(['id', 'factor'])->where(['id' => $postdata['goal_type']])->one();

                    if ($goal_type && $goal_type->factor) {
                        $calories = $calories * $goal_type->factor;
                    }

                }
                $data->calories = round($calories);
                return array('status' => 200, 'message' => 'Calories counted', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid or Goal Type not found', 'data' => $data);
        }
    }
    public function actionDropdown()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            $user = User::find()
                ->where(['id' => $postdata['uid']])
                ->one();
            if (!$user) {
                return array('status' => 400, 'message' => 'User not found', 'data' => $data);
            } else {
                if ($user->isenrolled == '1') {

                    $goal_type = GoalType::find()->select(['id', 'name'])->all();
                } else {
                    $goal_type = GoalType::find()->select(['id', 'name'])->where(['!=', 'name', 'Surplus'])->all();
                }
                $macro = array();
                for ($i = 1; $i < 100; $i++) {
                    if ($i % 5 == 0) {
                        array_push($macro, $i);
                    }
                }
                if (
                    $user->c_weight == '' || $user->c_weight == NULL ||
                    $user->height == '' || $user->height == NULL ||
                    $user->age == '' || $user->age == NULL ||
                    $user->gender == '' || $user->gender == NULL
                ) {
                    $calories = 1;
                } else {
                    $weight = round($user->c_weight * 0.453592);
                    $ft = explode('ft', $user->height);
                    $in = explode('in', $ft[1]);

                    $height = round(((integer) $ft[0] * 30.48) + ((integer) $in[0] * 2.54));
                    $age = round($user->age);
                    $calories = 1;
                    if ($user->gender == 'Male') {
                        $calories = 88.362 + (13.397 * $weight) + (4.799 * $height) - (5.677 * $age);
                    }
                    if ($user->gender == 'Female') {
                        $calories = 447.593 + (9.247 * $weight) + (3.098 * $height) - (4.330 * $age);
                    }
                    $calories = $calories * 1.3;

                }

                $data->macro = $macro;
                $data->goal_type = $goal_type;
                $data->suggested_calories = round($calories);
                return array('status' => 200, 'message' => 'Calories counted', 'data' => $data);

            }
        } else {
            return array('status' => 400, 'message' => 'Uid or Goal Type not found', 'data' => $data);
        }
    }
    public function actionMealreview()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }

        $data = new \stdClass();
        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['food_id']) && !empty($postdata['food_id'])) {
            $user = User::find()->where(['id' => $postdata['uid']])->one();

            $user->current_date = isset($postdata['current_date']) ? $postdata['current_date'] : $user->current_date;

            if (!$user) {
                return array('status' => 400, 'message' => 'User not found', 'data' => $data);
            } else {
                $meal = array();
                $carbs = $fat = $protein = $caloriesss = 0;
                $carbs_buckets = $fat_buckets = $protein_buckets = 0;
                $restrict_array = array(
                    'verification_token',
                    'created_at',
                    'updated_at',
                    'auth_key',
                    'password_hash',
                    'password_reset_token'
                );
                if (isset($postdata['quantity']) && !empty($postdata['quantity'])) {
                    $foods = explode(',', $postdata['food_id']);
                    $quantitys = explode(',', $postdata['quantity']);
                    if (count($foods) != count($quantitys)) {
                        return array('status' => 400, 'message' => 'Number of food and quantity are not equal', 'data' => $data);
                    }

                    foreach ($quantitys as $key => $value) {
                        if ($value <= 0) {
                            $quantitys[$key] = 1;
                        }
                    }

                    $query = "SELECT food_items.*, 
                    IF(favorite_food.food_id = food_items.id AND favorite_food.uid = food_items.created_by, TRUE, FALSE) as favorite
                    FROM food_items
                    LEFT JOIN favorite_food ON (food_items.id = favorite_food.food_id)
                    WHERE food_items.id IN (" . $postdata['food_id'] . ")
                    ORDER BY FIELD(food_items.id," . $postdata['food_id'] . ")";

                    $connection = Yii::$app->getDb();

                    $command = $connection->createCommand($query);

                    $models = $command->queryAll();

                    // foreach ($foods as $key => $food) {
                    foreach ($models as $key => $food) {
                        // $food = FoodItems::findOne(['id' => $food]);
                        if ($food) {

                            $food_data = new \stdClass();

                            // if (FavoriteFood::findOne(['uid' => $postdata['uid'], 'food_id' => $food->id])) {
                            //     $food_data->favorite = '1';
                            // } else {
                            //     $food_data->favorite = '0';
                            // }

                            foreach ($food as $abc => $value) {
                                if (in_array($abc, $restrict_array)) {
                                    continue;
                                }
                                if ($value == null) {
                                    $value = '';
                                }
                                $food_data->$abc = $value;
                            }

                            $isCustom = explode('/', $food_data->food_id);
                            if (count($isCustom) > 1 && $isCustom[1] == 'app') {
                                $food_data->customFood = true;
                            } else {
                                $food_data->customFood = false;
                            }

                            if (!empty($food_data->image)) {
                                if (substr($food_data->image, 0, 4) == 'http') {
                                    $img = $food_data->image;
                                } else {
                                    $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $food_data->image;
                                }
                            } else {
                                $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/default-food.png';
                            }

                            $food_data->calories = (float) $food_data->calories;
                            $food_data->carbs = (float) $food_data->carbs;
                            $food_data->fat = (float) $food_data->fat;
                            $food_data->protein = (float) $food_data->protein;
                            $food_data->quantity = (float) $food_data->quantity;

                            $food_data->image = $img;
                            if (!$quantitys[$key]) {
                                $quantitys[$key] = $food_data->quantity;
                            }
                            $quantity = $quantitys[$key] / $food_data->quantity;

                            $calories = $food_data->calories * $quantity;
                            $carbs += $carbss = $food_data->carbs * $quantity;
                            $fat += $fats = $food_data->fat * $quantity;
                            $protein += $proteins = $food_data->protein * $quantity;

                            $test_key = 'test_protein' . $key;


                            $food_data->carbs_value = (integer) $food_data->carbs;
                            $food_data->fat_value = (integer) $food_data->fat;
                            $food_data->protein_value = (integer) $food_data->protein;

                            $food_nutrition = Utils::bucketsInNumber($carbss, $fats, $proteins);

                            $data->$test_key = $food_nutrition;

                            $food_data->carbs = Utils::numberToBuckets($food_nutrition['carbs']);
                            $food_data->fat = Utils::numberToBuckets($food_nutrition['fat']);
                            $food_data->protein = Utils::numberToBuckets($food_nutrition['protein']);

                            $food_data->protein_value = $proteins;
                            $food_data->calories = round($calories);
                            $food_data->calories_percentage = ($food_data->calories / ($user->calories_macro ? $user->calories_macro : $food_data->calories)) * 100;
                            // $food_data->quantity = $quantitys[$key];
                            // $food_data->serving_qty = $food->quantity;
                            $food_data->serving_qty = $food_data->quantity;
                            $food_data->quantity = $quantitys[$key];
                            array_push($meal, $food_data);


                            $carbs_buckets += $food_nutrition['carbs'];
                            $fat_buckets += $food_nutrition['fat'];
                            $protein_buckets += $food_nutrition['protein'];
                        }
                    }
                } else {
                    $foods = explode(',', $postdata['food_id']);

                    foreach ($foods as $food) {
                        $std_food = new \stdClass();

                        $food = FoodItems::findOne(['id' => $food]);
                        if ($food) {

                            $food_data = new \stdClass();
                            $food_data->favorite = '0';
                            if (FavoriteFood::findOne(['uid' => $postdata['uid'], 'food_id' => $food->id])) {
                                $food_data->favorite = '1';
                            }
                            foreach ($food as $key => $value) {
                                if (in_array($key, $restrict_array)) {
                                    continue;
                                }
                                if ($value == null) {
                                    $value = '';
                                }
                                $food_data->$key = (string) $value;
                            }
                            if (!empty($food->image)) {
                                if (substr($food->image, 0, 4) == 'http') {
                                    $img = $food->image;
                                } else {
                                    $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $food->image;
                                }
                            } else {
                                $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/default-food.png';
                            }
                            $food_data->image = $img;

                            $food_data->carbs = (integer) $food_data->carbs;
                            $food_data->fat = (integer) $food_data->fat;
                            $food_data->protein = (integer) $food_data->protein;

                            $carbs += $food_data->carbs;
                            $fat += $food_data->fat;
                            $protein += $food_data->protein;

                            $food_data->carbs = $this->bucketarraysingle(($food_data->carbs), 20);
                            $food_data->fat = $this->bucketarraysingle(($food_data->fat), 10);
                            $food_data->protein = $this->bucketarraysingle(($food_data->protein), 20, true);
                            if ($food_data->calories > 0) {
                                $food_data->calories_percentage = ($food_data->calories / ($user->calories_macro ? $user->calories_macro : $food_data->calories)) * 100;
                            } else {
                                $food_data->calories_percentage = 0;
                            }
                            array_push($meal, $food_data);
                        }
                    }
                }

                $macro = new \stdClass();

                $macro->carbs = $this->numberToBuckets($carbs_buckets);
                $macro->fat = $this->numberToBuckets($fat_buckets);
                $macro->protein = $this->numberToBuckets($protein_buckets);

                if (isset($postdata['date']) && !empty($postdata['date'])) {
                    $incremented_meal_number = Meal::find()->where(['uid' => $postdata['uid'], 'date' => explode(',', $postdata['date'])[0]])->max('meal');
                    $data->meal_number = ++$incremented_meal_number;
                } else {
                    return array('status' => 400, 'message' => 'Date not found', 'data' => $data);
                }

                $data->meal = $meal;
                $data->macro = $macro;
                $data->favorite_meal = 0;

                {
                    if(isset($postdata['meal_id']) && !empty($postdata['meal_id'])){
                        $fav_meal = Meal::find()->where(['id'=>$postdata['meal_id'],'favorite'=>1])->one();
                        $fav_meals = array();
                        if($fav_meal){
                            if ($fav_meal->favorite_meal) {
                                $fav_meals = json_decode($fav_meal->favorite_meal);
                            }
                            if (isset($postdata['food_id']) && isset($postdata['quantity'])) {
                                $flag = 0;
                                foreach ($fav_meals as $meal) {
                                    if ($meal->food_id == $postdata['food_id'] && $meal->quantity == $postdata['quantity']) {
                                        $flag = 1;
                                        break;
                                    }
                                }
                                if ($flag) {
                                    $data->favorite_meal = 1;
                                }
                            }
                        }
                    }
                }

                $today_date = strtotime($user->current_date ? explode(',', $user->current_date)[0] : date('m/d/y'));

                $data->date = Utils::weekDates($today_date);

                return array('status' => 200, 'message' => 'Calories counted', 'data' => $data);

            }
            
        } else {
            return array('status' => 400, 'message' => 'Uid or Food Id not found', 'data' => $data);
        }
    }
    public function actionChange_password()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            $user = User::findOne(['id' => $postdata['uid']]);
            if ($user) {
                if (isset($postdata['old_password']) && !empty($postdata['old_password']) && isset($postdata['new_password']) && !empty($postdata['new_password'])) {

                    if (Yii::$app->getSecurity()->validatePassword($postdata['old_password'], $user->password_hash)) {

                        // all good, logging user in
                        $user->password_hash = Yii::$app->security->generatePasswordHash($postdata['new_password']);
                        $user->save(false);
                        return array('status' => 200, 'message' => 'Password Updated', 'data' => $data);

                    } else {
                        // wrong password
                        return array('status' => 400, 'message' => 'Incorrect Password', 'data' => $data);

                    }
                } else {
                    return array('status' => 400, 'message' => 'Old or New Password not found', 'data' => $data);
                }


            } else {
                return array('status' => 400, 'message' => 'User not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid not found', 'data' => $data);
        }
    }
    //-------------------------------------------------------------------------------
    public function actionRecipe_add()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $model = new Recipes();
        $model->attributes = $postdata;

        if (!empty($model) && $model->validate()) {

            if (!$model->calories) {
                $model->calories = ($model->carbs * 4) + ($model->fat * 9) + ($model->protein * 4);
            }

            $model->created_at = time();
            $model->updated_at = time();
            $model->save(false);
            $innerdata = new \stdClass();
            $restrict_array = array(
                'verification_token',
                'created_at',
                'updated_at',
                'auth_key',
                'password_hash',
                'password_reset_token'
            );
            foreach ($model as $key => $value) {
                if (in_array($key, $restrict_array)) {
                    continue;
                }
                if ($value === null) {
                    $value = '';
                }
                $innerdata->$key = (string) $value;
            }
            if (!empty($model->image)) {
                $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/recipes/' . $model->image;
            } else {
                $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/recipes/' . "default-food.png";
            }
            $innerdata->image = $img;
            return array('status' => 200, 'message' => 'Recipe added successfully', 'data' => $innerdata);
        } else {
            $errors = $model->getErrors();
            $error = '';
            foreach ($errors as $val) {
                $error = isset($val[0]) ? $val[0] : '';
                break;
            }
            $data = new \stdClass();

            return array('status' => 400, 'message' => $error, 'data' => $data);
        }
    }
    public function actionRecipeslist()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();
        $data->list = array();
        $data->featured = array();
        $recipes = Recipes::find()->all();
        $perPage = $page = 1;
        $pages_array = [];
        if (isset($postdata['page']) && !empty($postdata['page']) && isset($postdata['perpage']) && !empty($postdata['perpage'])) {
            $pattern = "/^[0-9]*$/i";
            $page = $postdata['page'];

            if (preg_match($pattern, $postdata['perpage'])) {
                $perPage = $postdata['perpage'];
            } else {
                $perPage = 10;
            }
            $total_pages = ceil(count($recipes) / $perPage);
            if ($total_pages == 0) {
                ++$total_pages;
            }
            if ($page > $total_pages) {
                $page = $total_pages;
            }
            for ($i = 1; $i <= $total_pages; $i++) {
                array_push($pages_array, $i);
            }
            $offset = ($page - 1) * $perPage;
            $recipes = Recipes::find()
                ->offset($offset)
                ->limit($perPage)
                ->all();

        }
        $data->pages_array = $pages_array;
        $data->perpage = $perPage;
        $data->page = $page;
        if (isset($postdata['search']) && !empty($postdata['search'])) {
            $recipes = Recipes::find()
                ->filterWhere(['like', 'name', $postdata['search']])
                ->all();
        }
        $restrict_array = array(
            'created_at',
            'updated_at',
            'veggie'
        );
        foreach ($recipes as $recipe) {
            $innerdata = new \stdClass();
            foreach ($recipe as $key => $value) {
                if (in_array($key, $restrict_array)) {
                    continue;
                }
                if ($value == null) {
                    $value = '';
                }
                $innerdata->$key = (string) $value;
            }
            if (!empty($recipe->image)) {
                $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/recipes/' . $recipe->image;
            } else {
                $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/recipes/' . "default-food.png";
            }
            $innerdata->image = $img;

            array_push($data->list, $innerdata);
        }

        $recipes = Recipes::find()
            ->where(['<', 'id', 5])
            ->all();
        foreach ($recipes as $recipe) {
            $innerdata = new \stdClass();
            foreach ($recipe as $key => $value) {
                if (in_array($key, $restrict_array)) {
                    continue;
                }
                if ($value == null) {
                    $value = '';
                }
                $innerdata->$key = (string) $value;
            }
            if (!empty($recipe->image)) {
                $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/recipes/' . $recipe->image;
            } else {
                $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/recipes/' . "default-food.png";
            }
            $innerdata->image = $img;
            array_push($data->featured, $innerdata);
        }
        return array('status' => 200, 'message' => 'Recipes List', 'data' => $data);
    }
    public function actionRecipesinfo()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();
        $restrict_array = array('created_at', 'updated_at');
        if (isset($postdata['rid']) && !empty($postdata['rid'])) {
            $recipe = Recipes::find()->where(['id' => $postdata['rid']])->one();
            if ($recipe) {
                $innerdata = new \stdClass();
                foreach ($recipe as $key => $value) {
                    if (in_array($key, $restrict_array)) {
                        continue;
                    }
                    if ($value === null) {
                        $value = '';
                    }
                    $innerdata->$key = (string) $value;
                }
                if (!empty($recipe->image)) {
                    $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/recipes/' . $recipe->image;
                } else {
                    $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/recipes/' . "default-food.png";
                }

                $innerdata->is_multiple = FALSE;
                if (count(explode(',', $innerdata->carbs)) > 1) {
                    $innerdata->is_multiple = TRUE;
                    $nutrition = array();

                    $innerdata->carbs = explode(',', $innerdata->carbs);
                    foreach ($innerdata->carbs as $key => $value) {
                        $variation = new \stdClass();
                        $variation->data = $this->bucketarraysingle(((integer) $value), 20);
                        $variation->name = 'Variation ' . ($key + 1);
                        array_push($nutrition, $variation);
                    }
                    $innerdata->carbs = $nutrition;
                    $nutrition = array();
                    $innerdata->fat = explode(',', $innerdata->fat);
                    foreach ($innerdata->fat as $key => $value) {
                        $variation = new \stdClass();
                        $variation->data = $this->bucketarraysingle(((integer) $value), 10);
                        $variation->name = 'Variation ' . ($key + 1);
                        array_push($nutrition, $variation);
                    }
                    $innerdata->fat = $nutrition;
                    $nutrition = array();
                    $innerdata->protein = explode(',', $innerdata->protein);
                    foreach ($innerdata->protein as $key => $value) {
                        $variation = new \stdClass();
                        $variation->data = $this->bucketarraysingle(((integer) $value), 20, true);
                        $variation->name = 'Variation ' . ($key + 1);
                        array_push($nutrition, $variation);
                    }
                    $innerdata->protein = $nutrition;

                } else {
                    $innerdata->carbs = (integer) $innerdata->carbs;
                    $innerdata->fat = (integer) $innerdata->fat;
                    $innerdata->protein = (integer) $innerdata->protein;

                    $innerdata->carbs = $this->bucketarraysingle(($innerdata->carbs), 20);
                    $innerdata->fat = $this->bucketarraysingle(($innerdata->fat), 10);
                    $innerdata->protein = $this->bucketarraysingle(($innerdata->protein), 20, true);
                    $innerdata->veggie = $this->bucketarraysingle($innerdata->veggie, 1);

                }

                $innerdata->image = $img;
                $innerdata->favorite = 0;
                $item = FavoriteRecipe::find()->where(['uid' => $postdata['uid'], 'recipe_id' => $postdata['rid']])->one();
                if ($item) {
                    $innerdata->favorite = 1;
                }
                $innerdata->progress_bar = 20;
                return array('status' => 200, 'message' => 'Recipe Details', 'data' => $innerdata);

            } else {
                return array('status' => 400, 'message' => 'Recipe not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Rid not found', 'data' => $data);
        }
    }
    public function actionFavoriterecipeadd()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $model = new FavoriteRecipe();
        $model->attributes = $postdata;
        $data = new \stdClass();

        if (!empty($model) && $model->validate()) {
            if (FavoriteRecipe::findOne(['uid' => $model->uid, 'recipe_id' => $model->recipe_id])) {
                return array('status' => 400, 'message' => 'Food added already! ', 'data' => $data);
            }
            $food = Recipes::findOne(['id' => $model->recipe_id]);
            if (!$food) {
                return array('status' => 400, 'message' => 'Recipe not found! ', 'data' => $data);
            }
            $model->created_at = time();
            $model->updated_at = time();
            $model->save(false);
            $innerdata = new \stdClass();
            $restrict_array = array(
                'verification_token',
                'created_at',
                'updated_at',
                'auth_key',
                'password_hash',
                'password_reset_token'
            );
            return array('status' => 200, 'message' => 'Recipe added', 'data' => $innerdata);
        } else {
            $errors = $model->getErrors();
            $error = '';
            foreach ($errors as $val) {
                $error = isset($val[0]) ? $val[0] : '';
                break;
            }
            return array('status' => 400, 'message' => $error, 'data' => $data);
        }
    }
    public function actionFavoritereciperemove()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['recipe_id']) && !empty($postdata['recipe_id'])) {
            $item = FavoriteRecipe::find()->where(['uid' => $postdata['uid'], 'recipe_id' => $postdata['recipe_id']])->one();
            if (!empty($item)) {
                $item->delete();
                return array('status' => 200, 'message' => 'Item removed', 'data' => $data);
            } else {
                return array('status' => 400, 'message' => 'Entry doesn\'t exists', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid or Recipe id not found', 'data' => $data);
        }
    }

    public function actionApprovedfoodlist()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $postdata = new \stdClass();
        $data_protein = ApprovedFood::find()->where(['nutrients' => 'Protein'])->all();
        foreach ($data_protein as $data) {
            if (!empty($data->image)) {
                $data->image = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/recipes/' . $data->image;
            } else {
                $data->image = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/recipes/' . "default-food.png";
            }
        }
        $data_carbs = ApprovedFood::find()->where(['nutrients' => 'Carbohydrates'])->all();
        $data_fat = ApprovedFood::find()->where(['nutrients' => 'Fats'])->all();
        foreach ($data_carbs as $data) {
            if (!empty($data->image)) {
                $data->image = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/recipes/' . $data->image;
            } else {
                $data->image = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/recipes/' . "default-food.png";
            }
        }
        foreach ($data_fat as $data) {
            if (!empty($data->image)) {
                $data->image = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/recipes/' . $data->image;
            } else {
                $data->image = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/recipes/' . "default-food.png";
            }
        }

        $postdata->protein = $data_protein;
        $postdata->fat = $data_fat;
        $postdata->carbs = $data_carbs;
        return array('status' => 200, 'message' => 'Protein List', 'data' => $postdata);
    }
    public function actionDailydairy()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();
        $meal_array = array();
        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['date']) && !empty($postdata['date'])) {
            $meals = Meal::find()->where(['uid' => $postdata['uid'], 'date' => $postdata['date'], 'status' => 1])->all();
            $given_date = explode(',', $postdata['date'])[0];

            $wdata = WeeklyData::findOne(['uid' => $postdata['uid'], 'date' => $given_date]);
            if (!$wdata) {
                $wdata = new WeeklyData();
                $wdata->uid = $postdata['uid'];
                $wdata->date = $given_date;
                $wdata->created_at = time();
                $wdata->updated_at = time();
            }

            $calories_total = 0;
            $carbs_buckets = $fat_buckets = $protein_buckets = 0;
            $weekdata_calories = $weekdata_carbs = $weekdata_fat = $weekdata_protein = 0;

            foreach ($meals as $meal) {
                $carbs_total = $fat_total = $protein_total = 0;
                if (!$meal->food_id) {
                    $meal->delete();
                    continue;
                }
                $food_array = explode(',', $meal->food_id);
                $quantity_array = explode(',', $meal->quantity);
                $calories = $calories = $carbs = $fat = $protein = 0;
                foreach ($food_array as $key => $food) {
                    $food = FoodItems::findOne(['id' => $food]);
                    if ($food) {
                        $quantity = $quantity_array[$key] / $food->quantity;

                        $weekdata_calories += $food->calories * $quantity;
                        $calories += $food->calories * $quantity;

                        $weekdata_carbs += $food->carbs * $quantity;
                        $carbs += $food->carbs * $quantity;

                        $weekdata_fat += $food->fat * $quantity;
                        $fat += $food->fat * $quantity;

                        $weekdata_protein += $food->protein * $quantity;
                        $protein += $food->protein * $quantity;

                        $nutritions = Utils::bucketsInNumber(($food->carbs * $quantity), ($food->fat * $quantity), ($food->protein * $quantity));

                        $carbs_total += $nutritions['carbs'];
                        $fat_total += $nutritions['fat'];
                        $protein_total += $nutritions['protein'];
                    }
                }

                $calories_total += $calories;
                $innerdata = new \stdClass();
                $innerdata->id = $meal->id;
                $innerdata->meal_name = $meal->meal_name;

                //----------- this is for bucket count---------
                $innerdata->carbs_value = $carbs;
                $innerdata->fat_value = $fat;
                $innerdata->protein_value = $protein;

                $innerdata->carbs = $carbs_total;
                $innerdata->fat = $fat_total;
                $innerdata->protein = $protein_total;

                $carbs_buckets += $carbs_total;
                $fat_buckets += $fat_total;
                $protein_buckets += $protein_total;
                // ----------------------------

                $innerdata->calories = round($calories);

                $innerdata->food_id = $meal->food_id;
                $innerdata->quantity = $meal->quantity;
                array_push($meal_array, $innerdata);
            }

            $wdata->carbs = round($weekdata_carbs);
            $wdata->fat = round($weekdata_fat);
            $wdata->protein = round($weekdata_protein);
            $wdata->calories = round($weekdata_calories);

            $wdata->save(false);

            $user = User::findOne(['id' => $postdata['uid']]);

            $user->current_date = isset($postdata['current_date']) ? $postdata['current_date'] : $user->current_date;

            $user->save(false);

            $carbs = $this->bucketarray_withgrey(($carbs_buckets * 20), 20, round(($user->carbo_macro / 4) / 20), false, true);
            $fat = $this->bucketarray_withgrey(($fat_buckets * 10), 10, round(($user->fat_macro / 9) / 10));
            $protein = $this->bucketarray_withgrey(($protein_buckets * 20), 20, round(($user->protein_macro / 4) / 20), false, true);

            $calories = new \stdClass();
            $calories->goal = $user->calories_macro;
            $calories->taken = round($calories_total);
            $calories->remaining = round($user->calories_macro - $calories_total);

            $innerdata = new \stdClass();
            $innerdata->wdata = $wdata;
            $innerdata->calories = $calories;
            $innerdata->meal_array = $meal_array;

            $progress = new \stdClass();

            $progress->filled = $progress->remaining = 0;
            $progress->filled += $carbs['filled'];
            $progress->filled += $fat['filled'];
            $progress->filled += $protein['filled'];

            $progress->remaining += round(($user->carbo_macro / 4) / 20) - $carbs['filled'];
            $progress->remaining += round(($user->fat_macro / 9) / 10) - $fat['filled'];
            $progress->remaining += round(($user->protein_macro / 4) / 20) - $protein['filled'];

            $progress->remaining_progress_value = round(($progress->remaining / ($progress->filled + $progress->remaining)) * 100);
            $progress->filled_progress_value = round(($progress->filled / ($progress->filled + $progress->remaining)) * 100);

            $innerdata->progress = $progress;

            $today_date = strtotime($user->current_date ? explode(',', $user->current_date)[0] : date('m/d/y'));

            $innerdata->date = Utils::weekDates($today_date);

            return array('status' => 200, 'message' => 'Daily Dairy', 'data' => $innerdata);
        } else {
            return array('status' => 400, 'message' => 'Uid or Date not found', 'data' => $data);
        }
    }
    public function actionNutrition_query()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $error = array();

        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['query']) && !empty($postdata['query'])) {
            // $url = 'https://trackapi.nutritionix.com/v2/natural/nutrients';
            $url = 'https://trackapi.nutritionix.com/v2/custom_foods';
            $headers = array(
                'x-app-id:' . $this->nutrition_app_id,
                'x-app-key:' . $this->nutrition_app_key,
                // 'x-user-jwt:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTQ5MDYzMSwiaWF0IjoxNjQ5MTkwMzU2LCJleHAiOjE2NTE4Njg3NTZ9.CdMFPlY-XE1wmr7h0LtbahF-OXIlNFfPIxM2BeQLBJE',
                'accept: application/json',
                'content-type: application/json'
            );
            // $data = json_encode(array(
            //     "query"  => $postdata['query'],
            //     ));
            $data = json_encode(
                array(
                    "food_name" => 'abcd',
                    "nf_calories" => '5464',
                    "nutritionix_user_id" => 'poJk95Nr0oWZwqN',
                    "nutritionix_user_jwt" => 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTQ5MDYzMSwiaWF0IjoxNjQ5MTkwMzU2LCJleHAiOjE2NTE4Njg3NTZ9.CdMFPlY-XE1wmr7h0LtbahF-OXIlNFfPIxM2BeQLBJE',
                )
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            $response = curl_exec($ch);
            if (curl_errno($ch)) {
                echo 'Error:' . curl_error($ch);
            }
            curl_close($ch);
            $response = json_decode($response);
            $data = array();
            if (isset($response->foods)) {
                foreach ($response->foods as $foods) {
                    $innerdata = new \stdClass();
                    $innerdata->food_name = $foods->food_name;
                    $innerdata->brand_name = $foods->brand_name;
                    $innerdata->serving_qty = 'grams'; //$foods->serving_qty;
                    $innerdata->serving_weight_grams = $foods->serving_weight_grams;
                    $innerdata->calories = $foods->nf_calories;
                    $innerdata->fat = $foods->nf_total_fat;
                    $innerdata->carbs = $foods->nf_total_carbohydrate;
                    $innerdata->protein = $foods->nf_protein;
                    array_push($data, $innerdata);
                }
            }
            array_push($data, $response);
            // $data = array(
            //     'calories' => $response->foods[0]->nf_calories,
            //     'fat' => $response->foods[0]->nf_total_fat,
            //     'carbs' => $response->foods[0]->nf_total_carbohydrate,
            //     'protein' => $response->foods[0]->nf_protein,
            //     'foods'=>$response
            // );
            return array('status' => 200, 'message' => 'boom', 'data' => $data);

        } else {
            return array('status' => 400, 'message' => 'Uid or query not found', 'data' => $error);
        }
    }
    public function actionNutrition_barcode()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $error = array();

        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            if (isset($postdata['upc']) && !empty($postdata['upc'])) {
                $url = 'https://trackapi.nutritionix.com/v2/search/item?upc=' . $postdata['upc']; //038000000102
            } else if (isset($postdata['nix_item_id']) && !empty($postdata['nix_item_id'])) {
                $url = 'https://trackapi.nutritionix.com/v2/search/item?nix_item_id=' . $postdata['nix_item_id'];
            } else {
                return array('status' => 400, 'message' => 'upc or nix_item_id not found', 'data' => $error);
            }
            $headers = array(
                'x-app-id:' . $this->nutrition_app_id,
                'x-app-key:' . $this->nutrition_app_key,
                'accept: application/json',
                'content-type: application/json'
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $response = curl_exec($ch);
            if (curl_errno($ch)) {
                echo 'Error:' . curl_error($ch);
            }
            curl_close($ch);
            $response = json_decode($response);
            $data = array();
            if (isset($response->foods)) {
                foreach ($response->foods as $foods) {
                    $innerdata = new \stdClass();
                    $innerdata->food_name = $foods->food_name;
                    $innerdata->brand_name = $foods->brand_name;
                    $innerdata->serving_qty = 'grams'; //$foods->serving_qty;
                    $innerdata->serving_weight_grams = $foods->serving_weight_grams;
                    $innerdata->calories = $foods->nf_calories;
                    $innerdata->fat = $foods->nf_total_fat;
                    $innerdata->carbs = $foods->nf_total_carbohydrate;
                    $innerdata->protein = $foods->nf_protein;
                    array_push($data, $innerdata);
                }
            }
            array_push($data, $response);
            return array('status' => 200, 'message' => 'boom', 'data' => $data);

        } else {
            return array('status' => 400, 'message' => 'Uid not found', 'data' => $error);
        }
    }
    public function actionNotifications()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $error = array();
        $notification = $this->send_notification(['title' => 'testing', 'push_msg' => 'test_message']);
        return array('status' => 200, 'message' => 'boom', 'data' => $notification);
    }
    //--------------------------------------dev---------------------------------------
    public function actionPrevMeals()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid'])) {
            $meals = Meal::find()->where(['uid' => $postdata['uid'], 'status' => 1])->orderBy(['created_at' => SORT_DESC])->all();
            $perPage = $page = 1;
            $pages_array = [];
            if (isset($postdata['page']) && !empty($postdata['page']) && isset($postdata['perpage']) && !empty($postdata['perpage'])) {
                $pattern = "/^[0-9]*$/i";
                $page = $postdata['page'];

                if (preg_match($pattern, $postdata['perpage'])) {
                    $perPage = $postdata['perpage'];
                } else {
                    $perPage = 10;
                }
                $total_pages = ceil(count($meals) / $perPage);
                if ($total_pages == 0) {
                    ++$total_pages;
                }
                if ($page > $total_pages) {
                    $page = $total_pages;
                }
                for ($i = 1; $i <= $total_pages; $i++) {
                    array_push($pages_array, $i);
                }
                $offset = ($page - 1) * $perPage;
                $meals = Meal::find()->where(['uid' => $postdata['uid'], 'status' => 1])
                    ->offset($offset)
                    ->limit($perPage)
                    ->all();

            }
            $data->pages_array = $pages_array;
            $data->perpage = $perPage;
            $data->page = $page;

            if ($meals) {
                $listing = array();
                $restrict_array = array('created_at', 'updated_at', 'favorite_meal', 'favorite');
                foreach ($meals as $meal) {
                    $innerdata = new \stdClass();
                    $foods = explode(',', $meal->food_id);

                    foreach ($meal as $key => $value) {
                        if (in_array($key, $restrict_array)) {
                            continue;
                        }
                        if ($value == null) {
                            $value = '';
                        }
                        $innerdata->$key = (string) $value;
                    }
                    $innerdata->food_id = $foods;
                    $innerdata->quantity = explode(',', $innerdata->quantity);
                    $innerdata->calories = 0;
                    $innerdata->image = '';
                    foreach ($foods as $value) {
                        $food = FoodItems::findOne(['id' => $value]);
                        if (!$food) {
                            continue;
                        }

                        $innerdata->calories += $food->calories;
                        if (!$innerdata->image) {
                            $innerdata->image = $food->image;
                        }
                    }
                    if (!empty($innerdata->image)) {
                        if (substr($innerdata->image, 0, 4) == 'http') {
                            $img = $innerdata->image;
                        } else {
                            $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/' . $innerdata->image;
                        }
                    } else {
                        $img = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . Yii::$app->request->baseUrl . '/uploads/food_images/default-food.png';
                    }
                    $innerdata->image = $img;
                    // $innerdata->food = $food_data;
                    array_push($listing, $innerdata);
                }
                $data->result = $listing;
                return array('status' => 200, 'message' => ' Meals found', 'data' => $data);
            } else {
                return array('status' => 400, 'message' => 'Meal not found', 'data' => $data);
            }
        } else {
            return array('status' => 400, 'message' => 'Uid not found', 'data' => $data);
        }
    }
    public function actionWeeklyProgressPhotos()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['date']) && !empty($postdata['date'])) {

            $weekNumber = Utils::getWeekNumberByDate($postdata['date']);

            if (!$weekNumber) {
                return array('status' => 400, 'message' => 'Invalid Date', 'data' => $data);
            }

            $weekly_photos = WeeklyPhotos::find()->where(['uid' => $postdata['uid'], 'week_number' => $weekNumber])->one();

            if (!$weekly_photos) {
                $weekly_photos = new WeeklyPhotos();
                $weekly_photos->uid = $postdata['uid'];
                $weekly_photos->week_number = $weekNumber;
                $weekly_photos->created_at = time();
                $weekly_photos->updated_at = time();
            }
            if (isset($postdata['front']) && !empty($postdata['front'])) {
                $weekly_photos->front = $postdata['front'];
            }
            if (isset($postdata['side']) && !empty($postdata['side'])) {
                $weekly_photos->side = $postdata['side'];
            }
            if (isset($postdata['back']) && !empty($postdata['back'])) {
                $weekly_photos->back = $postdata['back'];
            }

            $weekly_photos->updated_at = time();
            $weekly_photos->save(false);

            $restrict_array = array('created_at', 'updated_at', 'favorite_meal', 'week_number');
            $innerdata = new \stdClass();
            foreach ($weekly_photos as $key => $value) {
                if (in_array($key, $restrict_array)) {
                    continue;
                }
                if ($value == null) {
                    $value = '';
                }
                $innerdata->$key = (string) $value;
            }
            return array('status' => 200, 'message' => 'Image added', 'data' => $innerdata);

        } else {
            return array('status' => 400, 'message' => 'Uid or week number not found', 'data' => $data);
        }
    }
    public function actionSendChatOverMail()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();
        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $data = new \stdClass();

        if (isset($postdata['uid']) && !empty($postdata['uid']) && isset($postdata['emailBody']) && !empty($postdata['emailBody'])) {
            $user = User::find()->where(['id'=>$postdata['uid']])->one();
            if($user){
                Utils::sendMail('developingsofts@gmail.com', $user->name, $postdata['emailBody'],"Chat Received");
                return array('status' => 200, 'message' => ' Email sent.', 'data' => $data);
            }else{
                return array('status' => 400, 'message' => 'User not found', 'data' => $data);
            }           
        } else {
            return array('status' => 400, 'message' => 'Uid or emailBody not found', 'data' => $data);
        }
    }



    public function actionPostcreate()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();

        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        $model = new CommunityForums();
        $model->attributes = $postdata;
        $model->created_at = time();
        if($model->save(false)){
            return array('status' => 200, 'message' => "Success", 'data' => $model);
        } else {
            return array('status' => 400, 'message' => "Fail", 'data' => "no");

        }
    }

    public function actionPostupdate()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();

        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        if (isset($postdata['id']) && !empty($postdata['id'])) {
            $model = CommunityForums::find()->where(['id' => $postdata['id']])->one();
            if (!empty($model)) {
                $model->attributes = $postdata;
                $model->updated_at = time();
                if ($model->save(false)) {
                    return array('status' => 200, 'message' => "Success", 'data' => model);
                } else {
                    return array('status' => 400, 'message' => "Fail", 'data' => (object)[]);        
                }
            }else {
                return array('status' => 400, 'message' => "No record found", 'data' => (object)[]);        
            }
        }        
    }

    public function actionPostdelete()
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;
        $postdata = Yii::$app->request->post();

        if (empty($postdata)) {
            $postdata = file_get_contents("php://input");
            $postdata = json_decode($postdata, true);
        }
        if (isset($postdata['id']) && !empty($postdata['id'])) {
            $model = CommunityForums::find()->where(['id' => $postdata['id']])->one();
            if (!empty($model)) {
                if ($model->delete()) {
                    return array('status' => 200, 'message' => "Deleted Successfully", 'data' => (object)[]);
                } 
            }else {
                return array('status' => 400, 'message' => "No record found", 'data' => (object)[]);        
            }
        }        
    }



    //--------------------------------------------------------------------------------
    /*
    @value = nutritions in grams(except water and veggies)
    @type = {
    20 - carbs,protein
    10 - fat
    1 - water,veggies
    }
    @iteration = number of
    */
    public function bucketarray($value, $type, $iteration, $isProtein = false)
    {
        $iteration = ceil($iteration);

        $array = array();
        $filled = 0;
        if ($type == 20) {
            $upper_limit = 16;
        }
        if ($type == 10) {
            $upper_limit = 9;
        }
        if ($type == 1) {
            $upper_limit = 1;
        }
        for ($i = $iteration, $j = $value; $i > 0; $i--, $j -= $type) {
            if ($j <= 0) {
                array_push($array, 0);
                continue;
            }
            if ($j < $upper_limit) {
                if ($j == 1 || $j == 2) {
                    continue;
                }
                if ($j < 7) {
                    array_push($array, 25);
                    $filled += 0.25;
                    continue;
                }
                if ($j < 12) {
                    array_push($array, 50);
                    $filled += 0.5;
                    continue;
                }
                if ($j < 16) {
                    array_push($array, 75);
                    $filled += 0.75;
                    continue;
                }
            } else if ($j < $upper_limit) {
                if ($j < ($type == 20 ? 6 : 4)) {
                    array_push($array, 25);
                    $filled += 0.25;
                    continue;
                }
                if ($j < ($type == 20 ? 11 : 6)) {
                    array_push($array, 50);
                    $filled += 0.5;
                    continue;
                }
                if ($j < ($type == 20 ? 16 : 9)) {
                    array_push($array, 75);
                    $filled += 0.75;
                    continue;
                }
            }
            array_push($array, 100);
            $filled += 1;
        }
        return ['array' => $array, 'filled' => $filled];
    }
    /*
    @value - nutritions in grams
    @type - {
    20 - carbs , protein
    10 - fat
    }
    */
    public function bucketarraysingle($value, $type, $isProtein = false)
    {
        $array = array();
        for ($i = $value; $i > 0; $i -= $type) {
            if ($isProtein && $i < 16) {
                // $a = round($i * 100);
                if ($i == 1 || $i == 2) {

                    continue;
                }
                if ($i < 7) {
                    array_push($array, 25);
                    continue;
                }
                if ($i < 12) {
                    array_push($array, 50);
                    continue;
                }
                if ($i < 16) {
                    array_push($array, 75);
                    continue;
                }
            } else if ($i > 0 && $i < ($type == 20 ? 16 : 9)) {
                if ($i > 0 && $i < ($type == 20 ? 6 : 4)) {
                    array_push($array, 25);
                    continue;
                }
                if ($i < ($type == 20 ? 11 : 6)) {
                    array_push($array, 50);
                    continue;
                }
                if ($i < ($type == 20 ? 16 : 9)) {
                    array_push($array, 75);
                    continue;
                }
            }
            array_push($array, 100);
        }
        return $array;
    }
    public function getdate($week, $year)
    {
        $ret = new \stdClass();
        $date = new \DateTime();
        $date->setISODate($year, $week);
        $ret->week_start = $date->format('m/d/Y');
        $ret->week = "Week of " . $date->format('m/d');
        $date->modify('+6 days');
        $ret->week_end = $date->format('m/d/Y');
        $ret->week .= " - " . $date->format('m/d');
        return $ret;
    }
    public function chart_array($array)
    {
        $count = count($array);
        if ($count < 7) {
            for ($i = 0; $i < 7 - $count; $i++) {
                array_push($array, 0);
            }
        }
        return $array;
    }
    //--------------------------------------------------

    function send_notification($data)
    {
        // $data=$request->all();
        $title = $data['title'];
        $msg = $data['push_msg'];
        $api_key = $this->server_id;
        $ch = curl_init("https://fcm.googleapis.com/fcm/send");

        //Body of the Notification.

        //Creating the notification array.
        $notification = array('title' => $title, 'body' => $msg);
        //This array contains, the token and the notification. The 'to' attribute stores the token.
        // $arrayToSend = array('to' => '/topics/grown', 'notification' => $notification,'priority'=>'high');
        $arrayToSend = array('to' => $this->token, 'notification' => $notification, 'priority' => 'high');
        //Generating JSON encoded string form the above array.
        $json = json_encode($arrayToSend);
        //Setup headers:
        $headers = array();
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Authorization:key=' . $api_key; // key here

        //Setup curl, add headers and post parameters.
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        //Send the request
        $result = curl_exec($ch);
        //Close request
        curl_close($ch);
        return $result;
        // return redirect()->back()->with('message', 'IT WORKS!'); 
    }

    public function bucketarray_withgrey($value, $type = 20, $iteration, $color = false, $isProtein = false)
    {
        $iteration = ceil($iteration);
        $upper_limit = 0;
        $array = array();
        $filled = 0;

        if ($type == 20) {
            $upper_limit = 16;
        }
        if ($type == 10) {
            $upper_limit = 9;
        }
        if ($type == 1) {
            $upper_limit = 1;
        }

        $limit = ($iteration * $type);
        $count = 0;
        for ($i = 0; $i < $limit; $i += $type) {

            if (($value - $i) > $upper_limit) {
                array_push($array, ['value' => 100, 'is_maximize' => $color]);
                $filled += $color ? 0 : 1;
                // if ($color === true) {
                //     break;
                // }
                if (($value > ($iteration * $type)) && (count($array) == $iteration)) {
                    $limit = $value;
                    $color = true;
                }
                continue;
            }
            if ($i > $value || $value == 0 || $value == $i) { //($count !=1 && $i == 0)){
                array_push($array, ['value' => 0, 'is_maximize' => $color]);
                continue;
            }
            if (($value - $i) == $upper_limit) { //($count !=1 && $i == 0)){
                array_push($array, ['value' => 100, 'is_maximize' => $color]);
                $filled += $color ? 0 : 1;
                continue;
            }

            if ($isProtein && (($value - $i) < $upper_limit) && (($value - $i) > 0)) {
                // echo $value - $i." - true";
                if (($value - $i) < 7 && ($value - $i) > 2) {
                    array_push($array, ['value' => 25, 'is_maximize' => $color]);
                    $filled += $color ? 0 : 0.25;
                    continue;
                }
                if (($value - $i) < 12) {
                    array_push($array, ['value' => 50, 'is_maximize' => $color]);
                    $filled += $color ? 0 : 0.5;
                    continue;
                }
                if (($value - $i) < 16) {
                    array_push($array, ['value' => 75, 'is_maximize' => $color]);
                    $filled += $color ? 0 : 0.75;
                    continue;
                }
            } else if ((($value - $i) < $upper_limit) && (($value - $i) > 0)) {
                if (($value - $i) < ($type == 20 ? 6 : 4)) {
                    array_push($array, ['value' => 25, 'is_maximize' => $color]);
                    $filled += $color ? 0 : 0.25;
                    continue;
                }
                if (($value - $i) < ($type == 20 ? 11 : 6)) {
                    array_push($array, ['value' => 50, 'is_maximize' => $color]);
                    $filled += $color ? 0 : 0.5;
                    continue;
                }
                if (($value - $i) <= ($type == 20 ? 16 : 9)) {
                    array_push($array, ['value' => 75, 'is_maximize' => $color]);
                    $filled += $color ? 0 : 0.75;
                    continue;
                }
            }

        }
        return ['array' => $array, 'filled' => $filled];
    }
    public function numberToBuckets($number)
    {
        $array = array();
        for ($i = $number; $i > 0; $i--) {
            if ($i < 1) {
                // $a = round($i * 100);
                if ($i == 0.25) {
                    array_push($array, 25);
                    continue;
                }
                if ($i == 0.50) {
                    array_push($array, 50);
                    continue;
                }
                if ($i == 0.75) {
                    array_push($array, 75);
                    continue;
                }
            }
            array_push($array, 100);
        }
        return $array;
    }

}