?
Current File : /home2/slickdealsnews/public_html/application/models/User_preference.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class User_preference extends CI_Model
{
    private $table = 'tbl_user_pref';
    private $table1 = 'tbl_users';
    private $tableAddress = 'tbl_user_address';
    private $tbl_order           = 'tbl_order';
    private $tbl_order_detail    = 'tbl_order_detail';

    function __construct()
    {
        parent::__construct();
        $this->load->model('Webservices_model/Cart_model');
        $this->load->library('email_lib');
        //echo "edjlj";die;
    }

    public function get_ProductListByVariant($weight_id)
    {

        $this->db->select("*");
        $this->db->where("id", $weight_id);
        $query = $this->db->get("tbl_product_price");
        // echo $this->db->last_query();die;
        if ($query->num_rows()) {
            $rs_data['status']          =   "success";
            $rs_data['result']          =   $query->row();
            $this->db->select('image');
            $this->db->where('variant_id', $weight_id);
            $result = $this->db->get('tbl_product_gallery');
            if ($result->num_rows() > 0) {
                $rs_data['result']->variant_img =   $result->row()->image;
            }
        } else {
            $rs_data['status'] = "error";
            $rs_data['result'] = '';
        }
        return $rs_data;
    }
    public function get_contact_us_address()
    {
        $this->db->select('description');
        $this->db->where('id', '2');
        $result = $this->db->get('tbl_cms')->row();
        if ($result) {
            return $result->description;
        } else {
            return false;
        }
    }

    public function check_wallet_pin($wallet_pin, $user_id)
    {

        if (!empty($wallet_pin && $user_id)) {
            $this->db->select('*');
            $this->db->where('id', $user_id);
            $this->db->where('wallet_pin', $wallet_pin);
            $result = $this->db->get('tbl_users');
            if ($result->num_rows() > 0) {
                $data['status'] = 'success';
            } else {
                $data['status'] = 'error';
            }
        } else {
            $data['status'] = 'error';
        }
        return $data;
    }

    public function get_weight_data($weight_ids_array, $store_id = "")
    {
        $this->db->select('*');
        $this->db->where_in('id', $weight_ids_array);
        $this->db->where('unit_status', '1');
        $this->db->order_by('id', 'desc');
        $result = $this->db->get('tbl_product_price')->result();
        // pr($result);
        // pr($weight_ids_array);
        // die;
        ##########for store wise price on product detail page api starts####################
        if ($store_id != "") {

            $result = get_weight_data_store_wise_api($result, $weight_ids_array, $store_id);
        }
        ##########for store wise price on product detail page api ends####################
        if ($result) {
            return $result;
        } else {
            return false;
        }
    }

    public function get_product_detail_by_id($product)
    {
        $this->db->select('product_id,product_code,product_s_ad_info,product_s_desc,product_ean_code,product_name,product_url,product_type,product_status,product_metatitle,product_metadescription,product_metakeyword,country_name,brand_name,product_image,weight_ids,product_prices,product_pec_weights,product_s_prices,date_added,date_modified,brand_type,mb_express,mb_express_category,product_nature,product_weight_type,tag,food_type,featured,substitute,selected_category');
        $this->db->where('product_id', $product);
        $product_data = $this->db->get('tbl_product')->result();


        foreach ($product_data as $pd_key => $pd_val) {

            $product_s_prices   =   $product_data[$pd_key]->product_s_price;

            $product_s_prices   =   explode(',', $product_s_prices);

            $product_prices     =   $product_data[$pd_key]->product_price;
            $product_prices     =   explode(',', $product_prices);
            /**Manage Discount */
            $store_id       =   get_store_id('id');
            $discount_data  =   getDiscountOnProduct_main($pd_val->product_id, $qty = 0, $pd_val->price, $store_id, $user_id);

            $product_data[$pd_key]->discount_data   =   $discount_data;

            $product_s_prices_str   =   '';
            $discounted_amount_str      =   '';
            foreach ($product_s_prices as $psp_key => $psp_val) {
                $discount_value = 0;
                $price_after_discount = 0;
                if ($psp_val == '0.00') {
                    /**Means this product does not have special price*/
                    if ($discount_data['discount_type'] == 'percentage') {
                        $discount_value         =   ($product_prices[$psp_key] * $discount_data['discount']) / 100;
                        $price_after_discount   =   $product_prices[$psp_key] - $discount_value;
                    } else if ($discount_data['discount_type'] == 'flat') {
                        $discount_value         =   $discount_data['discount'];
                        $price_after_discount   =   $product_prices[$psp_key] - $discount_value;
                    } else {
                        $price_after_discount = $product_prices[$psp_key];
                    }
                    $product_s_prices_str   .=  $price_after_discount . ',';
                    $discounted_amount_str      .=  $discount_value . ',';
                } else {
                    $product_s_prices_str .=    $product_s_prices[$psp_key] . ',';
                    $discounted_amount_str      .=  '0.00' . ',';
                }
            }
            $product_s_prices_str   =   rtrim($product_s_prices_str, ','); //echo $product_s_prices_str; die;
            $product_data[$pd_key]->product_prices_after_discount   =   $product_s_prices_str;

            $discounted_amount_str  =   rtrim($discounted_amount_str, ',');
            $product_data[$pd_key]->discounted_amount               =   $discounted_amount_str;

            $weight_ids     =   $product_data[$pd_key]->weight_id;
            $weight_ids     =   explode(',', $weight_ids);
            /* ---get offer in product----- */
            $offer_data = get_offer($product_data[$pd_key]->weight_id);
            $product_data[$pd_key]->offer_data  =   $offer_data;
            /* ---offer section end ---------- */
            /* ----get flag icon-------- */
            $flag = get_flag($product_data[$pd_key]->country_name);
            $product_data[$pd_key]->flag    =   $flag;


            if (isset($_COOKIE['cart_items_cookie'])) {
                $cookie_product = $_COOKIE['cart_items_cookie'];
                $cookie_product = json_decode($cookie_product, true);
                $added_cart_quantity    =   '';
                foreach ($weight_ids as $w_key => $w_val) {
                    if (array_key_exists($w_val, $cookie_product)) {
                        $added_cart_quantity .= $cookie_product[$w_val] . ",";
                    } else {
                        $added_cart_quantity .= $cookie_product[$w_val] . "0,";
                    }
                }
                $added_cart_quantity    =   rtrim($added_cart_quantity, ',');
                $product_data[$pd_key]->in_cart_quantity    =   $added_cart_quantity;
            } else {
                $product_data[$pd_key]->in_cart_quantity    =   '';
            }


            if ($store_id) {
                $is_in_stock_str    =   '';
                foreach ($weight_ids as $w_key => $w_val) {
                    $stock_data     =   checkStock($store_id, $w_val);
                    //pr($stock_data); die;
                    if (isset($stock_data) && $stock_data != '') {
                        if ($stock_data->qnty_type   == 'unlimited') {
                            $is_in_stock_str    .=  'yes,';
                        } else if ($stock_data->qnty_type == 'limited') {
                            if ($stock_data->qnty <= 0) {
                                $is_in_stock_str    .=  'no,';
                            } else {
                                $is_in_stock_str    .=  'yes,';
                            }
                        } else {
                            $is_in_stock_str    .=  'yes,';
                        }
                    } else {
                        $is_in_stock_str    .=  'no,';
                    }
                }
                $is_in_stock_str    =   rtrim($is_in_stock_str, ',');
                $product_data[$pd_key]->is_in_stock =   $is_in_stock_str;
            }
        }





        if ($product_data) {
            return $product_data;
        } else {
            return false;
        }
    }


    public function get_product_detail_by_id_api($product, $user_id = '')
    {

        $cart_items_from_db = $this->Cart_model->get_cart_items_new($user_id);
        $store_id = $_POST['store_id'];
        $this->db->select("pp.id as vid,pp.product_price as product_price1,pp.product_pec_weight as product_pec_weight1,pp.product_s_price as product_s_price1,pp.special_price_start_date,pp.special_price_end_date,pp.set_quantity,pg.image,p.product_metatitle,p.product_metakeyword,p.product_metadescription,p.product_id,p.product_image,p.product_code,p.product_s_desc,p.product_s_ad_info,p.product_name,p.product_url,p.product_type,p.product_status,p.category_ids,p.weight_ids as weight_id,p.product_prices as product_price,p.product_pec_weights as product_pec_weight,p.product_s_prices as product_s_price,p.food_type,p.product_weight_type,p.product_nature,p.country_name,p.mb_express", false);
        $this->db->join("tbl_product_price as pp", "pp.product_id=p.product_id");
        $this->db->join("tbl_product_gallery as pg", "pg.variant_id=pp.id", "left");
        $this->db->where('p.product_status', '1');
        $this->db->where('p.product_id', $product);
        $rs_data = $this->db->get('tbl_product as p')->result();
        $product_data = $rs_data[0];
        $product_id     = $product_data->product_id;
        $product_data->weight_id = implode(array_reverse(explode(',', $product_data->weight_id)), ',');
        $product_data->product_pec_weight = implode(array_reverse(explode(',', $product_data->product_pec_weight)), ',');
        $weight_ids     = explode(',', rtrim($product_data->weight_id, ','));
        $weight_ids_array = $weight_ids[0];
        #####checking if the product specific weight is active starts############
        //pr($product_data[0]);die;
        //foreach ($product_data as $pd_key => $pd_val) {
        // if($pd_val->product_id==11230){
        //     pr($pd_val);
        $product_pec_weight =  null;
        $weight_id          = null;
        $product_s_prices   = null;
        $product_prices     = null;
        $new_product_pec_weight =  null;
        $new_weight_id          = null;
        $new_product_s_prices   = null;
        $new_product_prices     = null;

        $product_id         = $product_data->product_id;
        $product_pec_weight = explode(',', rtrim($product_data->product_pec_weight, ','));
        $weight_id          = explode(',', rtrim($product_data->weight_id, ','));
        $product_s_prices   = explode(',', rtrim($product_data->product_s_price, ','));
        $product_prices     = explode(',', rtrim($product_data->product_price, ','));
        $new_pec_weight = 0;
        $new_product_pec_weight = null;
        //pr($product_data);
        if (count(@$weight_id) > 1) {
            foreach ($weight_id as $key_variable_weight_id => $value_variable_weight_id) {
                if (IsActiveProductWeight($weight_id[$key_variable_weight_id], $product_id)) {
                    $new_product_pec_weight[$new_pec_weight] = $product_pec_weight[$key_variable_weight_id];
                    $new_product_s_prices[$new_pec_weight] = $product_s_prices[$key_variable_weight_id];
                    $new_product_prices[$new_pec_weight] = $product_prices[$key_variable_weight_id];
                    $new_weight_id[$new_pec_weight] =  $weight_id[$key_variable_weight_id];
                    $new_pec_weight++;
                }
            }
            $new_pec_weight = 0;
            $product_pec_weight     = $new_product_pec_weight;
            $product_s_prices       = $new_product_s_prices;
            $product_prices         = $new_product_prices;
            $weight_id              = $new_weight_id;
            // $product_data[$pd_key] = getNewActiveProductDetail($weight_id[0],$product_id);
            // pr($product_data[$pd_key]);
            $product_data->vid = $weight_id[0];
            $product_data->product_pec_weight1 = $product_pec_weight[0];
            $product_data->product_s_price1   = $product_s_prices[0];
            $product_data->product_price1     = $product_prices[0];
            $product_data->product_pec_weight = (implode(',', $product_pec_weight));
            $product_data->weight_id          = (implode(',', $weight_id));
            $product_data->product_s_price    = (implode(',', $product_s_prices));
            $product_data->product_price      = (implode(',', $product_prices));
            $weight_ids                       = (explode(",", $product_data->weight_id));
            $weight_ids_array = $weight_ids[0];
        }
        $new_product_pec_weight = null;
        $weight = $this->get_weight_data($weight_ids_array, $store_id);
        $product_data->vid = $weight[0]->id;
        $product_data->product_price1 = $weight[0]->product_price;
        $product_data->product_pec_weight1 = $weight[0]->product_pec_weight;
        $product_data->product_s_price1 = $weight[0]->product_s_price;
        $product_data->set_quantity = $weight[0]->set_quantity;
        $product_data->special_price_start_date = $weight[0]->special_price_start_date;
        $product_data->special_price_end_date = $weight[0]->special_price_end_date;
        /*Check all offer here*/
        /*SP Price date diff*/
        $data['product_data'] = $product_data;
        if ((int) $product_data->product_s_price1 > 0 && $product_data->special_price_start_date != '' && $product_data->special_price_start_date != '0000-00-00' && $product_data->special_price_end_date != '' && $product_data->special_price_end_date != '0000-00-00') {
            $curdate    = new DateTime();
            $fromdate   = new DateTime($product_data->special_price_start_date);
            $todate     = new DateTime($product_data->special_price_end_date);
            if (($curdate->getTimestamp() > $fromdate->getTimestamp()) && ($curdate->getTimestamp() < $todate->getTimestamp())) {

                $is_redeemed_sp_price = chk_redeem_limit($product_data->vid, $user_id, $product_data->vid, 3, $product_data->set_quantity);
                if ($is_redeemed_sp_price) {
                    $specialprice_flag = true;
                }
            }
        }
        if (!empty($is_offer = get_offer($product_data->vid))) {
            $offer_type         = 'offer';
            $offer_data         = $is_offer;
            $free_item_product  = explode(",", $is_offer['free_item_product']);
            $this->db->select('p.product_name,p.product_image,pg.image,pp.product_pec_weight');
            $this->db->join('tbl_product_price as pp', 'pp.product_id = p.product_id');
            $this->db->join("tbl_product_gallery as pg", "pg.variant_id=pp.id", "left");
            $this->db->where_in("pp.id", $free_item_product);
            $this->db->group_by("p.product_id");
            $free_offer_data    = $this->db->get("tbl_product as p")->result_array();
            // pr($free_offer_data);die;
        } elseif ($specialprice_flag) {
            $offer_type         = 'special_price';
        } elseif ($discount_data1  = getDiscountOnProduct_main($product_data->vid, $product_data->product_price1, $store_id, $user_id)) {
            $offer_type         = 'discount';
            $offer_data         = $discount_data1;
        }

        // echo "pd_key=>".$pd_key; pr($offer_data); echo "<br>";
        $data['product_data']->offers_data                = isset($offer_data) ? $offer_data : '';
        $data['product_data']->offers_data['offers_type'] = isset($offer_type) ? $offer_type : '';
        if (isset($free_offer_data) && !empty($free_offer_data)) {
            $data['product_data']->offers_data['free_products']   = $free_offer_data;
            $data['product_data']->offers_data['offer_icon']      = base_url('assets/img/offer.png');
        }


        if ($store_id) {
            $is_in_stock_str        =   '';
            $in_cart_quantity_str   =   '';
            $stock_data     =   checkStock($store_id, $product_data->vid);
            if (isset($stock_data) && $stock_data != '') {
                if ($stock_data->qnty_type   == 'unlimited') {
                    $is_in_stock_str    .=  'yes,';
                } else if ($stock_data->qnty_type == 'limited') {
                    if ($stock_data->qnty <= 0) {
                        $is_in_stock_str    .=  'no,';
                    } else {
                        $is_in_stock_str    .=  'yes,';
                    }
                } else {
                    $is_in_stock_str    .=  'yes,';
                }
            } else {
                $is_in_stock_str    .=  'no,';
            }
            /*Getting product in cookies (check either this product in already cart via cookie)*/
            $weight_id  =   isset($w_val) ? $w_val : '';
            // pr($cart_items_from_db);die;
            $added_cart_quantity =  0;
            if (($user_id != '' || $user_id != 0) && (isset($cart_items_from_db) && !empty($cart_items_from_db))) {
                $cookie_product = $cart_items_from_db;
                $added_cart_quantity    =   '';
                if (array_key_exists($product_data->vid, $cookie_product)) {
                    $added_cart_quantity =  $cookie_product[$product_data->vid];
                }
            }
            /*End of Getting product in cookies*/
            $flag = get_flag($product_data->country_name);
            $data['product_data']->flag    =   $flag;
            $is_in_stock_str        =   rtrim($is_in_stock_str, ',');
            $data['product_data']->is_in_stock      =   $is_in_stock_str;
            // $in_cart_quantity_str   =   rtrim($in_cart_quantity_str,',');
            $data['product_data']->gallery_images = $this->fetch_gallery($product_data->vid);
            $data['product_data']->in_cart_quantity =   $added_cart_quantity;
            if (isset($price_for_print) && $price_for_print == '' || $price_for_print == 'null') {
                $data['product_data']->price_for_print =   $product_data->product_price1;
            } else {
                $data['product_data']->price_for_print =   $price_for_print;
            }
        }

        if ($data) {
            return $data;
        } else {
            return false;
        }
    }

    private function fetch_gallery($id = null)
    {

        $this->db->select('image,id');
        $this->db->where('variant_id', $id);
        $this->db->where("image!=''");
        $result = $this->db->get('tbl_product_gallery');
        //  echo $this->db->last_query(); die;
        if ($result->num_rows() > 0) {
            return $result->result();
        } else {
            return false;
        }
    }

    public function get_orders()
    {

        $uid = $this->session->userdata('auth_user')['users_id'];

        $this->db->select('*');
        $this->db->where('user_id', $uid);
        $this->db->where('order_status !=', '');
        $this->db->order_by('id', 'desc');
        $result = $this->db->get('tbl_order')->result();
        $new_date = '';
        $current_date = date('Y-m-d H:i:s');
        if ($result) {
            foreach ($result as $key_rd => $val_rd) {
                $new_date =  date('Y-m-d H:i:s', strtotime($val_rd->order_date . ' + 2 day'));
                if ($new_date >= $current_date) {
                    $result[$key_rd]->is_rescheduled_possible = 'yes';
                } else {
                    $result[$key_rd]->is_rescheduled_possible = 'no';
                }
            }
        }
        if (!empty($result)) {
            return $result;
        } else {
            return false;
        }
    }

    public function get_orders_pagination($user_id, $id = '', $limit = '', $start = '')
    {

        $this->db->select('SQL_CALC_FOUND_ROWS o.*,SUM(od.refund_amount) as refund_amount', FALSE);
        $this->db->where('o.order_status !=', '');
        if ($user_id != '') {
            $this->db->where('o.user_id', $user_id);
        }
        if ($id != '') {
            $this->db->where('o.id', $id);
        }
        if ($limit != '' && $start != '') {
            $this->db->limit($limit, $start);
        } else {
            $this->db->limit($limit);
        }
        $this->db->join('tbl_order_detail as od', 'od.order_id = o.id', 'left');
        $this->db->order_by('o.id', 'desc');
        $this->db->group_by('o.id');
        $query = $this->db->get('tbl_order as o');
        //echo $this->db->last_query();die;
        $num_rows = $query->num_rows();

        if ($num_rows > 0) {
            $result = $query->result();
            $rs_data['status']          = "success";
            $rs_data['search_records']  = $num_rows;
            $rs_data['total_records']    = $this->db->query('SELECT FOUND_ROWS() AS `count`')->row()->count;

            $new_date = '';
            $current_date = date('Y-m-d H:i:s');
            foreach ($result as $key_rd => $val_rd) {
                $new_date =  date('Y-m-d H:i:s', strtotime($val_rd->order_date . ' + 2 day'));
                if ($new_date >= $current_date) {
                    $result[$key_rd]->is_rescheduled_possible = 'yes';
                } else {
                    $result[$key_rd]->is_rescheduled_possible = 'no';
                }
            }
            $rs_data['result']  = $result;
        } else {
            $rs_data['status']     = "error";
            $rs_data['result']     = '';
            $rs_data['total_records']    = 0;
            $rs_data['search_records']  = 0;
        }

        if ($rs_data['total_records'] > 0) {
            return $rs_data;
        } else {
            return false;
        }
    }

    public function insert_rating_review($count, $message)
    {
        $order_id = $_POST['order_id'];

        $this->db->set('rating', $count);
        $this->db->set('reting_review', $message);
        $this->db->where('id', $order_id);
        $result = $this->db->update('tbl_order');
        if ($result) {
            return $result;
        } else {
            return false;
        }
    }

    public function insert_thread($user_id = '')
    {
        if ($user_id) {
            $uid = $user_id;
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }

        $data['order_id'] = $_POST['order_id'];
        $data['ticket_id'] = $_POST['ticket_id'];
        $data['description'] = $_POST['description'];
        $data['added_by'] = $uid;
        $data['created_date'] = date('Y-m-d H:i:s');

        $result = $this->db->insert('ticket_log', $data);
        if ($result) {
            return $result;
        } else {
            return false;
        }
    }

    public function cancel_order($order_id)
    {
        $this->db->trans_start();
        $auth_user             = $this->session->userdata('auth_user');
        $uid                 = $auth_user['users_id'];
        $user_email_address = $auth_user['email_address'];
        $name                 = $auth_user['first_name'] . ' ' . $auth_user['last_name'];

        // pr($auth_user);die;
        /*get order total amount*/
        $this->db->select('user_addr_id,order_type,total_amount,is_wallet_used,wallet_used_amount,payment_type,order_number,shipping_charges,refunded_amt,order_status,mb_express,store_id');
        $this->db->where('id', $order_id);
        $this->db->where('user_id', $uid);
        $result = $this->db->get('tbl_order', $order_id)->row();
        $total_amount = 0;
        $store_id = $result->store_id;
        //pr($result);die;
        // pr($result->order_status);die;
        if (!empty($result) && count($result) > 0) {
            if ($result->order_status != 'Delivered' && $result->order_status != 'WAITING PAYMENT CONFIRMATION' && $result->order_status != 'PAYMENT FAILED' && $result->order_status != 'Cancel' && $result->order_status != 'Return') {
                // pr($result->payment_type);die;
                $order_number = $result->order_number;
                if ($result->payment_type != 'COD') {

                    if ($result->is_wallet_used == '1' && $result->payment_type == 'WALLET+COD') {
                        $total_amount = $result->wallet_used_amount;
                    } else {
                        $total_amount = $result->total_amount;
                        if ($result->shipping_charges > 0) {
                            $total_amount += $result->shipping_charges;
                        }
                        if ($result->mb_express > 0) {
                            $total_amount += $result->mb_express;
                        }
                    } //pr("yess");die;
                    $total_amount = $total_amount - $result->refunded_amt;
                    //echo $total_amount; die;

                    /*get order total amount*/
                    /*effect wallet transaction table*/
                    if ($total_amount > 0) {
                        $data = [
                            'user_id'           => $uid,
                            'transaction_type'  => 1,
                            'payment_by'        => 2,
                            'amount'            => $total_amount,
                            'added_date'        => date('Y-m-d H:i:s'),
                            'order_id'          => $order_id
                        ];
                        $this->db->insert('tbl_wallet_transaction', $data);
                        /*effect wallet transaction table*/

                        /*cancel order credit money ad to wallet*/
                        $sql = 'UPDATE tbl_users set wallet_total_amount=wallet_total_amount+' . $total_amount . ' WHERE id = ' . $uid;
                        $this->db->query($sql);

                        // user wallet amt credit email
                        $sql1 = 'SELECT wallet_total_amount,wallet_used_amount from tbl_users WHERE id = ' . $uid;
                        $user_data = $this->db->query($sql1)->row();
                        //pr($user_data);die;
                        if (!empty($user_data) && count($user_data) > 0) {
                            $total_amount         = number_format((float) $total_amount, '2', '.', '');
                            $wallet_total_amount = $user_data->wallet_total_amount;
                            $wallet_used_amount = $user_data->wallet_used_amount;
                            $wallet_balance     = $wallet_total_amount - $wallet_used_amount;
                            $mail_data          = getSystemEmail('refund-in-wallet');
                            $admin_msg             = $mail_data[0]->content;
                            $admin_subject         = $mail_data[0]->subject . ' ' . $order_number;
                            $admin_msg             = str_replace('$invoice_no', $order_number, $admin_msg);
                            $admin_msg             = str_replace('$customer_name', $name, $admin_msg);
                            $admin_msg             = str_replace('$amount', $total_amount, $admin_msg);
                            $admin_msg             = str_replace('$wallet_balance', $wallet_balance, $admin_msg);
                            //pr("yesss");die;
                            //pr($admin_subject);die;
                            //pr($admin_msg);die;

                            $admin_mail = $this->dbsettings->ADMIN_EMAIL;
                            $this->email_lib->SendEmail($admin_subject, $admin_msg, $user_email_address, NULL, $admin_mail);
                        }
                    }
                }

                /*release Inventory*/

                $order_items = $this->get_order_items($order_id, $uid);
                if (isset($order_items) && !empty($order_items) && count($order_items) > 0) {
                    foreach ($order_items as $key1 => $item) {

                        $inv_qry = "UPDATE tbl_inventory set qnty = qnty+$item->product_qty WHERE store_id = $store_id AND product_id = $item->product_id AND priceid = $item->product_weight_id";
                        $this->db->query($inv_qry);
                    }
                }

                #Order cancel /Return EMail
                $mail_data          = getSystemEmail('user-cancel-order');
                $admin_msg             = $mail_data[0]->content;
                $admin_subject         = $mail_data[0]->subject . ' ' . $order_number;
                $admin_msg             = str_replace('$invoice_no', $order_number, $admin_msg);
                $admin_msg             = str_replace('$customer_name', $name, $admin_msg);


                if ($result->order_type == "2") {
                    $add_qry = "SELECT `mobile_number` FROM `tbl_user_address` WHERE `id` = $result->user_addr_id";
                    $shiping_user_mobile_no = $this->db->query($add_qry)->result_array()[0]['mobile_number'];
                    //echo  $this->db->last_query();

                } else {
                    $shiping_user_mobile_no = getUsers($uid)[0]->mobile;
                }

                // pr($shiping_user_mobile_no);die;
                // order_assignstatus_sms($name, $shiping_user_mobile_no, $order_number, 'Cancelled');
                $this->load->library('sms_lib');
                $this->sms_lib->send_order_status_sms($name, $shiping_user_mobile_no, $order_number, 'Cancelled', 'ORDER_CANCEL_BY_CUSTOMER');

                $admin_mail = $this->dbsettings->ADMIN_EMAIL;
                $this->email_lib->SendEmail($admin_subject, $admin_msg, $user_email_address, NULL, $admin_mail);

                $this->db->set('cancel_reason', $_POST['reason']);
                $this->db->set('order_status', 'Cancel');
                if ($_POST['reason']) {
                    $this->db->set('order_cancel_by', 'Customer');
                }
                $this->db->set('refunded_amt', 'refunded_amt+' . $total_amount);
                $this->db->set('is_amount_release', 1);
                $this->db->where('id', $order_id);
                $result1 = $this->db->update('tbl_order');
                #Start Notification 
                $notification['user_id'] = $uid;
                $notification['message'] = "Your order ( #" . $order_number . " ) is cancelled.";
                $this->db->insert('tbl_user_notification', $notification);
                #End Notification 
                if ($total_amount > 0) {
                    #Start Notification 
                    $notification['user_id'] = $uid;
                    $notification['message'] = "Your amount $total_amount is refunded to your wallet respect to order ( #" . $order_number . " ).";
                    $this->db->insert('tbl_user_notification', $notification);
                    #End Notification 
                }


                $this->db->trans_complete();
                return $result1;
            } elseif ($result->order_status == 'Delivered') {
                set_flashdata("error", 'Your order already delivered');
                return 0;
            } elseif ($result->order_status == 'Cancel') {
                set_flashdata("error", 'Your order already Cancelled');
                return 0;
            } elseif ($result->order_status == 'Return') {
                set_flashdata("error", 'Your order already Return');
                return 0;
            } elseif ($result->order_status == 'Return') {
                set_flashdata("error", 'Your order already Returned');
                return 0;
            } else {
                set_flashdata("error", 'Your order not complete');
                return 0;
            }
        } else {
            set_flashdata("error", 'Order not found');
            return 0;
        }
    }

    public function check_in_wishlist($id, $user_id)
    {
        if (isset($id) && !empty($id) && isset($user_id) && !empty($user_id)) {
            $this->db->select('*');
            $this->db->where('status', '1');
            $this->db->where('user_id', $user_id);
            $this->db->where("FIND_IN_SET($id,variant_id)!=", 0);
            $data = $this->db->get('tbl_wishlist')->result();
            // echo $this->db->last_query();
            if ($data) {
                return $data;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public function cancel_order_api($order_id, $user_id, $reason)
    {

        $this->db->trans_start();
        $user_detail        = get_user($user_id);
        $user_email_address = $user_detail->email_address;
        $name               = $user_detail->first_name . ' ' . $user_detail->last_name;
        $user_mobile        = $user_detail->mobile;

        // pr($auth_user);die;
        /*get order total amount*/
        $this->db->select('id,user_addr_id,order_type,total_amount,is_wallet_used,wallet_used_amount,payment_type,order_number,shipping_charges,refunded_amt,order_status,mb_express,store_id,shipping_mobile,login_by,paymoney');
        $this->db->where('id', $order_id);
        $this->db->where('user_id', $user_id);

        $result = $this->db->get($this->tbl_order, $order_id)->row();
        $total_amount = 0;
        $assigned_store_id = $result->store_id;
        // pr($result);die;
        // pr($result->order_status);die;
        if (isset($result) && !empty($result)) {

            if (strtolower($result->order_status) == 'order confirm') {
                $order_number = $result->order_number;
                if ($result->payment_type != 'COD') {
                    if ($result->is_wallet_used == '1' && $result->payment_type == 'WALLET+COD') {
                        $total_amount = $result->wallet_used_amount;
                    } else {
                        $total_amount = $result->total_amount;
                        if ($result->shipping_charges > 0) {
                            $total_amount += $result->shipping_charges;
                        }
                        if ($result->mb_express > 0) {
                            $total_amount += $result->mb_express;
                        }
                    }
                    $total_amount = $total_amount - $result->refunded_amt;
                    // echo $total_amount; die;

                    /*get order total amount*/
                    /*effect wallet transaction table*/
                    if (strtolower($result->login_by) == 'website') {
                        $payment_order_no = $result->order_number;
                    } else {
                        $payment_order_no = $result->id;
                    }

                    require_once(APPPATH . "libraries/PaytmKit/lib/config_paytm.php");
                    require_once(APPPATH . "libraries/PaytmKit/lib/encdec_paytm.php");
                    // Create an array having all required parameters for status query.
                    $requestParamList = array("MID" => PAYTM_MERCHANT_MID, "ORDERID" => $payment_order_no);
                    $StatusCheckSum = getChecksumFromArray($requestParamList, PAYTM_MERCHANT_KEY);
                    $requestParamList['CHECKSUMHASH'] = $StatusCheckSum;
                    // Call the PG's getTxnStatusNew() function for verifying the transaction status.
                    $responseParamList = getTxnStatusNew($requestParamList);
                    // pr($result);
                    // pr($responseParamList);die;

                    if ($responseParamList['STATUS'] == 'TXN_SUCCESS' && isset($responseParamList['TXNAMOUNT']) && !empty($responseParamList['TXNAMOUNT']) && $responseParamList['TXNAMOUNT'] == $result->paymoney) {
                        if ($total_amount > 0) {
                            $data = [
                                'user_id'           => $uid,
                                'transaction_type'  => 1,
                                'payment_by'        => 2,
                                'amount'            => $total_amount,
                                'added_date'        => date('Y-m-d H:i:s'),
                                'order_id'          => $order_id
                            ];
                            $this->db->insert('tbl_wallet_transaction', $data);
                            /*effect wallet transaction table*/

                            /*cancel order credit money ad to wallet*/
                            $sql = 'UPDATE tbl_users set wallet_total_amount=wallet_total_amount+' . $total_amount . ' WHERE id = ' . $uid;
                            $this->db->query($sql);

                            // user wallet amt credit email
                            $user_data = $this->db->query('SELECT wallet_total_amount,wallet_used_amount from tbl_users WHERE id = ' . $uid)->row();
                            // pr($user_data);die;

                            if (!empty($user_data) && count($user_data) > 0) {
                                $total_amount       = number_format((float) $total_amount, '2', '.', '');
                                $wallet_total_amount = $user_data->wallet_total_amount;
                                $wallet_used_amount = $user_data->wallet_used_amount;
                                $wallet_balance     = $wallet_total_amount - $wallet_used_amount;
                                $mail_data          = getSystemEmail('refund-in-wallet');
                                $admin_msg          = $mail_data[0]->content;
                                $admin_subject      = $mail_data[0]->subject . ' ' . $order_number;
                                $admin_msg          = str_replace('$invoice_no', $order_number, $admin_msg);
                                $admin_msg          = str_replace('$customer_name', $name, $admin_msg);
                                $admin_msg          = str_replace('$amount', $total_amount, $admin_msg);
                                $admin_msg          = str_replace('$wallet_balance', $wallet_balance, $admin_msg);
                                $this->email_lib->SendEmailTo($admin_subject, $admin_msg, $user_email_address);
                            }
                        }
                    } else {
                        //  not a valid amount found in paytm transaction
                    }
                }

                /*release Inventory*/

                $order_items = $this->get_order_items($order_id, $uid);
                // pr($order_items);die;
                if (isset($order_items) && !empty($order_items) && count($order_items) > 0) {
                    foreach ($order_items as $key1 => $item) {

                        $inv_qry = "UPDATE tbl_inventory set qnty = qnty+$item->product_qty WHERE store_id = $assigned_store_id AND product_id = $item->product_id AND priceid = $item->product_weight_id";
                        $this->db->query($inv_qry);

                        if (isset($item->offer_id) && !empty($item->offer_id)) {
                            $this->db->where('offer_type', $item->offer_type);
                            $this->db->where('user_id', $item->customer_id);
                            $this->db->where('order_id', $item->order_id);
                            $this->db->where('offer_id', $item->offer_id);
                            $this->db->where('variant_id', $item->product_weight_id);
                            $this->db->update('tbl_offer_redeem_limit', ['status' => 0]);
                        }
                    }
                }

                #Order cancel /Return EMail
                $mail_data          = getSystemEmail('user-cancel-order');
                $admin_msg          = $mail_data[0]->content;
                $admin_subject      = $mail_data[0]->subject . ' ' . $order_number;
                $admin_msg          = str_replace('$invoice_no', $order_number, $admin_msg);
                $admin_msg          = str_replace('$customer_name', $name, $admin_msg);

                if ($result->order_type == 2) {
                    $shiping_user_mobile_no = $user_mobile;
                } elseif ($result->order_type == 2) {
                    $shiping_user_mobile_no = $result->shipping_mobile;
                } else {
                    $shiping_user_mobile_no = $user_mobile;
                }

                //pr($shiping_user_mobile_no);die;
                if (isset($shiping_user_mobile_no) && !empty($shiping_user_mobile_no) && strlen($shiping_user_mobile_no) >= 10) {
                    $this->load->library('sms_lib');
                    $this->sms_lib->send_order_status_sms($name, $shiping_user_mobile_no, $order_number, 'Cancelled', 'ORDER_CANCEL_BY_CUSTOMER');
                }

                $this->email_lib->SendEmailToOrder($admin_subject, $admin_msg, $user_email_address);

                $this->db->set('cancel_reason', $reason);
                $this->db->set('order_status', 'Cancel');
                if ($reason) {
                    $this->db->set('order_cancel_by', 'Customer');
                }
                $this->db->set('refunded_amt', 'refunded_amt+' . $total_amount);
                $this->db->set('is_amount_release', 1);
                $this->db->where('id', $order_id);
                $result1 = $this->db->update($this->tbl_order);
                #Start Notification 
                $notification['user_id'] = $user_id;
                $notification['message'] = "Your order ( #" . $order_number . " ) is cancelled.";
                $this->db->insert('tbl_user_notification', $notification);
                #End Notification 
                if ($total_amount > 0) {
                    #Start Notification 
                    $notification['user_id'] = $user_id;
                    $notification['message'] = "Your amount $total_amount is refunded to your wallet respect to order ( #" . $order_number . " ).";
                    $this->db->insert('tbl_user_notification', $notification);
                    #End Notification 
                }

                $this->db->trans_complete();
                return ['status' => $result1, 'message' => 'Your order cancelled successfully'];
            } elseif ($result->order_status == 'Delivered') {

                return ['status' => 0, 'message' => 'Your order already delivered'];
            } elseif ($result->order_status == 'Cancel') {
                return ['status' => 0, 'message' => 'Your order already Cancelled'];
            } elseif ($result->order_status == 'Out for Delivery') {
                return ['status' => 0, 'message' => 'Your order already Out for Delivery'];
            } elseif ($result->order_status == 'Return') {
                return ['status' => 0, 'message' => 'Your order already Returned'];
            } else {
                return ['status' => 0, 'message' => 'The order is already under process. Please call customer care +91-6377716311 for more details'];
            }
        } else {
            return ['status' => 0, 'message' => 'Order not found'];
        }
    }

    public function get_offers()
    {
        date_default_timezone_set('Asia/Kolkata');
        $data = '';
        $date = date("Y-m-d H:i:s");
        $store_id = get_store_id('id');
        $user_id = $this->session->userdata['auth_user']['users_id'];
        $this->db->select('store_id');
        $this->db->where('user_id', $user_id);
        $store_lists = $this->db->get('tbl_user_address')->result_array();
        // pr($store_lists);die;
        $find_in_set = '( ';
        if (count($store_lists) > 0) {
            foreach ($store_lists as $key => $store_list) {
                $find_in_set .= " FIND_IN_SET('" . $store_list['store_id'] . "',store_id) OR";
            }
            $find_in_set = rtrim($find_in_set, 'OR');
            $find_in_set = $find_in_set . " )";
        } else {
            return array();
        }
        $sql = "SELECT * FROM tbl_discount WHERE start_date <= '" . $date . "' AND `end_date` >= '" . $date . "' AND " . $find_in_set . "           
        AND (CASE WHEN applicable = 1 THEN (FIND_IN_SET('" . $user_id . "',`users`)) ELSE (users = NULL OR users='' OR users = '0') END)
        AND STATUS='Active' ORDER BY `start_date` ASC";
        $result = $this->db->query($sql)->result();
        if (isset($result) && !empty($result)) {
            foreach ($result as $key => $value) {
                $this->db->select('*, SUM(purchaged_limit) as purchaged_limit');
                $this->db->where('offer_type', 2);
                $this->db->where('user_id', $user_id);
                $this->db->where('offer_id', $value->id);
                $this->db->group_by('offer_type');
                $query = $this->db->get('tbl_offer_redeem_limit')->row();
                $value->purchaged_limit = $query->purchaged_limit;
                // if($value->offer_img){
                //     $value->offer_img = base_url().'assets/uploads/product/'.$value->offer_img;
                //  }else{
                //     $value->offer_img = base_url().'assets/img/offer_list_img1.jpg';
                //  }
                $data[] = $value;
            }
        } else {
            $data =  $result;
        }
        foreach ($data as $key_data => $value_data) {
            if (isset($value_data->category) && !empty($value_data->category)) {
                $category =  array_filter(explode(",", $value_data->category));
                if (count($category) > 0 && count($category) == 1) {
                    $sqll = "SELECT parent_id,url_name,name FROM `tbl_categories` WHERE `id` = $category[0] ORDER BY `url_name` ASC";
                    $parent_id = $this->db->query($sqll)->row();

                    $sql_parent_product_check = "SELECT COUNT(category_ids) as total FROM `tbl_product` WHERE FIND_IN_SET($category[0],`category_ids`) ORDER BY `product_pec_weights` ASC";
                    $parent_product_check = $this->db->query($sql_parent_product_check)->row()->total;

                    if (isset($parent_id->parent_id) && !empty($parent_id->parent_id)) {
                        $sql_cat_url = "SELECT url_name,parent_id,name FROM `tbl_categories` WHERE `id` = $parent_id->parent_id ORDER BY `url_name` ASC";
                        $cat_url = $this->db->query($sql_cat_url)->row();

                        $sql_cat_product_check = "SELECT COUNT(category_ids) as total FROM `tbl_product` WHERE FIND_IN_SET($parent_id->parent_id,`category_ids`) ORDER BY `product_pec_weights` ASC";
                        $parent_cat_product_check = $this->db->query($sql_cat_product_check)->row()->total;
                        //pr($parent_cat_product_check);die;
                        if ($parent_cat_product_check > 0) {
                            $value_data->cat_url = $cat_url->url_name . '/' . $category[0];
                            $value_data->cat_name = $cat_url->name;
                            $value_data->subcat_name = $parent_id->name;
                            $value_data->parent_id = $parent_id->parent_id;
                            $value_data->cat_url_exist = 1;
                        } else {
                            $value_data->subcat_name = 'Applied on all categories';
                            $value_data->cat_url_exist = 0;
                        }

                        $sql_cat_product_check = null;
                        $parent_cat_product_check = null;
                    } else {
                        if ($parent_product_check > 0) {
                            $value_data->cat_url = $parent_id->url_name;
                            $value_data->cat_name = $parent_id->name;
                            $value_data->parent_id = $parent_id->parent_id;
                            $value_data->cat_url_exist = 1;
                        } else {
                            $value_data->subcat_name = 'Applied on all categories';
                            $value_data->cat_url_exist = 0;
                        }
                        $parent_product_check = null;
                        $sql_parent_product_check = null;
                    }
                } else {
                    //pr($category);
                    $value_data->subcat_name = 'View offer categories';
                    $value_data->cat_url_exist = 2;
                    foreach ($category as $key_category => $value_category) {
                        $parent_id = null;
                        $sqll = null;
                        $sqll = "SELECT parent_id,url_name,name FROM `tbl_categories` WHERE `id` = $value_category ORDER BY `url_name` ASC";
                        $parent_id = $this->db->query($sqll)->row();

                        $sqll_parent_product_check = "SELECT COUNT(category_ids) as total FROM `tbl_product` WHERE FIND_IN_SET($value_category,`category_ids`) ORDER BY `product_pec_weights` ASC";
                        $parent_product = $this->db->query($sqll_parent_product_check)->row()->total;

                        if (isset($parent_id->parent_id) && !empty($parent_id->parent_id)) {
                            $sql_cat_url = "SELECT url_name,parent_id,name FROM `tbl_categories` WHERE `id` = $parent_id->parent_id ORDER BY `url_name` ASC";
                            $cat_url = $this->db->query($sql_cat_url)->row();

                            $sqll_parent_cat_check = "SELECT COUNT(category_ids) as total FROM `tbl_product` WHERE FIND_IN_SET($parent_id->parent_id,`category_ids`) ORDER BY `product_pec_weights` ASC";
                            $parent_parent_product = $this->db->query($sqll_parent_cat_check)->row()->total;
                            //pr($value_category);die;
                            if ($parent_parent_product > 0) {
                                $new_cat_data[$key_category]['cat_url'] = $cat_url->url_name . '/' . $value_category;
                                $new_cat_data[$key_category]['cat_name'] = $cat_url->name;
                                $new_cat_data[$key_category]['subcat_name'] = $parent_id->name;
                                $new_cat_data[$key_category]['parent_id'] = $parent_id->parent_id;
                                $new_cat_data[$key_category]['category_id'] = $value_category;
                                $new_cat_data[$key_category]['cat_url_exist'] = 1;
                            } else {
                                $new_cat_data[$key_category]['cat_url_exist'] = 0;
                            }

                            //pr($new_cat_data[$key_category]->cat_url);die; 
                        } else {
                            if ($parent_product > 0) {
                                $new_cat_data[$key_category]['cat_url'] = $parent_id->url_name;
                                $new_cat_data[$key_category]['cat_name'] = $parent_id->name;
                                $new_cat_data[$key_category]['parent_id'] = $parent_id->parent_id;
                                $new_cat_data[$key_category]['category_id'] = $value_category;
                                $new_cat_data[$key_category]['cat_url_exist'] = 1;
                            } else {
                                $new_cat_data[$key_category]['cat_url_exist'] = 0;
                                $value_data->subcat_name = 'Applied on all categories';
                            }
                            $sqll_parent_product_check = null;
                            $parent_product = null;
                        }
                    } //pr($new_cat_data[0]['cat_url_exist']);die;
                    if (isset($new_cat_data[0]['cat_url_exist']) && !empty($new_cat_data[0]['cat_url_exist'])) {

                        $value_data->multi_cat_url = $new_cat_data;
                    }
                    $new_cat_data = null;
                }
            } else {
                $value_data->cat_url_exist = 0;
                $value_data->subcat_name = 'Applied on all categories';
            }
        }
        //pr($data);die;
        return $data;
        // echo $this->db->last_query();die;   
    }

    // public function get_offers_api(){

    //     date_default_timezone_set('Asia/Kolkata');
    //     $CI = & get_instance();
    //     $data = '';
    //     $date = date("Y-m-d H:i:s");
    //     $store_id = $_POST['store_id'];
    //     $user_id = $_POST['user_id'];
    //     $this->db->select('store_id');
    //     $this->db->where('user_id',$user_id);
    //     $store_lists = $this->db->get('tbl_user_address')->result_array();

    //     $find_in_set = '( ';
    //     if(count($store_lists)>0)
    //     {
    //         foreach ($store_lists as $key => $store_list) {
    //             $find_in_set .= " FIND_IN_SET('".$store_list['store_id']."',store_id) OR";
    //         }
    //         $find_in_set = rtrim($find_in_set,'OR');
    //         $find_in_set = $find_in_set." )";
    //     }
    //     else
    //     {
    //         return array();
    //     }


    //     $sql = "SELECT * FROM tbl_discount WHERE start_date <= '".$date."' AND `end_date` >= '".$date."'  AND ".$find_in_set."           
    //         AND (CASE WHEN applicable = 1 THEN (FIND_IN_SET('".$user_id."',`users`)) ELSE (users = NULL OR users='' OR users = '0') END)
    //         AND STATUS='Active'  ORDER BY `start_date` ASC";
    //     $result = $this->db->query($sql)->result();
    //     if(!empty($result))
    //     {
    //         foreach ($result as $key => $value) {
    //             $this->db->select('*, SUM(purchaged_limit) as purchaged_limit');
    //             $this->db->where('offer_type',2);
    //             $this->db->where('user_id',$user_id);
    //             $this->db->where('offer_id',$value->id);
    //             $this->db->group_by('offer_type');
    //             $query = $this->db->get('tbl_offer_redeem_limit')->row();
    //             $value->purchaged_limit = $query->purchaged_limit;
    //             $value->remaining = $value->redeem_limit-$value->purchaged_limit;
    //             $data[] = $value;
    //         }
    //     }
    //     else
    //     {
    //         $data =  $result;
    //     }
    //  return $data;
    // }



    public function get_offers_api()
    {

        date_default_timezone_set('Asia/Kolkata');
        $CI = &get_instance();
        $data = '';
        $date = date("Y-m-d H:i:s");
        $store_id = $_POST['store_id'];
        $user_id = $_POST['user_id'];
        $this->db->select('store_id');
        $this->db->where('user_id', $user_id);
        $store_lists = $this->db->get('tbl_user_address')->result_array();

        $find_in_set = '( ';
        if (count($store_lists) > 0) {
            foreach ($store_lists as $key => $store_list) {
                $find_in_set .= " FIND_IN_SET('" . $store_list['store_id'] . "',store_id) OR";
            }
            $find_in_set = rtrim($find_in_set, 'OR');
            $find_in_set = $find_in_set . " )";
        } else {
            return array();
        }


        $sql = "SELECT * FROM tbl_discount WHERE start_date <= '" . $date . "' AND `end_date` >= '" . $date . "'  AND " . $find_in_set . "           
            AND (CASE WHEN applicable = 1 THEN (FIND_IN_SET('" . $user_id . "',`users`)) ELSE (users = NULL OR users='' OR users = '0') END)
            AND STATUS='Active'  ORDER BY `start_date` ASC";
        $result = $this->db->query($sql)->result();
        if (!empty($result)) {
            foreach ($result as $key => $value) {
                $this->db->select('*, SUM(purchaged_limit) as purchaged_limit');
                $this->db->where('offer_type', 2);
                $this->db->where('user_id', $user_id);
                $this->db->where('offer_id', $value->id);
                $this->db->group_by('offer_type');
                $query = $this->db->get('tbl_offer_redeem_limit')->row();
                $value->purchaged_limit = $query->purchaged_limit;
                $value->remaining = $value->redeem_limit - $value->purchaged_limit;
                if ($value->offer_img) {
                    $value->offer_img = base_url() . 'assets/uploads/product/' . $value->offer_img;
                } else {
                    $value->offer_img = base_url() . 'assets/img/offer_list_img1.jpg';
                }
                $data[] = $value;
            }
        } else {
            $data =  $result;
        }
        foreach ($data as $key_data => $value_data) {
            if ($value_data->category) {
                $category =  array_filter(explode(",", $value_data->category));
                if (count($category) > 0 && count($category) == 1) {
                    $sqll = "SELECT parent_id,url_name,name FROM `tbl_categories` WHERE `id` = $category[0] ORDER BY `url_name` ASC";
                    $parent_id = $this->db->query($sqll)->row();

                    $sql_parent_product_check = "SELECT COUNT(category_ids) as total FROM `tbl_product` WHERE FIND_IN_SET($category[0],`category_ids`) ORDER BY `product_pec_weights` ASC";
                    $parent_product_check = $this->db->query($sql_parent_product_check)->row()->total;

                    if ($parent_id->parent_id) {
                        $sql_cat_url = "SELECT url_name,parent_id,name FROM `tbl_categories` WHERE `id` = $parent_id->parent_id ORDER BY `url_name` ASC";
                        $cat_url = $this->db->query($sql_cat_url)->row();

                        $sql_cat_product_check = "SELECT COUNT(category_ids) as total FROM `tbl_product` WHERE FIND_IN_SET($parent_id->parent_id,`category_ids`) ORDER BY `product_pec_weights` ASC";
                        $parent_cat_product_check = $this->db->query($sql_cat_product_check)->row()->total;
                        //pr($parent_cat_product_check);die;
                        if ($parent_cat_product_check > 0) {
                            $value_data->cat_url = $cat_url->url_name . '/' . $category[0];
                            $value_data->cat_name = $cat_url->name;
                            $value_data->subcat_name = $parent_id->name;
                            $value_data->parent_id = $parent_id->parent_id;
                            $value_data->cat_url_exist = 1;
                        } else {
                            $value_data->subcat_name = 'Applied on all categories';
                            $value_data->cat_url_exist = 0;
                        }

                        $sql_cat_product_check = null;
                        $parent_cat_product_check = null;
                    } else {
                        if ($parent_product_check > 0) {
                            $value_data->cat_url = $parent_id->url_name;
                            $value_data->cat_name = $parent_id->name;
                            $value_data->parent_id = $parent_id->parent_id;
                            $value_data->cat_url_exist = 1;
                        } else {
                            $value_data->subcat_name = 'Applied on all categories';
                            $value_data->cat_url_exist = 0;
                        }
                        $parent_product_check = null;
                        $sql_parent_product_check = null;
                    }
                } else {
                    //pr($category);
                    $value_data->subcat_name = 'View offer categories';
                    $value_data->cat_url_exist = 2;
                    foreach ($category as $key_category => $value_category) {
                        $parent_id = null;
                        $sqll = null;
                        $sqll = "SELECT parent_id,url_name,name FROM `tbl_categories` WHERE `id` = $value_category ORDER BY `url_name` ASC";
                        $parent_id = $this->db->query($sqll)->row();

                        $sqll_parent_product_check = "SELECT COUNT(category_ids) as total FROM `tbl_product` WHERE FIND_IN_SET($value_category,`category_ids`) ORDER BY `product_pec_weights` ASC";
                        $parent_product = $this->db->query($sqll_parent_product_check)->row()->total;

                        if ($parent_id->parent_id) {
                            $sql_cat_url = "SELECT url_name,parent_id,name FROM `tbl_categories` WHERE `id` = $parent_id->parent_id ORDER BY `url_name` ASC";
                            $cat_url = $this->db->query($sql_cat_url)->row();

                            $sqll_parent_cat_check = "SELECT COUNT(category_ids) as total FROM `tbl_product` WHERE FIND_IN_SET($parent_id->parent_id,`category_ids`) ORDER BY `product_pec_weights` ASC";
                            $parent_parent_product = $this->db->query($sqll_parent_cat_check)->row()->total;

                            if ($parent_parent_product > 0) {
                                $new_cat_data[$key_category]->cat_url = $cat_url->url_name . '/' . $value_category;
                                $new_cat_data[$key_category]->cat_name = $cat_url->name;
                                $new_cat_data[$key_category]->subcat_name = $parent_id->name;
                                $new_cat_data[$key_category]->parent_id = $parent_id->parent_id;
                                $new_cat_data[$key_category]->category_id = $value_category;
                                $new_cat_data[$key_category]->cat_url_exist = 1;
                            } else {
                                $new_cat_data[$key_category]->cat_url_exist = 0;
                            }
                        } else {
                            if ($parent_product > 0) {
                                $new_cat_data[$key_category]->cat_url = $parent_id->url_name;
                                $new_cat_data[$key_category]->cat_name = $parent_id->name;
                                $new_cat_data[$key_category]->parent_id = $parent_id->parent_id;
                                $new_cat_data[$key_category]->category_id = $value_category;
                                $new_cat_data[$key_category]->cat_url_exist = 1;
                            } else {
                                $new_cat_data[$key_category]->cat_url_exist = 0;
                                $value_data->subcat_name = 'Applied on all categories';
                            }
                            $sqll_parent_product_check = null;
                            $parent_product = null;
                        }
                    }
                    if ($new_cat_data[0]->cat_url_exist) {
                        $value_data->multi_cat_url = $new_cat_data;
                    }
                    $new_cat_data = null;
                }
            } else {
                $value_data->cat_url_exist = 0;
                $value_data->subcat_name = 'Applied on all categories';
            }
        }

        return $data;
    }





    // public function get_offers1(){
    //       $store_id = get_store_id('id');
    //       $user_id = @$_SESSION['auth_user']['users_id'];
    //      $offer_array = array();
    //      $current_date = date('Y-m-d H:i:s');

    //      $this->db->select('*');
    //      $this->db->where('status','Active');
    //      $this->db->where("FIND_IN_SET($store_id,store_id)!=", 0);
    //      $this->db->where('start_date <=',$current_date);
    //      $this->db->where('end_date >=',$current_date);
    //      $result = $this->db->get('tbl_discount')->result();

    //      if(!empty($result)){
    //         foreach($result as $key_r=>$val_r){
    //             if($val_r->applicable == '1'){

    //                  $this->db->select('*');
    //                  $this->db->where('status','Active');
    //                  // $this->db->where('store_id',$store_id);
    //                  $this->db->where("FIND_IN_SET($store_id,store_id)!=", 0);
    //                  $this->db->where("FIND_IN_SET($user_id,users)!=", 0);
    //                  $applicable_user = $this->db->get('tbl_discount')->result();
    //                  $offer_array = $applicable_user;
    //             }else{

    //                 $offer_array[$key_r] = $val_r;
    //             }
    //         }
    //     }
    //     // echo $this->db->last_query();die;   
    //     return $offer_array;
    //  }

    public function get_orders_for_api($offset)
    {

        $uid = $_POST['user_id'];
        $limit = $this->dbsettings->WEBSITE_PAGINATION;
        $this->db->select('*');
        $this->db->where('user_id', $uid);
        $this->db->order_by('id', 'desc');
        if (!empty($offset) && $offset > 0) {
            $this->db->limit($limit, $offset);
        } else {
            $this->db->limit($limit, 0);
        }
        $result = $this->db->get('tbl_order')->result();
        if (!empty($result)) {
            foreach ($result as $key_rt => $val_rt) {
                $val_rt->total_amount = number_format((($val_rt->total_amount + $val_rt->shipping_charges + $val_rt->mb_express) - ($val_rt->refunded_amt)), 2, '.', '');
                $val_rt->order_date = date('d-m-Y h:i A', strtotime($val_rt->order_date));
                if ($val_rt->order_status == 'Delivered' || $val_rt->order_status == 'Picked up by Customer') {
                    $current_date = date('Y-m-d');
                    $delivery_date = date('Y-m-d', strtotime($val_rt->order_delivered_date));
                    $date1 = date_create($delivery_date);
                    $date2 = date_create($current_date);
                    $diff = date_diff($date1, $date2);
                    $total_days = $diff->format("%a");
                    $val_rt->difference = $total_days;
                } else {
                    $val_rt->difference = '';
                }
            }
        }
        if (!empty($result)) {
            return $result;
        } else {
            return false;
        }
    }


    public function get_order_detail($order_id)
    {

        $this->db->select('tbl_order.*,dn.day_name as DAY_NAME');
        $this->db->where('tbl_order.id', $order_id);
        $this->db->join('tbl_timeslot as TBLTS', 'TBLTS.id=tbl_order.selectdeliveryslot', 'left');
        $this->db->join('tbl_dayname as dn', 'dn.id=TBLTS.day_id', 'left');
        $result = $this->db->get('tbl_order')->row();
        // pr($result);die;
        if (isset($result->product_weight) && !empty($result->product_weight)) {

            $string_ids = rtrim($result->product_weight, ',');
            $array_ids = explode(',', $string_ids);
            $this->db->select('*');
            $this->db->where_in('id', $array_ids);
            // $this->db->order_by('id','desc');
            $product_price = $this->db->get('tbl_product_price')->result();

            if (isset($product_price) && !empty($product_price)) {
                foreach ($product_price as $key_pp => $val_pp) {
                    $this->db->select('*');
                    $this->db->where('product_id', $val_pp->product_id);
                    $product = $this->db->get('tbl_product')->row();
                    $product_price[$key_pp]->product = $product;

                    /* get substitute product individual product */
                    $substitute_product = $result->substitute_product;
                    $substitute_array = explode('~', $substitute_product);

                    $order_status = $result->p_status;
                    $status_array = explode('~', $order_status);

                    $product_weight = $result->product_weight;
                    $product_weight_string = rtrim($result->product_weight, ',');
                    $product_weight_array = explode(',', $product_weight_string);
                    $final_substitute_array = array();
                    $product_status = array();
                    if (!empty($product_weight_array)) {
                        foreach ($product_weight_array as $key_p => $val_p) {
                            $final_substitute_array[$val_p] = isset($substitute_array[$key_p]) ? $substitute_array[$key_p] : '';
                            $product_status[$val_p] = $status_array[$key_p];
                        }
                    }

                    if (!empty($final_substitute_array)) {
                        $current_substitute = '';
                        $current_status = '';
                        foreach ($final_substitute_array as $key_f => $val_f) {
                            if ($key_f == $product->weight_ids) {
                                $current_substitute = $val_f;
                                $current_status = $product_status[$key_f];
                            }
                        }
                    }

                    $product_price[$key_pp]->selected_substitute = $current_substitute;
                    $product_price[$key_pp]->product_status = $current_status;
                    /* End of get substitute product individual product */
                }
            }
        }

        $result->product_data = $product_price;
        $new_date = '';
        $current_date = date('Y-m-d H:i:s');
        if ($result) {

            $new_date =  date('Y-m-d H:i:s', strtotime($result->order_date . ' + 2 day'));
            if ($new_date >= $current_date) {
                $result->is_rescheduled_possible = 'yes';
            } else {
                $result->is_rescheduled_possible = 'no';
            }
        }

        /* Calculate total saving on this order*/
        $total_price = '';
        $unit_price = explode(',', rtrim($result->unit_price, ','));
        foreach ($unit_price as $key_u => $val_u) {
            $total_price += $val_u;
        }

        $total_amount = ($total_price) + $result->shipping_charges;

        $total_saving = $total_amount - $result->paymoney;
        /* Calculate total saving on this order*/
        $result->total_saving = $total_saving;

        if (!empty($result)) {

            return $result;
        } else {
            return false;
        }
    }

    public function get_product_data()
    {
        $order_id = $_POST['order_id'];
        $product_array  = array();
        $this->db->select('TBLOD.product_name,TBLOD.product_weight_id as id,TBLOD.pweight as product_pec_weight');
        $this->db->where('order_id', $order_id);
        $result = $this->db->get('tbl_order_detail as TBLOD')->result();
        if (!empty($result)) {
            return $result;
        } else {
            return false;
        }
    }


    public function get_delivery_boy_data()
    {
        if ($_POST['order_id']) {
            $this->db->select('TBLDB.id,TBLDB.first_name,TBLDB.last_name');
            $this->db->where('id', $_POST['order_id']);
            $this->db->join('tbl_delivery_boys as TBLDB', 'TBLDB.id = TBLO.delivery_boy_id');
            $result =  $this->db->get('tbl_order as TBLO')->row();
            if ($result) {
                return $result;
            } else {
                return false;
            }
        }
    }

    public function get_last_order_rating($user_id = '')
    {
        if ($user_id != '') {
            $uid = $user_id;
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }
        $this->db->select('rating,reting_review,id,order_number');
        $this->db->where('user_id', $uid);
        $this->db->where('order_status', 'Delivered');
        $this->db->order_by('id', 'desc');
        $this->db->limit(1);
        $result = $this->db->get('tbl_order')->row();
        if ($result) {
            return $result;
        } else {
            return false;
        }
    }


    public function insert_ticekt_data($pan_file, $user_id = '')
    {
        if ($user_id) {
            $uid = $user_id;
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }

        $data['ticket_type'] = '1';
        $data['order_id'] = $_POST['order_id'];
        $data['document'] = $pan_file;
        $data['issue_type'] = $_POST['issue_type'];
        if ($_POST['issue_type'] == '1') {
            $data['product'] = $_POST['selected_data'];
        } else {
            $data['delivery_boy'] = $_POST['selected_data'];
        }
        $data['subject'] = $_POST['subject'];
        $data['description'] = $_POST['description'];
        $data['status'] = '1';
        $data['added_by'] = $uid;
        $data['created_date'] = date('Y-m-d H:i:s');
        $result = $this->db->insert('manage_ticket', $data);
        $insert_id = $this->db->insert_id();


        $this->db->set('is_ticket_generated', '1');
        $this->db->where('id', $_POST['order_id']);
        $this->db->update('tbl_order');


        if ($insert_id) {
            return $insert_id;
        } else {
            return false;
        }
    }

    public function get_order_ticket_data($user_id_api = '')
    {
        if ($user_id_api) {
            $user_id = $user_id_api;
        } else {
            $user_id = $_SESSION['auth_user']['users_id'];
        }
        $this->db->select('*');
        $this->db->where('added_by', $user_id);
        $this->db->where('ticket_type', '1');
        $this->db->order_by('id', 'desc');
        $query = $this->db->get('manage_ticket')->result();
        if (!empty($query)) {
            foreach ($query as $key_qq => $val_qq) {
                $val_qq->created_date = date('d-m-Y h:i A', strtotime($val_qq->created_date));
            }
        }
        if ($query) {
            return $query;
        } else {
            return false;
        }
    }

    public function get_store_ticket_data($user_id_api = '')
    {
        if ($user_id_api) {
            $user_id = $user_id_api;
        } else {
            $user_id = $_SESSION['auth_user']['users_id'];
        }
        $this->db->select('manage_ticket.*,TBLS.store_name');
        $this->db->where('added_by', $user_id);
        $this->db->where('ticket_type', '2');
        $this->db->join('tbl_store as TBLS', 'TBLS.store_id = manage_ticket.store');
        $this->db->order_by('id', 'desc');
        $query = $this->db->get('manage_ticket')->result();
        if (!empty($query)) {
            foreach ($query as $key_qqq => $val_qqq) {
                $val_qqq->created_date = date('d-m-Y h:i A', strtotime($val_qqq->created_date));
                $val_qqq->visit_date = date('d-m-Y', strtotime($val_qqq->visit_date));
            }
        }
        if ($query) {
            return $query;
        } else {
            return false;
        }
    }

    public function get_delivyer_boy_existence($order_id)
    {
        $this->db->select('id,delivery_boy_id,is_ticket_generated');
        $this->db->where('id', $order_id);
        $result = $this->db->get('tbl_order')->row();
        if ($result) {
            if ($result->is_ticket_generated == '1') {
                $this->db->select('id');
                $this->db->where('order_id', $order_id);
                $query = $this->db->get('manage_ticket')->row();
                if ($query) {
                    $result->ticket_id = $query->id;
                } else {
                    $result->ticket_id = '';
                }
            }
        }
        if ($result) {
            return $result;
        }
        return false;
    }

    public function get_ticket_view_order($id)
    {

        $this->db->select('manage_ticket.*,Tbl_O.order_number as order_id');
        $this->db->where('manage_ticket.id', $id);
        $this->db->join('tbl_order as Tbl_O', 'Tbl_O.id = manage_ticket.order_id');
        $query = $this->db->get('manage_ticket')->row();
        $query->created_date = date('d-m-Y h:i A', strtotime($query->created_date));
        if ($query->issue_type == '1') {

            $this->db->select('*');
            $this->db->where('id', $query->product);
            $product_price = $this->db->get('tbl_product_price')->result();

            if (!empty($product_price)) {
                foreach ($product_price as $key_pp => $val_pp) {

                    $this->db->select('product_name');
                    $this->db->where('product_id', $val_pp->product_id);
                    $product = $this->db->get('tbl_product')->row();

                    $product_price[$key_pp]->product_name = $product->product_name;
                }
            }
            $product_name = $product_price[0]->product_name . ' ' . $product_price[0]->product_pec_weight;
            $query->name = $product_name;
        } else if ($query->issue_type == '2') {

            $delivery_boy = $query->delivery_boy;
            $this->db->select('first_name,last_name');
            $this->db->where('id', $delivery_boy);
            $result = $this->db->get('tbl_delivery_boys')->row();
            if ($result) {
                $query->name = $result->first_name . ' ' . $result->last_name;
            }
        }

        $ticket_id = $query->id;
        if (!empty($ticket_id)) {
            $this->db->select('*');
            $this->db->where('ticket_id', $ticket_id);
            $log = $this->db->get('ticket_log')->result();
            if (!empty($log)) {
                $query->log = $log;
            } else {
                $query->log = '';
            }
        }

        if ($query) {
            return $query;
        } else {
            return false;
        }
    }

    public function get_ticket_view($id)
    {

        $this->db->select('manage_ticket.*'); //,TBLST.store_name
        $this->db->where('id', $id);
        //$this->db->join('tbl_store as TBLST','TBLST.store_id = manage_ticket.store');
        $query = $this->db->get('manage_ticket')->row();

        if ($query->issue_type == '1') {
            $this->db->select('*');
            $this->db->where('id', $query->product);
            $product_price = $this->db->get('tbl_product_price')->result();

            if (!empty($product_price)) {
                foreach ($product_price as $key_pp => $val_pp) {

                    $this->db->select('product_name');
                    $this->db->where('product_id', $val_pp->product_id);
                    $product = $this->db->get('tbl_product')->row();

                    $product_price[$key_pp]->product_name = $product->product_name;
                }
            }
            $product_name = $product_price[0]->product_name . ' ' . $product_price[0]->product_pec_weight;
            $query->name = $product_name;
        } else if ($query->issue_type == '2') {

            $delivery_boy = $query->delivery_boy;
            $this->db->select('first_name,last_name');
            $this->db->where('id', $delivery_boy);
            $result = $this->db->get('tbl_delivery_boys')->row();
            if ($result) {
                $query->name = $result->first_name . ' ' . $result->last_name;
            }
        }

        if ($query) {
            return $query;
        } else {
            return false;
        }
    }


    public function get_ticket_view_api($id)
    {

        $this->db->select('manage_ticket.*,TBLST.store_name');
        $this->db->where('id', $id);
        $this->db->join('tbl_store as TBLST', 'TBLST.store_id = manage_ticket.store');
        $query = $this->db->get('manage_ticket')->row();

        if ($query->issue_type == '1') {
            $this->db->select('*');
            $this->db->where('id', $query->product);
            $product_price = $this->db->get('tbl_product_price')->result();

            if (!empty($product_price)) {
                foreach ($product_price as $key_pp => $val_pp) {

                    $this->db->select('product_name');
                    $this->db->where('product_id', $val_pp->product_id);
                    $product = $this->db->get('tbl_product')->row();

                    $product_price[$key_pp]->product_name = $product->product_name;
                }
            }
            $product_name = $product_price[0]->product_name . ' ' . $product_price[0]->product_pec_weight;
            $query->name = $product_name;
        } else if ($query->issue_type == '2') {

            $delivery_boy = $query->delivery_boy;
            $this->db->select('first_name,last_name');
            $this->db->where('id', $delivery_boy);
            $result = $this->db->get('tbl_delivery_boys')->row();
            if ($result) {
                $query->name = $result->first_name . ' ' . $result->last_name;
            }
        }


        $query->created_date = date('d-m-Y h:i A', strtotime($query->created_date));
        $query->visit_date = date('d-m-Y', strtotime($query->visit_date));

        if ($query) {
            return $query;
        } else {
            return false;
        }
    }



    public function get_order_detail_for_api()
    {

        $order_id = $_POST['order_id'];
        $this->db->select('*');
        $this->db->where('id', $order_id);
        $result = $this->db->get('tbl_order')->row();
        $derived_address = '';

        if ($result->user_address != '') {
            $derived_address .= $result->user_address . ',';
        }
        if ($result->user_landmark != '') {
            $derived_address .= $result->user_landmark . ',';
        }
        if ($result->user_locality != '') {
            $derived_address .= $result->user_locality . ',';
        }
        if ($result->user_city != '') {
            $derived_address .= $result->user_city . ',';
        }
        if ($result->user_state != '') {
            $derived_address .= $result->user_state . ',';
        }
        if ($result->user_zipcode != '' && $result->user_zipcode != '0') {
            $derived_address .= $result->user_zipcode . ',';
        }

        $result->printed_address = rtrim($derived_address, ',');

        if (isset($result) && !empty($result)) {

            $result->order_date = date('d-m-Y h:i A', strtotime($result->order_date));

            if ($result->order_status == 'Delivered' || $result->order_status == 'Picked up by Customer') {

                $current_date = date('Y-m-d');
                $delivery_date = date('Y-m-d', strtotime($result->order_delivered_date));
                $date1 = date_create($delivery_date);
                $date2 = date_create($current_date);
                $diff = date_diff($date1, $date2);
                $total_days = $diff->format("%a");
                $result->difference = $total_days;
            } else {
                $result->difference = '';
            }
        }

        if (isset($result) && !empty($result)) {
            $current_date1 = date('Y-m-d');
            $orderDate = date('Y-m-d', strtotime($result->order_date));
            $date11 = date_create($orderDate);
            $date22 = date_create($current_date1);
            $diff1 = date_diff($date11, $date22);
            $total_days1 = $diff1->format("%a");
            $result->reschedule_difference = $total_days1;
        }

        if ($result->selectdeliverytime) {
            if ($result->order_type == '1') {
                $time_slot = $result->selectdeliverytime;
            } else {
                $delivery_time_slot = explode('-', @$result->selectdeliverytime);
                $time_slot = date('h:i A', strtotime($delivery_time_slot[0])) . ' : ' . date('h:i A', strtotime($delivery_time_slot[1]));
            }
        }

        if ($result->selectdeliverydate != '') {
            $result->selectdeliverydate = date('d-m-Y', strtotime($result->selectdeliverydate));
        }

        if ($result->order_date != '') {
            $result->order_date = date('d-m-Y h:i A', strtotime($result->order_date));
        }

        if ($result->order_type == 1) {

            $day_name = date('l');
        } else {
            $slot_id = $result->selectdeliveryslot;
            $this->db->select('day_id');
            $this->db->where('id', $slot_id);
            $day_name = $this->db->get('tbl_timeslot')->row()->day_id;
        }

        $result->day_name  = date('l', strtotime($result->selectdeliverydate));
        $result->time_slot = $time_slot;

        if ($result->delivery_boy_id) {
            $delivery_boy = $result->delivery_boy_id;
            $this->db->select('first_name,last_name');
            $this->db->where('id', $delivery_boy);
            $delivery_boy_data = $this->db->get('tbl_delivery_boys')->row();
            $result->delivery_boy_name = $delivery_boy_data->first_name . ' ' . $delivery_boy_data->last_name;
        } else {
            $result->delivery_boy_name = '';
        }

        $product_details = get_product_detail($result->id, $result->user_id, 1);

        if (isset($product_details) && !empty($product_details)) {

            foreach ($product_details as $key_pd => $val_pd) {

                if (($val_pd->product_qty) > ($val_pd->redeem_limit) && $val_pd->redeem_limit != 0) {
                    $act =  number_format($val_pd->act_price * ($val_pd->product_qty - $val_pd->redeem_limit), 2);
                    $dis =   number_format($val_pd->unit_price * $val_pd->redeem_limit, 2);

                    $val_pd->price_for_print =  $act + $dis;
                } else {

                    $val_pd->price_for_print =  number_format($val_pd->unit_price * $val_pd->product_qty, 2);
                }

                if ($val_pd->status == '3') {
                    $substitute = $val_pd->substitute_product;
                    if ($substitute != '0') {
                        $substitute_product_data = get_substitute_product_data($substitute);
                        $val_pd->substitute_product = $substitute_product_data;
                    } else {
                        $val_pd->substitute_product = '';
                    }
                } else {
                    $val_pd->substitute_product = '';
                }
            }

            $refunded_amt1 = 0;
            foreach ($product_details as $key => $normal_product) {
                $normal_product = (array) $normal_product;
                $id = $val_od->product->weight_ids;
                if (($normal_product['status'] == 2 || $normal_product['status'] == 3) && ($normal_product['substitute_product'] == '' || $normal_product['substitute_product'] == 0  || $normal_product['substitute_product'] == null)) {
                    if (($normal_product['product_qty']) > ($normal_product['redeem_limit']) && $normal_product['redeem_limit'] != 0) {
                        $act =  number_format($normal_product['act_price'] * ($normal_product['product_qty'] - $normal_product['redeem_limit']), 2);
                        $dis =   number_format($normal_product['unit_price'] * $normal_product['redeem_limit'], 2);

                        $abc =  $act + $dis;

                        $refunded_amt1 +=   $abc;
                    } else {

                        $refunded_amt1 += $normal_product['unit_price'] * $normal_product['product_qty'];
                    }
                }
            }
            $refunded_amt1 = number_format($refunded_amt1, 2, '.', '');
        }

        $combo_data = array();
        if (isset($result->combo) && $result->combo != '') {
            $combo_name     = explode('/', rtrim($result->combo_name, '/'));
            $combo_image    = explode('/', rtrim($result->combo_image, '/'));
            $combos         = explode('/', rtrim($result->combo, '/'));
            $combo_mrp      = explode('/', rtrim($result->mrp, '/'));
            $combo_price    = explode('/', rtrim($result->combo_price, '/'));
            $combo_qnty     = explode('/', rtrim($result->combo_qnty, '/'));
            foreach ($combos as $key => $combo_items) {

                $combo_item_array   = explode('-', $combo_items);
                $combo_details      = get_product_detail($result->id, $result->user_id, 2, explode(",", $combo_item_array[1]));

                /* Check image existance */
                $img = '';
                if ($combo_image[$key] == '' || ($combo_image[$key] != '' && !FILE_EXISTS('./assets/uploads/combo/' . $combo_image[$key]))) {

                    $img = 'product_placeholder.png';
                } else {
                    $img = $combo_image[$key];
                }

                /*End of Check image existance */

                $combo_data[$key]['image'] = $img;
                $combo_data[$key]['name'] = $combo_name[$key];
                $combo_data[$key]['qnty'] = $combo_qnty[$key];
                $combo_data[$key]['price'] = $combo_price[$key];
                $combo_data[$key]['price_for_print'] = number_format($combo_qnty[$key] * $combo_price[$key], 2);
                $combo_data[$key]['detail'] = $combo_details;
            }
        }

        $final_array = array();
        $order_summery = array();

        $sub_total_amount = $result->total_amount + $result->total_discount + $result->promocode_amount;
        $order_summery['item_subtotal'] = number_format($sub_total_amount, 2, '.', '');

        if ($result->order_type == 2) {

            $order_summery['shipping'] = $result->shipping_charges;
        }

        if ($result->promocode_amount != '' && $result->promocode_amount > 0) {
            $order_summery['promocode'] = '-' . number_format($result->promocode_amount, 2, '.', '');
        }

        if ($result->total_discount != '0') {
            $order_summery['promotion_applied'] = -$result->total_discount;
        }

        if ($result->is_wallet_used == 1) {

            $order_summery['wallet_amount'] = '-' . number_format($result->wallet_used_amount, 2, '.', '');
        }

        $result->payment_check = $result->payment_type;
        if ($result->is_wallet_used == 1 && $result->payment_type != 'WALLET') {
            $result->payment_type = 'WALLET + ' . $result->payment_type;
        }

        if ($result->payment_type != 'WALLET') {
            $order_summery['total_amount'] = number_format(($result->total_amount + $result->shipping_charges + $result->mb_express) - $refunded_amt1, 2, '.', '');
        } else {
            $order_summery['total_amount'] = number_format(($result->total_amount + $result->shipping_charges + $result->mb_express), 2, '.', '');
        }

        if ($result->payment_type != 'WALLET') {

            $order_summery['total_payable_amount']  = number_format(($result->total_amount + $result->shipping_charges + $result->mb_express) - ($result->wallet_used_amount + $refunded_amt1), 2, '.', '');
        } else {

            $order_summery['total_payable_amount']  = number_format(($result->total_amount + $result->shipping_charges + $result->mb_express) - $result->wallet_used_amount, 2, '.', '');
        }

        $order_summery['total_saving'] = number_format($result->total_discount + $result->promocode_amount, 2, '.', '');;

        $result->order_delivered_date = date('d-m-Y h:i A', strtotime($result->order_delivered_date));

        if ($result->payment_type == 'COD'  && $result->is_wallet_used != 1) {

            $result->refunded_amt = 0;
            // $final_array['detail']   = $result->refunded_amt;
        }

        $final_array['detail']   = $result;
        if ($refunded_amt1 != '0.00') {
            $final_array['item_cancelled_amount']    = '-' . $refunded_amt1;
        } else {
            $final_array['item_cancelled_amount']    = '';
        }

        $final_array['order_summery']    = $order_summery;
        $final_array['products']        = $product_details;
        $final_array['combo']            = $combo_data;

        $derived_amount = number_format((($result->total_amount + $result->shipping_charges + $result->mb_express) - ($result->refunded_amt)), 2, '.', '');;

        $final_array['item_subtotal']       = number_format($derived_amount, 2, '.', '');
        $final_array['total_itmes']         = get_total_items($result->id);

        if (!empty($final_array)) {

            return $final_array;
        } else {
            return false;
        }
    }


    public function get_list_for_invoice($id = "", $limit = "", $start = "", $counts = "", $status = "", $store_id = "")
    {
        $this->db->select("`tbl_order`.*");


        if ($limit != "" || $start != "") {
            $this->db->limit($limit, $start);
        }
        if ($id != "") {
            $this->db->where("`tbl_order`.`id`", $id);
        }
        if ($store_id != "") {
            $ppp = explode(",", $store_id);
            $this->db->where_in("`tbl_order`.`store_id`", $ppp);
        }

        if ($status != "") {
            $this->db->where("`tbl_order`.`order_status`", $status);
        }

        $this->db->order_by('`tbl_order`.`id`', 'DESC');
        $query = $this->db->get('tbl_order');
        //echo $this->db->last_query();die;
        $total = $query->num_rows();
        if ($counts != "") {
            return $total;
        } else {
            if ($total > 0) {
                foreach ($query->result() as $row) {
                    $data[] = $row;
                }
                return $data;
            }
        }
        return false;
    }

    public function get_slot_id_by_day_store_id($day, $store_id)
    {
        $this->db->select('id');
        $this->db->where('day_name', $day);
        $this->db->where('store', $store_id);
        $result =  $this->db->get('tbl_timeslot')->row();
        if (!empty($result)) {
            return $result->id;
        } else {
            return false;
        }
    }

    public function rescheduled($data, $id)
    {

        $this->db->where('id', $id);
        return $this->db->update('tbl_order', $data);
    }

    public function get_store_list()
    {

        $this->db->select('*');
        $this->db->where('store_status', '1');
        $result = $this->db->get('tbl_store')->result();
        if ($result) {
            return $result;
        } else {
            return false;
        }
    }

    public function add_store_issue($user_id = '')
    {
        if ($user_id) {
            $uid = $user_id;
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }

        $data['ticket_type']        = '2';
        $data['status']             = '1';
        $data['store']              = $_POST['store'];
        $data['visit_date']         = date('Y-m-d H:i:s', strtotime($_POST['visit_date']));
        $data['description']        = $_POST['description'];
        $data['added_by']           = $uid;
        $data['created_date']       = date('Y-m-d H:i:s');

        $result = $this->db->insert('manage_ticket', $data);
        if ($result) {
            return $result;
        } else {
            return false;
        }
    }

    public function get_store_data($store_id = '', $isTimeslot = FALSE)
    {
        $data = [];
        if (isset($store_id) && !empty($store_id)) {
            $this->db->where('store_id', $store_id);
            $query = $this->db->get('tbl_store');
            // echo lq();die;
            if ($query->num_rows()) {
                $data =  $query->row();
                if (isset($isTimeslot) && $isTimeslot) {
                    $data->timeslot = $this->get_time_slot_new($store_id);
                }
            }
        }
        return $data;
    }

    public function get_time_slot_new($store_id)
    {
        $slots = [];
        $this->db->select("t.*,d.day_name,TIME_FORMAT(t.slot_from_time, '%H:%i') as slot_from_time,TIME_FORMAT(t.slot_to_time, '%H:%i') as slot_to_time,TIME_FORMAT(t.before_closing_time, '%H:%i') as before_closing_time", FALSE);
        $this->db->join('tbl_dayname AS d', 't.day_id = d.id', "LEFT");
        $this->db->where('t.store', $store_id);
        $this->db->where('t.status', 1);
        $this->db->order_by("t.day_id", 'ASC');
        $this->db->order_by("t.slot_from_time", 'ASC');
        $this->db->group_by("t.id", 'ASC');
        $query = $this->db->get('tbl_timeslot AS t');
        if ($query->num_rows()) {
            $slots_data =  $query->result_array();
            // echo $this->db->last_query();die;
            // prd($slots_data);
            $slots_temp_1 = [];
            $slots_temp_2 = [];
            $before_today = [];
            $current_day =  date("N");
            if (isset($slots_data) && !empty($slots_data)) {
                foreach ($slots_data as $slot_key => $slot) {
                    $slots_temp_1[$slot['day_id']][] = $slot;
                }
            }
            if (isset($slots_temp_1) && !empty($slots_temp_1)) {
                foreach ($slots_temp_1 as $day => $slot_data) {
                    if ($day < $current_day) {
                        $before_today[$day] = $slot_data;
                        unset($slots_temp_1[$day]);
                    }
                }
            }
            // pr($before_today);die;
            $slots_temp_2 = $slots_temp_1 + $before_today;
            if (isset($slots_temp_2) && !empty($slots_temp_2)) {
                foreach ($slots_temp_2 as $key => $value) {
                    $slots[changeNumToDate($key)] = $value;
                }
            }

            // prd($slots);
        }
        return $slots;
    }


    public function get_time_slot($day, $store_id)
    {

        if (isset($day) && !empty($day) && isset($store_id) && !empty($store_id)) {
            $this->db->select('*');
            $this->db->where('store', $store_id);
            $this->db->where('day_id', $day);
            $result = $this->db->get('tbl_timeslot')->row();
            //echo $this->db->last_query();die;
            if (!empty($result)) {
                return $result;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public function get_order_address($id)
    {
        $this->db->select('id,customer_first_name,customer_last_name,mobile_number');
        $this->db->where('id', $id);
        $result = $this->db->get('tbl_user_address')->row();
        if (!empty($result)) {
            return $result;
        } else {
            return false;
        }
    }

    public function completion_status($user_id = '')
    {
        $bar = 30;
        if ($user_id != '') {
            $uid = $user_id;
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }

        if ($auth_user !== FALSE) {
            $this->db->select('gender,user_dob,marital_status');
            $total_addr = $this->db->query("SELECT id FROM `tbl_user_address` WHERE user_id = '" . $uid . "' AND (addr_type='home' OR addr_type='office' OR addr_type='other') group by addr_type")->result();
            // echo $this->db->last_query();die;
            // pr($total_addr);die;
            $total_addr = count($total_addr);
            $query = $this->db->get_where($this->table1, array('id' => $uid));
            if ($query->num_rows() > 0) {
                $rec = (array) $query->row();
                if ($rec['gender'] != '') {
                    $bar = $bar + 10;
                }
                if ($rec['user_dob'] != '') {
                    $bar = $bar + 10;
                }
                if ($rec['marital_status'] == 'yes') {
                    $bar = $bar + 20;
                } elseif ($rec['marital_status'] == 'no') {
                    $bar = $bar + 20;
                }

                $total_addr_per = 10 * $total_addr;
                $bar = $bar + $total_addr_per;
            }
            return $bar;
        } else {
            return false;
        }
    }

    public function getUserPreferences($id = null)
    {
        if ($id != null) {
            $uid = $id; //$this->session->userdata('auth_user')['users_id'];
            $this->db->select('categories,order_type,day,time,order_preference_store,order_preference_address');
            $this->db->from('tbl_user_pref');
            $query = $this->db->where('user_id', $uid)->get();
            if ($query->num_rows() > 0) {
                return $query->row();
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public function getUserPreferences_new_api($id = null)
    {
        if ($id != null) {
            $uid = $id; //$this->session->userdata('auth_user')['users_id'];
            $this->db->select('categories,order_type,day,time,order_preference_store,order_preference_address');
            $this->db->from('tbl_user_pref');
            $query = $this->db->where('user_id', $uid)->get()->row();
            if (isset($query) && !empty($query)) {
                if (isset($query->order_type) && $query->order_type == 2 && !empty($query->order_preference_address)) {
                    $customer_addr  = $this->get_address($query->order_preference_address, $uid);
                    if (isset($customer_addr[0]->store_id) && !empty($customer_addr[0]->store_id)) {
                        $customer_addr  = $customer_addr[0];
                        $store          = get_store_name($customer_addr->store_id);
                        if (isset($store) && !empty($store)) {
                            $store  = $store[0];
                            // $user_preference_sess->order_type           = $query->order_type;
                            // $user_preference_sess->categories           = $query->categories;
                            // $user_preference_sess->day                  = $query->day;
                            // $user_preference_sess->time                 = $query->time;
                            // $user_preference_sess->order_type_name      = 'Deliver to address';
                            // $user_preference_sess->store_address        = isset($store->store_address) ? $store->store_address : '';
                            // $user_preference_sess->delivery_store_id    = isset($store->store_id) ? $store->store_id : '';
                            // $user_preference_sess->delivery_store_name  = isset($store->store_name) ? $store->store_name : '';
                            // $user_preference_sess->store_coordinates    = isset($store->coords) ? $store->coords : '';
                            // $user_preference_sess->order_preference_address = $query->order_preference_address;
                            // $user_preference_sess->customer_coordinates = isset($customer_addr->coards) ? $customer_addr->coards : '';
                            $delivery_address                           = $customer_addr->address . ", " . $customer_addr->city . ", " . $customer_addr->land_mark . ", " . $customer_addr->pincode;
                            $query->delivery_address                    = isset($delivery_address) ? $delivery_address : '';
                            $query->delivery_google_address             = isset($customer_addr->google_address) ? $customer_addr->google_address : '';
                            $query->store_distance                      = isset($customer_addr->distance) ? $customer_addr->distance : '';
                            // $user_preference_sess->min_shipping_amount  = $this->query->get_min_shipping($customer_addr->distance, $users_id);
                            // $user_preference_sess->time_slots           = $this->get_active_time_slot($store->store_id);
                        }
                    }
                } elseif (isset($query->order_type) && $query->order_type == 1 && !empty($query->order_preference_store)) {
                    $store = get_store_name($query->order_preference_store);
                    if (isset($store) && !empty($store)) {

                        $store                                      = $store[0];
                        // $user_preference_sess->order_type           = $user_preference->order_type;
                        // $user_preference_sess->categories           = $user_preference->categories;
                        // $user_preference_sess->day                  = $user_preference->day;
                        // $user_preference_sess->time                 = $user_preference->time;
                        // $user_preference_sess->order_type_name      = 'Pick from store';
                        // $user_preference_sess->order_preference_store   = $user_preference->order_preference_store;
                        $query->store_address                       = isset($store->store_address) ? $store->store_address : '';
                        $query->store_coordinates                   = isset($store->coords) ? $store->coords : '';
                        $query->delivery_store_name                 = isset($store->store_name) ? $store->store_name : '';
                        $query->time_slots                          = get_pickup_timeslots($store->store_id);
                        // $this->session->set_userdata('user_preference', $user_preference_sess);
                    }
                }
                return $query;
            }
            return false;
        }
    }

    public function getUserPreferences_api($id = null)
    {
        if ($id != null) {
            $uid = $id; //$this->session->userdata('auth_user')['users_id'];
            $this->db->select('categories,order_type,day,time,order_preference_store,order_preference_address');
            $this->db->from('tbl_user_pref');
            $query = $this->db->where('user_id', $uid)->get()->row();
            if ($query) {
                $query->day = explode(',', rtrim($query->day, ','));
                $query->time = explode(',', rtrim($query->time, ','));
            }
            if ($query) {

                $this->db->select('store_address,coords');
                $this->db->where('store_id', $query->order_preference_store);
                $store_result = $this->db->get('tbl_store')->row();
                $query->store_address = $store_result->store_address;
                $query->store_coordinates = $store_result->coords;

                $this->db->select('address,city,land_mark,pincode,locality,coards,state_id,distance');
                $this->db->where('id', $query->order_preference_address);
                $address_result = $this->db->get('tbl_user_address')->row();
                $query->distance = $address_result->distance;

                if (!empty($address_result)) {
                    if ($address_result->state_id != '') {
                        $this->db->select('name');
                        $this->db->where('id', $address_result->state_id);
                        $state_name = $this->db->get('tbl_states')->row()->name;
                    }

                    if (($state_name != '' && $state_name != 'NULL') || ($address_result->address != '' && $address_result->address != 'NULL')) {

                        $derived_delivery_address = '';
                        if ($address_result->address != '') {
                            $derived_delivery_address .= $address_result->address . ',';
                        }
                        if ($address_result->city != '') {
                            $derived_delivery_address .= $address_result->city . ',';
                        }
                        if ($address_result->land_mark != '') {
                            $derived_delivery_address .= $address_result->land_mark . ',';
                        }
                        if ($address_result->locality != '') {
                            $derived_delivery_address .= $address_result->locality . ',';
                        }
                        if ($state_name != '') {
                            $derived_delivery_address .= $state_name . ',';
                        }
                        if ($address_result->pincode != '0') {
                            $derived_delivery_address .= $address_result->pincode;
                        }
                        $derived_delivery_address = rtrim($derived_delivery_address, ',');

                        $query->delivery_address = $derived_delivery_address;
                    } else {
                        $query->delivery_address = '';
                        /* $address_result->address.', '.$address_result->city.', '.$address_result->land_mark.', '.$address_result->pincode;*/
                        $query->customer_coordinates = $address_result->coards;
                    }

                    $query->customer_coordinates = $address_result->coards;
                } else {
                    $query->delivery_address = '';
                }
            }


            if ($query) {
                return $query;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public function updatePreference($pref = NULL, $user_id = NULL)
    {

        if (isset($pref) && !empty($pref) && isset($user_id) && !empty($user_id)) {
            //pr("yess11");die;
            $this->db->select('id, categories, order_type, day, time');
            $this->db->from($this->table);
            $query = $this->db->where('user_id', $user_id)->get();
            if (isset($pref['order_type']) && $pref['order_type'] == 2) {
                $sql = "UPDATE $this->tableAddress SET `default_addr` = CASE WHEN id = " . $pref['order_preference_address'] . " THEN 1 ELSE 0 END WHERE user_id = $user_id";
                $total_addr = $this->db->query($sql);
            }
            if ($query->num_rows() > 0) {
                $this->db->where('user_id', $user_id);
                $preference = $this->db->update($this->table, $pref);
                if ($preference) {
                    return $pref;
                } else {
                    return false;
                }
            } else {
                $pref['user_id'] = $user_id;
                $preference = $this->db->insert($this->table, $pref);
                // echo $this->db->last_query();die;
                if ($preference) {
                    return $pref;
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
    }

    public function addPreference($pref = null, $user_id = '')
    {
        if ($pref != null) {
            if ($user_id) {
                $uid = $user_id;
            } else {
                $uid = $this->session->userdata('auth_user')['users_id'];
            }

            $this->db->select('id,categories');
            $this->db->from($this->table);
            $query = $this->db->where('user_id', $uid)->get();
            if ($query->num_rows() > 0) {
                $res = $query->result();
                $userNewPref = $pref;
                $userPref = explode(',', $res->categories);
                $pref = array_filter(array_unique(array_merge($userNewPref, $userPref)));
                $data['user_id'] = $uid;
                $data['categories'] = implode(',', $pref);
                $this->db->where('user_id', $uid);
                $preference = $this->db->update($this->table, $data);
                if ($preference) {
                    return $pref;
                } else {
                    return false;
                }
            } else {
                $data['user_id'] = $uid;
                $data['categories'] = implode(',', $pref);
                $preference = $this->db->insert($this->table, $data);
                if ($preference) {
                    return $pref;
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
    }

    public function get_list($user_id = "")
    {
        if ($user_id) {
            $uid = $user_id;
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }

        if ($uid != '') {
            $this->db->select('*');
            $query = $this->db->get_where($this->table1, array('id' => $uid));
            if ($query->num_rows() > 0) {
                foreach ($query->result_array() as $row) {
                    return $row;
                }
            }
            return false;
        } else {
            return false;
        }
    }

    public function get_user_address_list($id = NULL, $user_id = NULL)
    {
        if (isset($user_id) && !empty($user_id)) {
            $uid = $user_id;
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }
        if ($auth_user !== FALSE) {
            $this->db->select("tbl_user_address.*,tbl_states.name as state_name");
            // $this->db->select("*,tbl_product_price.id as pid");
            $this->db->join('`tbl_states`', '`tbl_user_address`.`state_id` = `tbl_states`.`id`', 'left');
            if ($id == null) {
                $this->db->where('tbl_user_address.user_id', $uid);
            } else {
                $this->db->where("tbl_user_address.id", $id);
            }
            $this->db->order_by("addr_type", "ASC");
            $query = $this->db->get("tbl_user_address");
            // echo $this->db->last_query();die;
            if ($query->num_rows() > 0) {
                return $query->result();
            }
            return false;
        } else {
            return false;
        }
    }

    public function get_user_address_list_for_api($id = NULL)
    {

        if (isset($id) && !empty($id)) {
            $this->db->select("tbl_user_address.*,tbl_states.name as state_name");
            $this->db->join('`tbl_states`', '`tbl_user_address`.`state_id` = `tbl_states`.`id`', 'LEFT');
            $this->db->where("tbl_user_address.user_id", $id);
            $this->db->order_by("addr_type", "ASC");
            $query = $this->db->get("tbl_user_address");
            // echo $this->db->last_query();die;
            if ($query->num_rows() > 0) {
                return $query->result();
            }
        }
        return false;
    }

    public function get_user_address_list_for_cart($user_id = null)
    {
        $uid = $user_id;
        if ($auth_user !== FALSE) {
            $this->db->select("tbl_user_address.*,tbl_states.name as state_name");
            // $this->db->select("*,tbl_product_price.id as pid");
            $this->db->join('`tbl_states`', '`tbl_user_address`.`state_id` = `tbl_states`.`id`', 'left');
            if ($id == null) {
                $this->db->where('tbl_user_address.user_id', $uid);
            } else {
                $this->db->where("tbl_user_address.id", $id);
            }
            $this->db->order_by("addr_type", "ASC");
            $query = $this->db->get("tbl_user_address");
            // echo $this->db->last_query();die;
            if ($query->num_rows() > 0) {
                return $query->result();
                //      foreach ($query->result_array() as $row) {
                //          return $row;
                // }
            }
            return false;
        } else {
            return false;
        }
    }

    public function get_address($id = NULL, $user_id = NULL, $isDefault = NULL)
    {
        $data = [];
        if ((isset($user_id) && !empty($user_id)) || (isset($id) && !empty($id))) {
            $this->db->select("addr.*, concat(addr.address,', ',addr.land_mark,', ',addr.locality,', ',addr.city,', ',addr.pincode) as full_address, tbl_states.name as state_name", FALSE);
            $this->db->join('`tbl_states`', '`addr`.`state_id` = `tbl_states`.`id`', 'left');
            if (isset($id) && !empty($id)) {
                $this->db->where('addr.id', $id);
            }
            if (isset($user_id) && !empty($user_id)) {
                $this->db->where('addr.user_id', $user_id);
            }
            if (isset($isDefault) && !empty($isDefault)) {
                $this->db->where('default_addr', '1');
            }
            $this->db->order_by("addr_type", "ASC");
            $query = $this->db->get("tbl_user_address AS addr");
            // echo $this->db->last_query();die;
            $data =  $query->result();
        }

        return $data;
    }


    public function get_user_address_list_for_checkout_api($id = null)
    {
        $uid = $_POST['user_id'];
        if ($uid !== FALSE) {
            $this->db->select("tbl_user_address.*,tbl_states.name as state_name");
            // $this->db->select("*,tbl_product_price.id as pid");
            $this->db->join('`tbl_states`', '`tbl_user_address`.`state_id` = `tbl_states`.`id`', 'left');
            if ($id == null) {
                $this->db->where('tbl_user_address.user_id', $uid);
            } else {
                $this->db->where("tbl_user_address.id", $id);
            }
            $this->db->where('default_addr', '1');
            $this->db->order_by("addr_type", "ASC");
            $query = $this->db->get("tbl_user_address");
            // echo $this->db->last_query();die;
            if ($query->num_rows() > 0) {
                return $query->row();
                //      foreach ($query->result_array() as $row) {
                //          return $row;
                // }
            }
            return false;
        } else {
            return false;
        }
    }


    public function get_wishlist_product_list($product_ids = "", $store_id = "")
    {

        // remove this line when it maintain during login
        if (isset($product_ids) && !empty($product_ids)) {
            $wishlist_ids =  $product_ids;
        } else {
            $wishlist_ids =  $this->session->userdata("wishlist");
        }

        if (!isset($wishlist_ids) || empty($wishlist_ids)) {
            return false;
        }
        /*
        $this->db->select("tbl_product.product_id,tbl_product.product_name, tbl_product.product_image,  tbl_product.product_url,tbl_product.mb_express,tbl_product.product_weight_type,cnt.country_flag, tbl_product_price.id as $product_data[$pd_key]->price_for_print             = $final_price;variant_id,tbl_product_price.product_price,tbl_product_price.product_pec_weight, tbl_product_price.product_s_price, tbl_product_gallery.image");
        $this->db->join('`tbl_product_price`', '`tbl_product`.`product_id` = `tbl_product_price`.`product_id`', 'inner');
        $this->db->join('`tbl_product_gallery`', '`tbl_product_price`.`id` = `tbl_product_gallery`.`variant_id`', 'left');
        $this->db->join('`tbl_country` as cnt', '`tbl_product`.`country_name` = `cnt`.`id`', 'left');*/
        $this->db->select("SQL_CALC_FOUND_ROWS p.product_id,CONVERT(p.product_prices, DECIMAL) as price,p.product_image,p.product_code,p.product_name,p.product_url,p.product_type,p.product_status,p.weight_ids as weight_ids,p.product_prices as product_price,p.product_pec_weights as product_pec_weight,p.product_s_prices as product_s_price,p.category_ids,p.mb_express,p.food_type,p.product_nature,p.product_weight_type,p.country_name,p.featured,pp.special_price_start_date,pp.special_price_end_date,pp.set_quantity,pp.product_s_price as product_s_price1,pp.product_pec_weight as product_pec_weight1,pp.product_price as product_price1,pp.id as vid,pg.image", false);

        $this->db->join('tbl_product_price as pp', 'pp.product_id = p.product_id', 'left');
        $this->db->join('tbl_product_gallery as pg', 'pg.variant_id = pp.id', 'left');
        $this->db->where('p.product_status', '1');
        $this->db->where("p.product_prices!=''");
        ///////inventory unchecked condition starts///////
        // if($store_id==""){
        //     $check_store_id = get_store_id('id');
        // }else{
        //     $check_store_id = $store_id;
        // }
        // if(@$check_store_id!=null && @$check_store_id){
        //     $this->db->join('tbl_inventory as tbl_invt','tbl_invt.product_id = p.product_id','left');
        //     $this->db->where("tbl_invt.store_id",@$check_store_id);

        //     //$this->db->group_by("tbl_invt.product_id");
        // }
        // #########################################
        //     // $this->db->where('pp.unit_status','1');

        // #########################################
        ///////inventory unchecked condition ends///////
        $this->db->where('`pp`.product_price!=', 0);
        // $this->db->where('`pg`.image!=""');

        $this->db->where_in("`pp`.`id`", $wishlist_ids);
        $this->db->where("`pp`.`unit_status`", 1);

        // $this->db->order_by('`tbl_product`.`product_name`', 'ASC');
        $this->db->group_by('`pp`.`product_id`');
        $this->db->order_by('`p`.`product_id`', 'DESC');
        $query = $this->db->get('tbl_product as p');
        // pr($this->db->last_query()); die;
        return $query->result();
    }

    public function get_wishlist_product_list_api($user_id = "", $store_id = "")
    {

        $this->db->select('variant_id');
        $this->db->where('user_id', $user_id);
        $product_ids = $this->db->get('tbl_wishlist')->row()->variant_id;

        $pids =  $product_ids;

        $this->db->select("tbl_product.product_id,tbl_product.country_name,tbl_product.food_type,tbl_product.product_nature,tbl_product.product_weight_type,tbl_product.product_name, tbl_product.product_image,  tbl_product.product_url,tbl_product.mb_express,tbl_product.product_weight_type, tbl_product_price.id as variant_id,tbl_product_price.product_price,tbl_product_price.product_pec_weight, tbl_product_price.product_s_price, tbl_product_gallery.image,tbl_product_price.special_price_start_date,tbl_product_price.special_price_end_date,tbl_product_price.set_quantity,tbl_product_price.product_s_price as product_s_price1,tbl_product.weight_ids");
        $this->db->join('`tbl_product_price`', '`tbl_product`.`product_id` = `tbl_product_price`.`product_id`', 'left');
        $this->db->join('`tbl_product_gallery`', '`tbl_product_price`.`id` = `tbl_product_gallery`.`variant_id`', 'left');
        //$this->db->join('`tbl_country` as cnt', '`tbl_product`.`country_name` = `cnt`.`id`', 'left');

        $this->db->where('`tbl_product_price`.product_price!=', 0);
        $this->db->where('tbl_product.product_status', '1');
        $this->db->where_in("`tbl_product_price`.`id`", explode(",", $pids));
        ///////inventory unchecked condition starts///////
        // if($store_id==""){
        //     $check_store_id = get_store_id('id');
        // }else{
        //     $check_store_id = $store_id;
        // }



        // if(@$check_store_id!=null && @$check_store_id){
        //     $this->db->join('tbl_inventory ','tbl_inventory.tbl_invt.product_id = tbl_product.product_id','left');
        //     $this->db->where("tbl_inventory.store_id",@$check_store_id);

        //     //$this->db->group_by("tbl_invt.product_id");
        // }
        // #########################################
        //     // $this->db->where('pp.unit_status','1');

        // #########################################
        ///////inventory unchecked condition ends///////
        if ($status != "") {
            // $this->db->where("`tbl_product`.`product_status`", $status);
            $this->db->where("`tbl_product_price`.`unit_status`", $status);
        }

        // $this->db->order_by('`tbl_product`.`product_name`', 'ASC');
        $this->db->group_by('`tbl_product_price`.`id`');
        $this->db->order_by('`tbl_product`.`product_id`', 'DESC');

        $query = $this->db->get('tbl_product');
        // pr($this->db->last_query()); die;
        $total = $query->num_rows();

        if ($counts != "") {
            return $total;
        } else {
            if ($total > 0) {
                foreach ($query->result() as $row) {
                    $data[] = $row;
                }
                return $data;
            }
        }

        return false;
    }

    public function get_stateName()
    {
        $this->db->select('*');
        $query = $this->db->get("tbl_states");
        if ($query->num_rows() > 0) {
            return $query->result_array();
        }
        return false;
    }

    public function getUserData($name, $user_id = '')
    {
        if ($user_id) {
            $uid = $user_id;
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }
        $this->db->select($name);
        $query = $this->db->where("id", $uid);
        return $this->db->get("tbl_users")->row()->$name;
    }

    public function save_user_profile($by_otp = null)
    {
        if ($_POST['user_id']) {
            $uid = $_POST['user_id'];
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }
        $data = array(
            'first_name' => $this->security->xss_clean(trim($this->input->post('first_name'))),
            'last_name' => $this->security->xss_clean(trim($this->input->post('last_name'))),
            'email_address' => $this->input->post('email_address'),
            'mobile' => $this->input->post('mobile'),
            'gender' => $this->input->post('gender'),
            'status' => $this->input->post('status'),
            'user_dob' => dateFormatForSQL($this->input->post('user_dob')),
            'gender' => $this->input->post('gender'),
            'marital_status' => $this->input->post('marital_status'),
            'date_modified' => date('Y-m-d H:i:s')
        );
        // if ($by_otp) {
        //     $data['phone_verify'] = $by_otp;
        // }
        // if ($this->input->post('marital_status') == 'yes') {
        //     $data['spouse_name'] = $this->input->post('spouse_name');
        //     $data['anniversary_date'] = dateFormatForSQL($this->input->post('anniversary_date'));
        //     $data['spouse_dob'] = dateFormatForSQL($this->input->post('spouse_dob'));
        //     $data['no_of_kids'] = $this->input->post('no_of_kids');
        //     if (isset($_POST['kids_dob']) && $this->input->post('kids_dob') != '') {
        //         $datestr = '';
        //         $dd = $this->input->post('kids_dob');
        //         foreach ($dd as $key => $value) {
        //             $datestr .= dateFormatForSQL($dd[$key]) . ",";
        //         }
        //         $data['kids_dob'] = rtrim($datestr, ",");
        //     }
        //     if (isset($_POST['kids_name']) && $this->input->post('kids_name') != '') {
        //         $datestr = '';
        //         $dd = $this->input->post('kids_name');
        //         foreach ($dd as $key => $value) {
        //             $datestr .= ($dd[$key]) . ",";
        //         }
        //         $data['kids_name'] = rtrim($datestr, ",");
        //     }
        // } else {
        //     $data['anniversary_date'] = '';
        //     $data['spouse_dob'] = '';
        //     $data['no_of_kids'] = '';
        //     $data['kids_dob'] = '';
        //     $data['kids_name'] = '';
        // }
        // if ($by_otp) {
        //     $_SESSION['auth_user']['mobile'] = @$this->input->post('mobile');
        // }


        $this->db->where('id', $uid);
        return $this->db->update($this->table1, $data);
    }

    public function save_user_profile_api()
    {

        if ($_POST['user_id']) {
            $uid = $_POST['user_id'];
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }
        if (isset($_POST['status']) && !empty($_POST['status']) && $_POST['status'] != '') {
            $status = $_POST['status'];
        } else {
            $status = '1';
        }

        $data = array(
            'first_name' => $this->security->xss_clean(trim($this->input->post('first_name'))),
            'last_name' => $this->security->xss_clean(trim($this->input->post('last_name'))),
            'email_address' => $this->input->post('email_address'),
            'mobile' => $this->input->post('mobile'),
            'gender' => $this->input->post('gender'),
            'status' => $status,
            'user_dob' => date('Y-m-d H:i:s', strtotime($this->input->post('user_dob'))),
            'gender' => $this->input->post('gender'),
            'marital_status' => $this->input->post('marital_status'),
            'date_modified' => date('Y-m-d H:i:s')
        );

        if ($this->input->post('marital_status') == 'yes') {
            $data['anniversary_date'] = date('Y-m-d H:i:s', strtotime($this->input->post('anniversary_date')));
            $data['spouse_dob'] = date('Y-m-d H:i:s', strtotime($this->input->post('spouse_dob')));
            $data['no_of_kids'] = $this->input->post('no_of_kids');
            if (isset($_POST['kids_dob_new']) && $this->input->post('kids_dob_new') != '') {
                $datestr = '';
                $kids_dob_array = explode(',', rtrim($this->input->post('kids_dob_new'), ','));
                $dd = $kids_dob_array;
                foreach ($dd as $key => $value) {
                    $datestr .= date('Y-m-d H:i:s', strtotime($dd[$key])) . ",";
                }
                $data['kids_dob'] = rtrim($datestr, ",");
            }

            if (isset($_POST['kids_name_new']) && $this->input->post('kids_name_new') != '') {
                //  $datestr='';
                $dd = $this->input->post('kids_name_new');
                /*  foreach ($dd as $key => $value) {
                    $datestr.= ($dd[$key]).",";
                } */
                $data['kids_name'] = rtrim($dd, ",");
            }
        } else {
            $data['anniversary_date'] = '';
            $data['spouse_dob'] = '';
            $data['no_of_kids'] = '';
            $data['kids_dob'] = '';
            $data['kids_name'] = '';
        }


        //pr($data);die;
        $this->db->where('id', $uid);
        return $this->db->update($this->table1, $data);
    }

    public function save_address()
    {

        // pr($this->input->post('validate_address'));die;
        // pr($_POST);die;
        if (isset($_POST['user_id']) && !empty($_POST['user_id'])) {
            $uid = $_POST['user_id'];
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }
        $store_id = $this->input->post('store_id');
        $store_data = get_store_name($store_id);
        if (empty($store_data) && count($store_data) == 0) {
            $this->session->set_flashdata("error", "Store Not found");
            return false;
        }

        $store_coards   = $store_data[0]->coords;
        // $store_coards    = $store_data[0]->google_coordinate;
        $user_coards    = $this->input->post('coards');
        if (isset($store_coards) && !empty($store_coards) && isset($user_coards) && !empty($user_coards)) {
            /**get distance - store to user address***/
            // $total_distance = __get_distance($store_coards, $user_coards);
            $total_distance = 0;
            $lat1   = explode(",", $store_coards)[0];
            $long1  = explode(",", $store_coards)[1];
            $lat2   = explode(",", $user_coards)[0];
            $long2  = explode(",", $user_coards)[1];
            $dist   = GetDrivingDistance_h($lat2, $long2, $lat1, $long1);
            // pr($dist);die;
            if (isset($dist) && isset($dist['distance'])) {
                $total_distance = $dist['distance'];
            } else {
                $this->session->set_flashdata("error", "Your address distance could not find. Please try again.");
                return false;
            }
        } else {
            $this->session->set_flashdata("error", "Store or user coards not found.");
            return false;
        }
        if ($this->input->post('address_id') == '') {
            $data = array(
                'first_name' => $this->security->xss_clean(trim($this->input->post('first_name'))),
                'mobile_number' => $this->security->xss_clean(trim(@$this->input->post('mobile_number'))),
                'address' => $this->input->post('address'),
                'locality' => $this->input->post('locality'),
                'land_mark' => $this->input->post('land_mark'),
                'pincode' => ($this->input->post('pincode')),
                'state_id' => $this->input->post('state_id'),
                'city' => ($this->input->post('city')),
                'addr_type' => ($this->input->post('addr_type')),
                'google_address' => $this->security->xss_clean(trim($this->input->post('location'))),
                'user_id' => $uid,
                'coards' => ($this->input->post('coards')),
                'latitude' => ($this->input->post('latitude')),
                'longitude' => ($this->input->post('longitude')),
                'store_id' => $this->input->post('store_id'),
                'distance' => $total_distance,
                'status' => 1,
                'date' => date('Y-m-d H:i:s')
            );

            return $this->db->insert('tbl_user_address', $data);
        } else {
            $id = $this->input->post('address_id');
            $data = array(
                'first_name' => $this->security->xss_clean(trim($this->input->post('first_name'))),
                'mobile_number' => $this->security->xss_clean(trim($this->input->post('mobile_number'))),
                'address' => $this->input->post('address'),
                'locality' => $this->input->post('locality'),
                'land_mark' => $this->input->post('land_mark'),
                'pincode' => ($this->input->post('pincode')),
                'state_id' => $this->input->post('state_id'),
                'google_address' => $this->security->xss_clean(trim($this->input->post('location'))),
                'city' => ($this->input->post('city')),
                'coards' => ($this->input->post('coards')),
                'latitude' => ($this->input->post('latitude')),
                'longitude' => ($this->input->post('longitude')),
                'store_id' => $this->input->post('store_id'),
                'distance' => $total_distance,
                'status' => 1,
                'modified_date' => date('Y-m-d H:i:s')
            );

            //  pr($data);die;
            // $this->db->where('id', $uid);
            $this->db->where('id', $id);
            $st = $this->db->update('tbl_user_address', $data);
            if ($st) {
                $user_preference = $this->session->userdata('user_preference');
                if (!empty($user_preference)) {
                    if ($user_preference->order_type == 2 && $user_preference->order_preference_address == $id) {
                        $user_preference->order_preference_store     = $store_id;
                        $user_preference->store_distance             = $total_distance;
                        $user_preference->store_coordinates         = $store_coards;
                        $user_preference->customer_coordinates         = $user_coards;
                        $this->session->set_userdata('user_preference', $user_preference);
                    }
                }
            }
            return $st;
        }
    }

    public function save_address_app($store_id, $user_id)
    {

        $store_data = get_store_name($store_id);
        if (empty($store_data) && count($store_data) == 0) {
            return ['error' => 'Store Not found'];
        }
        $total_distance = 0;
        $store_coards     = $store_data[0]->coords;
        // $store_coards 	= @$store_data[0]->google_coordinate;
        $user_coards     = @$this->input->post('coards');

        if (isset($store_coards) && !empty($store_coards) && isset($user_coards) && !empty($user_coards)) {
            /**get distance - store to user address***/
            // $total_distance = __get_distance($store_coards, $user_coards);

            $lat1 = explode(",", $store_coards)[0];
            $long1 = explode(",", $store_coards)[1];
            $lat2 = explode(",", $user_coards)[0];
            $long2 = explode(",", $user_coards)[1];
            $dist = GetDrivingDistance_h($lat2, $long2, $lat1, $long1);
            if (isset($dist) && isset($dist['distance'])) {
                $total_distance = $dist['distance'];
            } else {
                return ['error' => 'Your address distance could not find. Please try again'];
            }
        } else {
            return ['error' => 'Store or user coards not found'];
        }
        // pr($total_distance);die;
        if ($this->input->post('address_id') == '') {
            $data = array(
                'first_name' => $this->security->xss_clean(trim($this->input->post('first_name'))),
                'mobile_number' => trim(@$this->input->post('mobile_number')),
                'address' => $this->input->post('address'),
                'locality' => $this->input->post('locality'),
                'land_mark' => $this->input->post('land_mark'),
                'pincode' => ($this->input->post('pincode')),
                'state_id' => $this->input->post('state_id'),
                'city' => ($this->input->post('city')),
                'addr_type' => ($this->input->post('addr_type')),
                'google_address' => @$this->input->post('google_address'),
                'user_id' => $user_id,
                'coards' => ($this->input->post('coards')),
                'store_id' => $store_id,
                'distance' => $total_distance,
                'status' => 1,
                'date' => date('Y-m-d H:i:s')
            );
            return $this->db->insert('tbl_user_address', $data);
        } else {
            $address_id = $this->input->post('address_id');
            $data = array(
                'first_name' => $this->security->xss_clean(trim($this->input->post('first_name'))),
                'mobile_number' => @trim($this->input->post('mobile_number')),
                'address' => $this->input->post('address'),
                'locality' => $this->input->post('locality'),
                'land_mark' => $this->input->post('land_mark'),
                'pincode' => ($this->input->post('pincode')),
                'state_id' => $this->input->post('state_id'),
                'google_address' => @$this->input->post('google_address'),
                'city' => ($this->input->post('city')),
                'coards' => ($this->input->post('coards')),
                'store_id' => $store_id,
                'distance' => $total_distance,
                'status' => 1,
                'modified_date' => date('Y-m-d H:i:s')
            );


            $this->db->where('id', $address_id);
            $status = $this->db->update('tbl_user_address', $data);
            if ($status) {
                $this->db->where('order_type', 2);
                $this->db->where('user_id', $user_id);
                $this->db->where('order_preference_address', $address_id);
                $this->db->update('tbl_user_pref', ['order_preference_store' => $store_id]);
            }
            return $status;
        }
    }

    public function delete_address($id, $user_id)
    {
        //pr($id);die;
        $this->db->where('id', $id);
        $this->db->where('user_id', $user_id);
        return $this->db->delete('tbl_user_address');
    }

    public function change_user_Password($password_flag, $oauth_provider)
    {
        $uid = $this->session->userdata('auth_user')['users_id'];

        $old_password = md5($this->input->post('old_password'));
        $this->db->where('id', $uid);
        if ($password_flag == 0 && $oauth_provider == 0) {
            $this->db->where('password', $old_password);
        }
        $query = $this->db->get('tbl_users');

        if ($query->num_rows() > 0) {

            $existing_password = $query->row()->password;
            $new_change_password = md5($this->input->post('new_password'));

            if ($existing_password == $new_change_password) {
                $this->session->set_flashdata("error", "New password already exist!");
                return false;
            } else {
                $data = array(
                    'status' => 1,
                    'password' => md5($this->input->post('new_password')),
                    'date_modified' => date('Y-m-d H:i:s')
                );

                $this->db->where('id', $uid);
                return $this->db->update($this->table1, $data);
            }
        } else {
            $this->session->set_flashdata("error", "Your current password does not match!");
            return false;
        }
    }

    public function change_user_Password_api()
    {
        $uid = $_POST['user_id'];
        $type = $_POST['type'];
        $old_password = sha1($this->input->post('old_password'));
        $this->db->where('id', $uid);
        $this->db->where('password', $old_password);
        $query = $this->db->get('tbl_users');
        if ($type == '0') {
            if ($_POST['new_password'] != $_POST['confirm_password']) {
                $data['status'] = '0';
                $data['message'] = 'New password & confirm password does not match.!';
                return $data;
            } else {
                $data = array(
                    'status' => 1,
                    'password' => sha1($this->input->post('new_password')),
                    'date_modified' => date('Y-m-d H:i:s')
                );

                $this->db->where('id', $uid);
                $responce = $this->db->update($this->table1, $data);
                if ($responce) {
                    $data['status'] = '1';
                    $data['message'] = 'Your password successfully changed!';
                    return $data;
                } else {
                    $data['status'] = '0';
                    $data['message'] = 'Something Went Wrong!';
                    return $data;
                }
            }
        } else {
            if ($query->num_rows() > 0) {
                $existing_password = $query->row()->password;
                if (isset($_POST['new_password']) && !empty($_POST['new_password'])) {

                    $new_change_password = sha1($this->input->post('new_password'));
                    if ($existing_password == $new_change_password) {
                        $data['status'] = '0';
                        $data['message'] = 'New password already exist!';
                        return $data;
                    } else if ($_POST['new_password'] != $_POST['confirm_password']) {
                        $data['status'] = '0';
                        $data['message'] = 'New password & confirm password does not match.!';
                        return $data;
                    } else {
                        $data = array(
                            'status' => 1,
                            'password' => sha1($this->input->post('new_password')),
                            'date_modified' => date('Y-m-d H:i:s')
                        );
                        $this->db->where('id', $uid);
                        $responce = $this->db->update($this->table1, $data);
                        if ($responce) {
                            $data['status'] = '1';
                            $data['message'] = 'Your password successfully changed!';
                            return $data;
                        } else {
                            $data['status'] = '0';
                            $data['message'] = 'Something Went Wrong!';
                            return $data;
                        }
                    }
                } else {
                    $data['status'] = '0';
                    $data['message'] = 'Please enter new password!';
                    return $data;
                }
            } else {
                $data['status'] = '0';
                $data['message'] = 'Your Current password does not match!';
                return $data;
            }
        }
    }

    function update_wishlist($data)
    {
        if (isset($data) && !empty($data) && is_array($data)) {
            $this->db->select('user_id');
            $this->db->where('user_id', $data['user_id']);
            $result = $this->db->get('tbl_wishlist');
            if ($result->num_rows() > 0) {
                $this->db->where('user_id', $data['user_id']);
                $wishlist = $this->db->update('tbl_wishlist', $data);
                if ($wishlist) {
                    return true;
                } else {
                    return false;
                }
            } else {
                $wishlist = $this->db->insert("tbl_wishlist", $data);
                if ($wishlist) {
                    return true;
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
    }

    function updateStore($store_data)
    {
        $checkLocation = getUserLocationfromDB($store_data['uid']);
        if ($checkLocation != '' && count($checkLocation) > 0) {
            $this->db->where('uid', $store_data['uid']);
            $this->db->update('tbl_userlocations', $store_data);
            $this->session->set_userdata('storedate_user', $store_data);
        } else {
            $this->db->insert('tbl_userlocations', $store_data);
            $this->session->set_userdata('storedate_user', $store_data);
        }
    }

    function get_referal_code($user_id = '')
    {
        if ($user_id) {
            $user_id = $user_id;
        } else {
            $user_id = @$_SESSION['auth_user']['users_id'];
        }

        $refer_array = array();

        $this->db->select('refer_code');
        $this->db->where('status', '1');
        $this->db->where('id', $user_id);
        $result = $this->db->get('tbl_users')->result();
        if (!empty($result)) {
            foreach ($result as $key_r => $val_r) {
                if ($val_r->refer_code != "") {
                    $refer_array = $val_r->refer_code;
                } else {
                    $str = 'ORD' . ID_encode($user_id);
                    //$str = generateRandomString(4);
                    $this->db->set('refer_code', $str);
                    $this->db->where('id', $user_id);
                    $this->db->update('tbl_users');
                    $refer_array = $str;
                }
            }
        }
        return $refer_array;
    }

    function generateRandomString($length = 6)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    function get_referal_value()
    {
        $refer_array = array();
        $this->db->select('loyality_point');
        $this->db->where('name', 'On Referral');
        $result = $this->db->get('loyality_point')->result();
        if (!empty($result)) {
            foreach ($result as $key_r => $val_r) {
                if ($val_r->loyality_point != "") {
                    $refer_array = $val_r->loyality_point;
                }
            }
        }
        return $refer_array;
    }

    public function get_user_delivered_orders($user_id = "", $my_loyalty_order_list = '')
    {
        $this->db->select('id as id,total_amount,order_number,order_date');
        if (!$my_loyalty_order_list == '') {
            if (is_array($my_loyalty_order_list) && count($my_loyalty_order_list > 0)) {
                $this->db->where_not_in('id', $my_loyalty_order_list);
            } else {
                $this->db->where_not_in('id', $my_loyalty_order_list);
            }
        }
        $this->db->where('user_id', $user_id);
        // $this->db->where('order_status','Delivered');
        $this->db->where(" ( order_status= 'Delivered' OR order_status='Picked up by Customer') ");
        //$this->db->limit(10);
        $this->db->order_by('id', 'desc');
        $result = $this->db->get('tbl_order')->result();

        if (!empty($result)) {
            return $result;
        } else {
            return false;
        }
    }

    public function get_loyalty_list()
    {
        $this->db->where('name', 'Order');
        $result = $this->db->get('loyality_point')->result();
        return $result;
    }

    public function get_my_loyalty()
    {
        $this->db->select('order_id');
        $this->db->where('loyalty_type', 'order');
        return $this->db->get('tbl_user_loyalty')->result_array();
    }


    /*public function get_loyaltyPoints($range_from,$range_to,$type=''){
        $this->db->select('id,loyality_point');
        $this->db->where('range_from',$range_from);
        $this->db->where('range_to',$range_to);
        if($type!='')
        {
            $this->db->where('name',$type);
        }
        $this->db->from('loyality_point');
        $result = $this->db->get()->row();
        return $result;
    }*/

    public function update_userLoyalty($loyalty_data)
    {

        return $this->db->insert_batch('tbl_user_loyalty', $loyalty_data);
    }

    public function remove_userLoyalty()
    {
        $uid = $this->session->userdata('auth_user')['users_id'];
        $this->db->where('user_id', $uid);
        return $this->db->delete('tbl_user_loyalty');
    }

    public function save_loyalty($total_loyalty, $type)
    {
        $data = array();
        $uid = $this->session->userdata('auth_user')['users_id'];
        $data['user_id']    =   $uid;
        //$data['loyalty_id']   =   $loyalty_id;
        $data['total_loyalty_points']   =   $total_loyalty;
        $data['loyalty_type']   =   $type;
        //$data['loyalty_rupees']   =   $loyalty_rupees;
        $save_loyalty   =   $this->db->insert('user_loyalty', $data);

        if ($save_loyalty) {
            return true;
        } else {
            return false;
        }
    }

    public function get_rupeesRange()
    {
        $this->db->select('loyalty_point,rupees,redeem_limit');
        $data = $this->db->get('tbl_loyalty_conversion')->row();
        return $data;
    }

    public function get_LoyaltyRupees($type = '', $user_id = '')
    {
        if ($user_id) {
            $uid = $user_id;
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }

        if ($type == 'sum') {
            $this->db->select('SUM(tbl_user_loyalty.total_loyalty_points) as total_loyalty_points, SUM(tbl_user_loyalty.used_loyality) as used_loyality');
        } else {
            $this->db->select('tbl_user_loyalty.*,o.order_number');
        }
        $this->db->join("tbl_order as o", "o.id=tbl_user_loyalty.order_id", "left");
        $this->db->where('tbl_user_loyalty.user_id', $uid);
        $this->db->where('referral_status', 1);
        $this->db->order_by('tbl_user_loyalty.id', 'DESC');

        $data = $this->db->get('tbl_user_loyalty')->result();

        if (!empty($data)) {
            foreach ($data as $key_da => $val_da) {
                $val_da->total_loyalty_points = number_format($val_da->total_loyalty_points, 2, '.', '');
                $val_da->loyalty_rupees = number_format($val_da->loyalty_rupees, 2, '.', '');
            }
        }
        return $data;
    }


    public function get_referal_point($type = '', $user_id = '')
    {
        if ($user_id) {
            $uid = $user_id;
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }

        if ($type == 'sum') {
            $this->db->select('SUM(tbl_user_loyalty.total_loyalty_points) as total_loyalty_points, SUM(tbl_user_loyalty.used_loyality) as used_loyality');
        } else {
            $this->db->select('tbl_user_loyalty.*,o.order_number');
        }
        $this->db->join("tbl_order as o", "o.id=tbl_user_loyalty.order_id", "left");
        $this->db->where('tbl_user_loyalty.user_id', $uid);
        $this->db->where('referral_status', 2);
        $this->db->order_by('tbl_user_loyalty.id', 'DESC');

        $data = $this->db->get('tbl_user_loyalty')->result();
        if (!empty($data)) {
            foreach ($data as $key_da => $val_da) {
                $val_da->total_loyalty_points = number_format($val_da->total_loyalty_points, 2, '.', '');
                $val_da->loyalty_rupees = number_format($val_da->loyalty_rupees, 2, '.', '');
            }
        }
        return $data;
    }

    public function get_Loyalty_offers()
    {
        $array_con = array('Order', 'On Referral');
        $this->db->select('*');
        $this->db->where_in('name', $array_con);
        $result = $this->db->get('loyality_point')->result();
        if (!empty($result)) {
            return $result;
        } else {
            return false;
        }
    }

    public function get_otherLoyaltyPoints($user_id = "")
    {
        if ($this->session->userdata('auth_user')['users_id']) {

            $uid = $this->session->userdata('auth_user')['users_id'];
        } else {
            $uid = $user_id;
        }

        $this->db->select('total_loyalty_points');
        $this->db->where('loyalty_type!=', 'order');
        $this->db->where('user_id', $uid);
        $data = $this->db->get('tbl_user_loyalty')->row()->total_loyalty_points;
        return $data;
    }

    public function user_purchaseLoyaltyPoints($user_id = "")
    {
        if ($this->session->userdata('auth_user')['users_id']) {

            $uid = $this->session->userdata('auth_user')['users_id'];
        } else {
            $uid = $user_id;
        }
        $this->db->select('total_loyalty_points');
        $this->db->where('user_id', $uid);
        $this->db->where('loyalty_type', 'order');
        $data = $this->db->get('tbl_user_loyalty')->row()->total_loyalty_points;

        return $data;
    }

    public function get_my_wallet($user_id = "")
    {
        if ($user_id) {
            $uid = $user_id;
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }
        $this->db->where('id', $uid);
        return $this->db->get('tbl_users')->row_array();
    }

    public function get_my_wallet_api($user_id = "")
    {
        if ($user_id) {
            $uid = $user_id;
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }
        $this->db->where('id', $uid);
        $result = $this->db->get('tbl_users')->row_array();


        if (!empty($result)) {
            $total = $result['wallet_total_amount'] - $result['wallet_used_amount'];
            $result['wallet_total_amount'] = number_format($total, 2, '.', '');
            return $result;
        } else {
            return false;
        }
    }


    public function check_is_address($user_id)
    {
        $this->db->select('*');
        $this->db->where('user_id', $user_id);
        $result = $this->db->get('tbl_user_address')->result();
        if ($result) {
            return count($result);
        } else {
            return false;
        }
    }

    public function get_wallet_transaction($user_id = "")
    {
        if ($user_id) {
            $uid = $user_id;
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }
        $this->db->select('tbl_wallet_transaction.*,TBLO.order_number');
        $this->db->join('tbl_order as TBLO', 'TBLO.id = tbl_wallet_transaction.order_id', 'left');
        $this->db->where('tbl_wallet_transaction.user_id', $uid);
        $this->db->limit('150');
        $this->db->order_by('id', 'desc');
        return $this->db->get('tbl_wallet_transaction')->result_array();
    }

    public function get_wallet_transaction_pagination($user_id = '', $id = '', $limit = '', $start = '')
    {

        $this->db->select('SQL_CALC_FOUND_ROWS wt.*,TBLO.order_number', FALSE);
        $this->db->join('tbl_order as TBLO', 'TBLO.id = wt.order_id', 'left');
        if ($user_id != '') {
            $this->db->where('wt.user_id', $user_id);
        }
        if ($id != '') {
            $this->db->where('wt.id', $id);
        }
        if ($limit != '' && $start != '') {
            $this->db->limit($limit, $start);
        } else {
            $this->db->limit($limit);
        }
        $this->db->order_by('wt.id', 'desc');
        $query = $this->db->get('tbl_wallet_transaction as wt');
        //echo $this->db->last_query();die;
        $num_rows = $query->num_rows();
        if ($num_rows > 0) {
            $result = $query->result_array();
            $rs_data['status']          = "success";
            $rs_data['search_records']  = $num_rows;
            $rs_data['total_records']   = $this->db->query('SELECT FOUND_ROWS() AS `count`')->row()->count;
            $rs_data['result']          = $result;
        } else {
            $rs_data['status']             = "error";
            $rs_data['result']             = '';
            $rs_data['total_records']    = 0;
            $rs_data['search_records']      = 0;
        }
        //pr($rs_data);die;
        return $rs_data;
    }

    public function update_wallet_pin($pin, $user_id = '')
    {
        if ($user_id) {
            $uid = $user_id;
        } else {
            $uid = $this->session->userdata('auth_user')['users_id'];
        }
        $this->db->where('id', $uid);
        $this->db->set('wallet_pin', $pin);
        return $this->db->update('tbl_users');
    }

    public function add_money($data)
    {
        // $this->db->insert('tbl_wallet_transaction',$data);
        // $insert_id = $this->db->insert_id();
        $user_id = $data['user_id'];
        // // $this->db->where('id',$user_id);
        // // $this->db->set('wallet_total_amount','wallet_total_amount+'.$data['amount']);
        // // $this->db->update('tbl_users');

        // $sql = 'UPDATE tbl_users set wallet_total_amount=wallet_total_amount+'.$data['amount'].' WHERE id = '.$user_id;
        // $this->db->query($sql);
        // return $insert_id;
        $this->db->where('user_id', $user_id);
        $this->db->where('invoice_id', $data['invoice_id']);
        $this->db->update('tbl_wallet_transaction', $data);
        if (isset($data['txn_status']) && $data['txn_status'] === 'TXN_SUCCESS') {
            $sql = 'UPDATE tbl_users set wallet_total_amount=wallet_total_amount+' . $data['amount'] . ' WHERE id = ' . $user_id;
            $this->db->query($sql);
        }
        // echo $this->db->last_query();die;
    }

    public function add_money_new($data = NULL)
    {
        if (isset($data['user_id']) && !empty($data['user_id'])) {
            // $this->db->insert('tbl_wallet_transaction',$data);
            // $insert_id = $this->db->insert_id();
            // $user_id = $data['user_id'];
            // // $this->db->where('id',$user_id);
            // // $this->db->set('wallet_total_amount','wallet_total_amount+'.$data['amount']);
            // // $this->db->update('tbl_users');

            // $sql = 'UPDATE tbl_users set wallet_total_amount=wallet_total_amount+'.$data['amount'].' WHERE id = '.$user_id;
            // $this->db->query($sql);
            // return $insert_id;
            $this->db->where('user_id', $data['user_id']);
            $this->db->where('invoice_id', $data['invoice_id']);
            $this->db->update('tbl_wallet_transaction', $data);
            if ($this->db->affected_rows()) {
                if (isset($data['txn_status']) && ($data['txn_status'] === 'TXN_SUCCESS' || $data['txn_status'] === 'COMPLETED')) {
                    $sql = 'UPDATE tbl_users set wallet_total_amount=wallet_total_amount+' . $data['amount'] . ' WHERE id = ' . $data['user_id'];
                    $this->db->query($sql);
                }
            }
            // echo $this->db->last_query();die;
        }
    }


    public function get_weight_data_varient($weight_id)
    {
        $this->db->select('*');
        $this->db->where('id', $weight_id);
        $this->db->where('unit_status', '1');
        $result = $this->db->get('tbl_product_price')->row();
        if ($result) {
            return $result;
        } else {
            return false;
        }
    }


    public function get_wishlist_ids($uid)
    {
        $this->db->select('variant_id');
        $this->db->where('user_id', $uid);
        $result = $this->db->get('tbl_wishlist')->row();
        if ($result->variant_id) {
            return $result->variant_id;
        } else {
            return false;
        }
    }


    public function get_inventory($store_id = '', $product_id = '', $varient_id = '')
    {
        /*
        Date: 23/07/2019
        Author: Bhoopesh Kumar
        About: This function is used for getting inventory of product.
        Required Parameter : store_id,product_id,varient_id.
        */
        $this->db->select('*');
        $this->db->where('store_id', $store_id);
        $this->db->where('product_id', $product_id);
        if ($varient_id != '') {
            $this->db->where('priceid', $varient_id);
        }
        $result = $this->db->get('tbl_inventory')->result();
        if ($result) {
            return $result;
        } else {
            return false;
        }
    }


    public function get_wallet_balance($user_id)
    {
        /*
        Date: 29/07/2019
        Author: Bhoopesh Kumar
        About: This function is used for getting wallet information.
        Required Parameter : user_id.
        */
        $this->db->select('wallet_total_amount,wallet_used_amount,wallet_pin');
        $this->db->where('id', $user_id);
        $result = $this->db->get('tbl_users')->row();
        if ($result) {
            return $result;
        } else {
            return false;
        }
    }

    public function get_smart_way_data($id)
    {
        $this->db->select("*");
        $this->db->where('id', $id);
        $result = $this->db->get('mb_smart_way')->row();
        if (!empty($result)) {
            return $result;
        } else {
            return false;
        }
    }

    private function SendEmailTo($subject = null, $body = null, $email = null)
    {
        $this->load->library('Sendmail');
        $config['protocol']     = 'smtp';
        $config['smtp_host']    = 'ssl://smtp.gmail.com';
        $config['smtp_port']    = '465';
        $config['smtp_timeout'] = '7';
        $config['smtp_user']    = '';
        $config['smtp_pass']    = '';
        $config['charset']      = 'utf-8';
        $config['newline']      = "\r\n";
        $config['mailtype']     = 'text'; // or html
        $config['validation']   = TRUE; // bool whether to validate email or not      
        $this->email->initialize($config);
        $this->email->from($this->dbsettings->REGISTRATION_MAIL, 'SlickDealsNews.CO.IN');
        $this->email->to($email);
        $this->email->subject($subject);
        $this->email->set_mailtype("html");
        $this->email->message($body);
        //pr($this->email->message($body));die;
        //pr($this->email->send());die;
        return $this->email->send();
    }

    ////////////////////////////////////////////////////////////


    // public function new_notification($user_id, $count=0, $limit='', $start='')
    // {
    //     if ($user_id)
    //     {
    //         if($count==1)
    //         {
    //             $this->db->select("count(id) as total_row");
    //             $query = $this->db->get_where('tbl_user_notification', array('user_id' => $user_id,'status'=>0));
    //         	return $query->row()->total_row;
    //         }
    //         else
    //         {
    //         	$this->db->select('SQL_CALC_FOUND_ROWS link,message,date',FALSE);
    // 	        if($limit!='' && $start!='')
    // 	        {
    // 	        	$this->db->limit($limit, $start);
    // 	        }
    // 	        else
    // 	        {
    // 	        	$this->db->limit($limit);
    // 	        }

    //         	$this->db->where('user_id',$user_id);
    //         	$this->db->order_by('id','DESC');
    //         	$query = $this->db->get('tbl_user_notification');
    //         	$num_rows = $query->num_rows();

    // 	        if($num_rows>0){
    // 	          	$rs_data['result']  		= $query->result();
    // 	            $rs_data['status']          = "success";
    // 	            $rs_data['search_records']  = $num_rows;
    // 	            $rs_data['total_records']   = $this->db->query('SELECT FOUND_ROWS() AS `count`')->row()->count;
    // 	       	}
    // 	       	else{
    // 	           $rs_data['status'] 	= "error";
    // 	           $rs_data['result'] 	= '';
    // 	           $rs_data['total_records']    = 0;
    // 	           $rs_data['search_records']  = 0;
    // 	        }

    //         	$this->db->where('user_id',$user_id);
    //         	$this->db->set('status',1);
    //         	$this->db->update('tbl_user_notification');
    //         	if($rs_data['total_records']>0){
    // 	            return $rs_data;
    // 	        }else{
    // 	            return false;
    // 	        }
    //         }
    //     }
    //     else
    //     {
    //         return false;
    //     }
    // }


    public function new_notification($user_id, $count = 0, $limit = '', $start = '')
    {
        if ($user_id) {
            if ($count == 1) {
                // $this->db->select("count(id) as total_row");
                // $query = $this->db->get_where('tbl_user_notification', array('user_id' => $user_id,'status'=>0));
                // return $query->row()->total_row;
                $query_total_row = $this->db->select("count(id) as total_row");
                $whr = "((user_id = $user_id AND user_type= 'Selected') OR (user_type= 'All' AND FIND_IN_SET( '$user_id' , user_viewed_status) =0))";
                $query_total_row = $this->db->where("store_id=", null);
                // $query_total_row = $this->db->where('ios_user_type',null);
                // $query_total_row = $this->db->where('android_user_type',null);
                $query_total_row = $this->db->where($whr);
                $query_total_row = $this->db->where('status', '0');
                $query_total_row = $this->db->order_by('id', 'DESC');
                $query_total_row = $this->db->get('tbl_user_notification')->row()->total_row;
                // echo $this->db->last_query().'<br>';

                //pr($query_total_row);die;
                return $query_total_row;
            } else {
                $this->db->select('SQL_CALC_FOUND_ROWS link,message,date', FALSE);
                if ($limit != '' && $start != '') {
                    $this->db->limit($limit, $start);
                } else {
                    $this->db->limit($limit);
                }

                //$whr = "((user_id = $user_id AND user_type= 'Selected') OR (user_type= 'All' AND FIND_IN_SET( '$user_id' , user_viewed_status) =0))";
                $whr = "((user_id = $user_id AND user_type= 'Selected') OR (user_type= 'All'))";

                $this->db->where($whr);
                $this->db->where("store_id=", null);
                //$this->db->where('ios_user_type',null);
                //$this->db->where('android_user_type',null);
                $this->db->order_by('id', 'DESC');
                $query = $this->db->get('tbl_user_notification');
                $num_rows = $query->num_rows();
                //pr($query->result());die;
                if ($num_rows > 0) {
                    $rs_data['result']          = $query->result();
                    $rs_data['status']          = "success";
                    $rs_data['search_records']  = $num_rows;
                    $rs_data['total_records']   = $this->db->query('SELECT FOUND_ROWS() AS `count`')->row()->count;
                } else {
                    $rs_data['status']     = "error";
                    $rs_data['result']     = '';
                    $rs_data['total_records']    = 0;
                    $rs_data['search_records']  = 0;
                }


                //$this->db->where('user_id',$user_id);
                $whr = "((user_id = $user_id AND user_type= 'Selected') OR (user_type= 'All'))";
                $this->db->where($whr);
                $this->db->where("store_id=", null);
                $this->db->set('status', 1);
                $this->db->update('tbl_user_notification');

                //$whr = "((user_id = $user_id AND user_type= 'Selected') OR (user_type= 'All' AND FIND_IN_SET( '$user_id' , user_viewed_status) =0))";

                $check_all_offer_status = $this->db->select("id,user_viewed_status");
                $check_all_offer_status = $this->db->where("user_type=", "All");
                $check_all_offer_status = $this->db->where("user_id=", null);
                $check_all_offer_status = $this->db->where("store_id=", null);
                $check_all_offer_status = $this->db->where("FIND_IN_SET( '$user_id' , user_viewed_status) =", 0);
                $check_all_offer_status = $this->db->order_by('id', 'DESC');
                $check_all_offer_status = $this->db->get('tbl_user_notification')->result();
                // pr($check_all_offer_status);
                if ($check_all_offer_status[0]->id) {
                    foreach ($check_all_offer_status as $key_check_all_offer_status => $value_check_all_offer_status) {
                        if ($value_check_all_offer_status->user_viewed_status) {
                            $multi_id = $value_check_all_offer_status->user_viewed_status . ',' . $user_id;
                        } else {
                            $multi_id = $user_id;
                        }

                        $this->db->where("id", $value_check_all_offer_status->id);
                        //$this->db->set('status',1);
                        $this->db->set('user_viewed_status', $multi_id);
                        $this->db->update('tbl_user_notification');
                        //echo $this->db->last_query(); die;



                    }
                }



                //pr($rs_data);die;
                if ($rs_data['total_records'] > 0) {
                    return $rs_data;
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
    }


    public function fresh_cat_ids($user_id, $count = 0)
    {
        $this->db->select("id");
        $this->db->where('name', 'Fresh Cake');
        $this->db->or_where('name', 'Fresh Meat');
        $this->db->or_where('name', 'Meat, Eggs & Sea foods');
        $this->db->or_where('id', '278');
        return $this->db->get('tbl_categories')->result();
    }

    public function get_order_items($order_id = null, $user_id = null)
    {
        if (empty($order_id) || empty($user_id)) {
            return false;
        }
        $result = $this->db->get_where('tbl_order_detail', ['order_id' => $order_id, 'customer_id' => $user_id])->result();
        return $result;
    }

    public function on_checkout_save_address($store_id, $user_add_data)
    {


        $uid = $this->session->userdata('auth_user')['users_id'];

        // pr($store_id);die;
        //$store_id = $this->input->post('store_id');
        $store_data = get_store_name($store_id);
        if (empty($store_data) && count($store_data) == 0) {
            $this->session->set_flashdata("error", "Store Not found");
            return false;
        }

        // pr($user_add_data);
        // $store_coards 	= $store_data[0]->coords;
        $store_coards     = $store_data[0]->google_coordinate;
        $user_coards     = $user_add_data->customer_coordinates;
        $total_distance = __get_distance($store_coards, $user_coards);
        if ($total_distance == 0 && $_SESSION['user_preference']->order_type == '2') {
            $this->session->set_flashdata("error", "Distance Problem");
            return false;
        }
        // pr($total_distance);die;

        $id = $user_add_data->order_preference_address;
        $data = array(
            'store_id' => $store_id,
            'distance' => $total_distance,
            'status' => 1,
            'modified_date' => date('Y-m-d H:i:s')
        );

        // pr($data);die;
        // $this->db->where('id', $uid);
        $this->db->where('id', $id);
        $st = $this->db->update('tbl_user_address', $data);
        if ($st) {
            $user_preference = $this->session->userdata('user_preference');
            if (!empty($user_preference)) {
                if ($user_preference->order_type == 2 && $user_preference->order_preference_address == $id) {
                    //echo 'user_preference';die;
                    $user_preference->order_preference_store     = $store_id;
                    $user_preference->store_distance             = $total_distance;
                    $user_preference->store_coordinates         = $store_coards;
                    $user_preference->customer_coordinates         = $user_coards;
                    $this->session->set_userdata('user_preference', $user_preference);
                    // pr($this->session->userdata('user_preference'));die;
                }
            }
        }
        //pr($rt);die;
        return $st;
    }

    public function notification_api2($offset)
    {

        $uid = $_POST['user_id'];
        $limit = $this->dbsettings->WEBSITE_PAGINATION;
        $this->db->select('user_id,message,status,date');
        $this->db->where('user_id', $uid);
        //$this->db->where('status','0');
        $this->db->order_by('id', 'desc');
        if (!empty($offset) && $offset > 0) {
            $this->db->limit($limit, $offset);
        } else {
            $this->db->limit($limit, 0);
        }

        // $offer_msg = $this->getUserPreferences_api($uid);



        $result = $this->db->get('tbl_user_notification')->result();

        //pr($result);die;

        if (!empty($result)) {
            foreach ($result as $key => $value) {
                $string = null;
                $order_number = null;
                $row = null;
                $sql = null;
                $value->date = date('M, d ,Y h:i A', strtotime($value->date));
                $string = $value->message;
                if ($string) {
                    $str_p = strpos($string, "#");
                    $new_str = substr($string, ($str_p + 1));
                    $str_p = strpos($new_str, " )");
                    $order_number = trim(substr($new_str, 0, ($str_p)));
                    $value->order_number =  '#' . $order_number;
                    $sql = "SELECT tbl_order.* FROM `tbl_order` WHERE `tbl_order`.`order_number` = '$order_number'";
                    $row = $this->db->query($sql)->row();
                    // pr($row);die;

                    if ($row->order_status == 'Order Confirm') {
                        $value->order_status =  "Confirmed";
                    } else if ($row->order_status == 'Delivered') {
                        $value->order_status =  "Delivered";
                        //$value->order_status =  ($row->order_delivered_date!='0000-00-00 00:00:00')?date('d/m/Y h:i A',strtotime($row->order_delivered_date)):'';            
                    } else if ($row->order_status == 'Transaction Failure') {
                        $value->order_status =  "Transaction Failure";
                    } else if ($row->order_status == 'Cancelled By User') {
                        $value->order_status =  "Cancelled";
                    } else if ($row->order_status == 'Out for Delivery') {
                        $value->order_status =  "Out for Delivery";
                    } else if ($row->order_status == 'Cancel') {
                        $value->order_status =  "Cancelled";
                        if (!empty(@$row->order_cancel_by)) {
                            $value->order_status =  'Cancelled (By ' . @$row->order_cancel_by . ')';
                        }
                    } else if ($row->order_status == 'Assign Picker') {
                        $value->order_status =  "Assigned";
                    } else if ($row->order_status == 'Picked') {
                        $value->order_status =  "Picked";
                    } else if ($row->order_status == 'Billed') {
                        $value->order_status =  "Billed";
                    } else if ($row->order_status == 'Picked up by Customer') {
                        $value->order_status =  "Picked Up";
                    } else if ($row->order_status == 'Assign Delivery Boy') {
                        $value->order_status =  "Delivery Boy Assigned";
                    } else if ($row->order_status == 'Return ' || $row->order_status == 'Return') {
                        $value->order_status =  "Returned";
                    } else if ($row->order_status == 'Reschedule') {
                        $value->order_status =  "Rescheduled";
                    } else if ($row->order_status == 'WAITING PAYMENT CONFIRMATION') {
                        $value->order_status =  "WAITING PAYMENT CONFIRMATION";
                    } else if ($row->order_status == 'Order Rescheduled') {
                        $value->order_status =  "Order Rescheduled";
                    } else {
                        $value->order_status =  $row->order_status;
                    }
                } else {
                    $value->order_status = '';
                    $value->order_number = '';
                }
            }
            return $result;
        } else {
            return false;
        }
    }

    public function notification_api()
    {
        $uid = $_POST['user_id'];
        $user_id = $_POST['user_id'];
        $limit = $_POST['limit'];
        $start = $_POST['start'];
        if (@$limit == '') {
            $limit = $this->dbsettings->WEBSITE_PAGINATION;
        }

        if ($user_id) { {
                $this->db->select('SQL_CALC_FOUND_ROWS link,user_id,message,status,date,offer_id,user_viewed_status,user_type,android_user_type,ios_user_type,store_id', FALSE);
                $whr = "((user_id = $user_id AND user_type= 'Selected') OR (user_type= 'All'))";
                $this->db->where($whr);
                $this->db->order_by('id', 'DESC');
                $query = $this->db->get('tbl_user_notification');
                $num_rows = $query->num_rows();
                $rs = 0;
                if ($num_rows > 0) {
                    $rs_data['result']          = $query->result();
                    $rs_data['status']          = "success";
                    $rs_data['search_records']  = $num_rows;
                    $rs_data['total_records']   = $this->db->query('SELECT FOUND_ROWS() AS `count`')->row()->count;

                    /////////////////////////////////////////////////////////////////
                    if (!empty($rs_data['result'])) {
                        foreach ($rs_data['result'] as $key => $value) {
                            $string = null;
                            $order_number = null;
                            $row = null;
                            $sql = null;
                            $offer_end_time = date('d-m-Y H:i', strtotime("+1 day", strtotime($value->date)));
                            $value->offer_end_time  = $offer_end_time;
                            $value->date = date('M, d ,Y h:i A', strtotime($value->date));
                            $string = $value->message;
                            if ($string) {
                                $str_p = strpos($string, "#");
                                $new_str = substr($string, ($str_p + 1));
                                $str_p = strpos($new_str, " )");
                                $order_number = trim(substr($new_str, 0, ($str_p)));
                                $value->order_number =  '#' . $order_number;
                                $sql = "SELECT tbl_order.* FROM `tbl_order` WHERE `tbl_order`.`order_number` = '$order_number'";
                                $row = $this->db->query($sql)->row();
                                // pr($row);die;

                                if (isset($row->order_status) && $row->order_status == 'Order Confirm') {
                                    $value->order_status =  "Confirmed";
                                } else if (isset($row->order_status) && $row->order_status == 'Delivered') {
                                    $value->order_status =  "Delivered";
                                    //$value->order_status =  ($row->order_delivered_date!='0000-00-00 00:00:00')?date('d/m/Y h:i A',strtotime($row->order_delivered_date)):'';            
                                } else if (isset($row->order_status) && $row->order_status == 'Transaction Failure') {
                                    $value->order_status =  "Transaction Failure";
                                } else if (isset($row->order_status) && $row->order_status == 'Cancelled By User') {
                                    $value->order_status =  "Cancelled";
                                } else if (isset($row->order_status) && $row->order_status == 'Out for Delivery') {
                                    $value->order_status =  "Out for Delivery";
                                } else if (isset($row->order_status) && $row->order_status == 'Cancel') {
                                    $value->order_status =  "Cancelled";
                                    if (!empty(@$row->order_cancel_by)) {
                                        $value->order_status =  'Cancelled (By ' . @$row->order_cancel_by . ')';
                                    }
                                } else if (isset($row->order_status) && $row->order_status == 'Assign Picker') {
                                    $value->order_status =  "Assigned";
                                } else if (isset($row->order_status) && $row->order_status == 'Picked') {
                                    $value->order_status =  "Picked";
                                } else if (isset($row->order_status) && $row->order_status == 'Billed') {
                                    $value->order_status =  "Billed";
                                } else if (isset($row->order_status) && $row->order_status == 'Picked up by Customer') {
                                    $value->order_status =  "Picked Up";
                                } else if (isset($row->order_status) && $row->order_status == 'Assign Delivery Boy') {
                                    $value->order_status =  "Delivery Boy Assigned";
                                } else if (isset($row->order_status) && $row->order_status == 'Return ' || $row->order_status == 'Return') {
                                    $value->order_status =  "Returned";
                                } else if ($row->order_status == 'Reschedule') {
                                    $value->order_status =  "Rescheduled";
                                } else if (isset($row->order_status) && $row->order_status == 'WAITING PAYMENT CONFIRMATION') {
                                    $value->order_status =  "WAITING PAYMENT CONFIRMATION";
                                } else if (isset($row->order_status) && $row->order_status == 'Order Rescheduled') {
                                    $value->order_status =  "Order Rescheduled";
                                } else {
                                    $value->order_status =  $row->order_status;
                                }
                            } else {
                                $value->order_status = '';
                                $value->order_number = '';
                            }

                            ////for android & ios notification filteration starts ////
                            $userDetails = getUsers($user_id)[0];
                            //$value->userDetails = $userDetails;
                            if ($userDetails->id && $value->user_type == 'All' && $value->offer_id == null && ($value->android_user_type == 'ALL_Android' && ($userDetails->login_type == 'android' || $userDetails->login_type == 'website'))) {

                                $user_selected_store = get_store_id_for_api('id', $user_id);
                                if (strpos($value->store_id, $user_selected_store) !== false) {
                                    $new_rs_data[$rs] = $value;
                                    $rs++;
                                }
                            } else if ($userDetails->id && $value->user_type == 'All' && $value->offer_id == null && ($value->ios_user_type == 'All_IOS' && $userDetails->login_type == 'ios')) {

                                $user_selected_store = get_store_id_for_api('id', $user_id);
                                if (strpos($value->store_id, $user_selected_store) !== false) {
                                    $new_rs_data[$rs] = $value;
                                    $rs++;
                                }
                            } else if ($userDetails->id && $userDetails->id == $user_id && $value->user_type != 'All'  && $userDetails->login_type == 'ios') {
                                $new_rs_data[$rs] = $value;
                                $rs++;
                            } else if ($userDetails->id && $userDetails->id == $user_id && $value->user_type != 'All'  && ($userDetails->login_type == 'android' || $userDetails->login_type == 'website')) {
                                $new_rs_data[$rs] = $value;
                                $rs++;
                            } else {
                            }
                        }
                        $rs = 0;
                        $rs_data['result']          = $new_rs_data;
                        $rs_data['status']          = "success";
                    } else {
                        $rs_data['status']          = "error";
                    }
                } else {
                    $rs_data['status']     = "error";
                    $rs_data['result']     = '';
                    $rs_data['total_records']    = 0;
                    $rs_data['search_records']  = 0;
                }

                $ikl = 0;
                if ($rs_data['total_records'] > 0  && $rs_data['status'] == 'success') {
                    return $rs_data['result'];
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
    }

    public function notification_status_api()
    {
        $user_id = $_POST['user_id'];
        $whr = "((user_id = $user_id AND user_type= 'Selected') OR (user_type= 'All'))";
        $this->db->where("user_type=", "Selected");
        $this->db->where($whr);
        //$this->db->where('user_id',$user_id);
        $this->db->set('status', 1);
        $this->db->update('tbl_user_notification');
        $check_all_offer_status = $this->db->select("id,user_viewed_status");
        $check_all_offer_status = $this->db->where("user_type=", "All");
        $check_all_offer_status = $this->db->where("user_id=", null);
        $check_all_offer_status = $this->db->where("FIND_IN_SET( '$user_id' , user_viewed_status) =", 0);
        $check_all_offer_status = $this->db->order_by('id', 'DESC');
        $check_all_offer_status = $this->db->get('tbl_user_notification')->result();
        //pr($check_all_offer_status);die;
        if ($check_all_offer_status[0]->id) {
            foreach ($check_all_offer_status as $key_check_all_offer_status => $value_check_all_offer_status) {
                if ($value_check_all_offer_status->user_viewed_status) {
                    $multi_id = $value_check_all_offer_status->user_viewed_status . ',' . $user_id;
                } else {
                    $multi_id = $user_id;
                }

                $this->db->where("id", $value_check_all_offer_status->id);
                //$this->db->set('status',1);
                $this->db->set('user_viewed_status', $multi_id);
                $this->db->update('tbl_user_notification');
                //echo $this->db->last_query(); die;
            }
        }
    }

    public function get_order($order_id  = NULL)
    {
        $data = [];
        if (isset($order_id) && !empty($order_id)) {
            $this->db->select('id,order_number,shipping_name,user_id');
            $this->db->where('id', $order_id);
            $data = $this->db->get('tbl_order')->row();
        }
        return $data;
    }

    public function get_min_shipping($distance, $user_id)
    {
        if (isset($distance) && !empty($distance)) {
            $sql  = "SELECT * FROM tbl_shiping WHERE $distance BETWEEN distancefrom AND distanceto AND status = 1 ORDER BY  distancefrom ASC LIMIT 1";
            $query = $this->db->query($sql);
            if ($query->num_rows() > 0) {
                return $query->row()->minimum_order_price;
            }
        }
        return false;
    }

    public function get_wishlist($user_id)
    {
        $data =  [];
        if (isset($user_id) && !empty($user_id)) {
            $this->db->select('*');
            $this->db->where('status', '1');
            $this->db->where('user_id', $user_id);
            // $this->db->where("FIND_IN_SET($id,variant_id)!=", 0);
            $result = $this->db->get('tbl_wishlist')->row();
            if (isset($result) && !empty($result)) {
                $data = json_decode($result->variant_id);
            }
            // echo $this->db->last_query();
        }
        return $data;
    }
}