<?php
class M_admin extends CI_Model
{


    function getCountries($language, $id)
    {
          /* $query = $this->db->get_where('country', array('country_language_code' => $language,'country_id'=>$id));
            $this->db->order_by('country_language_code','ASC');
          echo $this->db->last_query();
          return $query->row();
*/

        $this->db->select('*');
        $this->db->from('country c');
        $this->db->where('country_language_code', $language);
        $this->db->where('country_id', $id);
        $this->db->order_by('country_language_code', 'ASC');
        $query = $this->db->get();
    //echo $this->db->last_query();
        return $query->row();
    }
    function getUserTypes()
    {
          $query = $this->db->get_where('user_type', array('user_type_status' => "Y"));
          return $query->result();
    }
    function login($data)
    {

            $query = $this->db->get_where('admin_user', $data);
           // echo $this->db->last_query();
            return $query->row();
    }
    function getCountriesByAjax()
    {

        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $this->db->select('c.*,c2.country_name as arbicname,c.country_name as englishname');
        $this->db->from('country c');
        $this->db->join('country c2', 'c2.country_id =c.country_id', 'left');
        $this->db->where('c.country_language_code', 1);
        $this->db->where('c2.country_language_code', 2);
           /* if($additional['searchKey']!="")
            {
                $this->db->like('LOWER(c.country_name)', strtolower($additional['searchKey']));
            }*/
            $this->db->order_by('c.country_id', 'desc');
            //$this->db->limit($limit, $start);
            $query = $this->db->get();
           //  echo $this->db->last_query();
             return $query->result();
    }
    function updateServiceTypePriority($priority, $priority_column, $category_id)
    {
        $this->db->trans_start();
            $this->db->select($priority_column);
            $this->db->from('category');
            $this->db->where('category_id', $category_id);
            // echo $this->db->last_query();
            $query   =   $this->db->get();
            $old_priority  =   $query->row();

            $this ->db-> where($priority_column, $priority);
            $this->db->set($priority_column, $old_priority->$priority_column);

            $this -> db ->update('category');
            // echo $this->db->last_query();
            $this -> db -> where('category_id', $category_id);
            $this->db->set($priority_column, $priority);
            $this -> db -> update('category');
// echo $this->db->last_query();
            $this->db->trans_complete();
            if ($this->db->trans_status() === false) {
                     return 0;
        } else {
            return 1;
        }
    }
    function getCountriesByAjaxTotal($additional)
    {
           $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
           $this->db->select('count(country_id) as count');
           $this->db->from('country c');
           $this->db->where('country_language_code', $language);
        if ($additional['searchKey']!="") {
            $this->db->like('LOWER(country_name)', strtolower($additional['searchKey']));
        }

            $query = $this->db->get();
           // echo $this->db->last_query();
            return $query->row();
    }


    function saveMasterTable($inputArray, $inputArray2, $key, $languageField, $tableName)
    {


            $language =($this->session->userdata('language')?$this->session->userdata('language'):1);

                 $this->db->trans_start();

        if ( $key == 'category_id') {
            $cat_product_attributes = $inputArray['category_product_attributes'];
            unset($inputArray['category_product_attributes']);
            unset($inputArray2['category_product_attributes']);
        } else {
            $cat_product_attributes = [];
        }
        if (isset($inputArray[$key]) && $inputArray[$key]>0) {
            $this->db->where($key, $inputArray[$key]);
            $this->db->where($languageField, 1);
            $this->db->update($tableName, $inputArray);


            $this->db->where($key, $inputArray2[$key]);
            $this->db->where($languageField, 2);
            $this->db->update($tableName, $inputArray2);



            $entityId =  $inputArray2[$key];

            $action   = 2;
        } else {
            $this->db->select('max('.$key.') as maxid');
            $this->db->from(''.$tableName.' c');
            $this->db->where($languageField, $language);
            $query = $this->db->get();
      // echo $this->db->last_query();
            $res  =  $query->row();
            $maxId              =   ($res->maxid>0?$res->maxid+1:1);


            $inputArray[$key]     =   $maxId  ;
            $inputArray2[$key]    =   $maxId  ;
            $this->db->insert($tableName, $inputArray);

        // echo $this->db->last_query(); exit;
            $this->db->insert($tableName, $inputArray2);

            $entityId =  $maxId;
            $action   = 1;
        }


                 //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        if ($key=="country_id") {
              $moduleId = 6;
        } else if ($key=="city_id") {
            $moduleId = 7;
        } else if ($key=="category_id") {
            $moduleId = 8;

            $insert_data = [];
            $skip_data = [];
            $delete_data = [];

            $attribute_map = $this->db->get_where('attribute_category_map', ['category_id' => $entityId])
                                        ->result_array();
            $current_data = [];
            foreach ($attribute_map as $t_row) {
                if ( in_array($t_row['attribute_id'], $cat_product_attributes) ) {
                    $skip_data[] = $t_row['attribute_id'];
                } else {
                    $delete_data[] = $t_row['attribute_id'];
                }
            }
            foreach ($cat_product_attributes as $t_id) {
                if ( (! in_array($t_id, $skip_data) ) && (! in_array($t_id, $delete_data) ) ) {
                    $insert_data[] = [
                        'attribute_id' => $t_id,
                        'category_id' => $entityId,
                    ];
                }
            }
            if (! empty($insert_data) ) {
                $this->db->insert_batch('attribute_category_map', $insert_data);
            }
            if (! empty($delete_data) ) {
                $this->db->where('category_id',  $entityId);
                $this->db->where_in('attribute_id', $delete_data);
                $this->db->delete('attribute_category_map');
            }

        } else if ($key=="brand_id") {
            $moduleId = 11;
        } else if ($tableName=="banner_images") {
            $moduleId = 12;
        } else if ($tableName=="slider_images") {
            $moduleId = 13;
        } else if ($tableName=="dragon_slider_images") {
            $moduleId = 14;
        } else if ($tableName=="dragon_slider_images_app") {
            $moduleId = 15;
        } else if ($tableName=="banner_images_app") {
            $moduleId = 16;
        } else if ($tableName=="slider_images_app") {
            $moduleId = 17;
        } else if ($tableName=="dragon_slider_images_app") {
            $moduleId = 18;
        } else if ($tableName=="dragon_offer_banner") {
            $moduleId = 19;
        } else if ($tableName=="app_homer_offer_popup") {
            $moduleId = 20;
        }

                    //dragon_offer_banner?:


                        $auditArray                     =     array();
                        $auditArray['admin_id']         =     $this->session->userdata('admin_id');
                        $auditArray['module_id']        =     $moduleId;
                        $auditArray['entity_id']        =     $entityId;
                        $auditArray['action_id']        =     $action;
                        $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
                        $auditArray['audit_note']       =     "";
                        $auditArray['menu_id']          =     5;
                        $this->db->insert('admin_audit_trial', $auditArray);

                    //admin audit trial //admin audit trial//admin audit trial//admin audit trial


                        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }

    function saveMasterTable2($inputArray, $key, $tableName)
    {

                $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
                    $this->db->trans_start();
        if (isset($inputArray[$key]) && $inputArray[$key]>0) {
               $this->db->where($key, $inputArray[$key]);
               //$this->db->where($languageField, 1);
               $this->db->update($tableName, $inputArray);

             $entityId  =  $inputArray[$key];
             $action    =  2;
        } else {
            $this->db->select('max('.$key.') as maxid');
            $this->db->from(''.$tableName.' c');
            //$this->db->where($languageField,$language);
            $query = $this->db->get();
           // echo $this->db->last_query();
            $res  =  $query->row();
            $maxId              =   ($res->maxid>0?$res->maxid+1:1);

         //print_r($inputArray);
             $inputArray[$key]    =   $maxId  ;

             $this->db->insert($tableName, $inputArray);

             $action = 1;
             $entityId =  $maxId;
        }

        if ($tableName=="dragon_offer_banner") {
            $moduleId = 19;
        }

                    $auditArray                     =     array();
                    $auditArray['admin_id']         =     $this->session->userdata('admin_id');
                    $auditArray['module_id']        =     $moduleId;
                    $auditArray['entity_id']        =     $entityId;
                    $auditArray['action_id']        =     $action;
                    $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
                    $auditArray['audit_note']       =     "";
                    $auditArray['menu_id']          =     5;
                    $this->db->insert('admin_audit_trial', $auditArray);

                    //admin audit trial //admin audit trial//admin audit trial//admin audit trial

                 $this->db->trans_complete();



        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }
            /* public function getCountries($language)
            {
                    $query = $this->db->get_where('country', array('country_language_code' => $language));
                   // echo $this->db->last_query();
                    return $query->result();
            }*/

    function deleteCountry($id)
    {
           $this->db->trans_start();

           $this -> db -> where('country_id', $id);
           $this -> db -> delete('country');

           //admin audit trial //admin audit trial//admin audit trial//admin audit trial

             $auditArray                     =     array();
             $auditArray['admin_id']         =     $this->session->userdata('admin_id');
             $auditArray['module_id']        =     6;
             $auditArray['entity_id']        =     $id;
             $auditArray['action_id']        =     3;
             $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
             $auditArray['audit_note']       =     "country delete from admin module";
             $auditArray['menu_id']          =     5;
             $this->db->insert('admin_audit_trial', $auditArray);

             //admin audit trial //admin audit trial//admin audit trial//admin audit trial

          $this->db->trans_complete();



        if ($this->db->trans_status() === false) {
              return 0;
        } else {
                  return 1;
        }
    }












    function getDress_typeByAjax()
    {

        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);

        $this->db->where('dress_type_language_code', $language);

        $this->db->order_by('dress_type_id', 'desc');

         $query = $this->db->get('dress_type');

          return $query->result();
    }





    function getcloth_typeByAjax()
    {

        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);

        $this->db->where('cloth_type_language_code', $language);

        $this->db->order_by('cloth_type_id', 'desc');

         $query = $this->db->get('cloth_type');

          return $query->result();
    }







    function getCitiesByAjax()
    {
        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $this->db->select('c.*,c2.city_name as arbicname,c.city_name as englishname,country_name');
        $this->db->from('city c');
        $this->db->join('city c2', 'c2.city_id =c.city_id', 'left');
        $this->db->join('country c3', 'c.city_country_id =c3.country_id', 'left');
        $this->db->where('c3.country_language_code', 1);
        $this->db->where('c.city_language_code', 1);
        $this->db->where('c2.city_language_code', 2);
        /* if($additional['searchKey']!="")
         {
             $this->db->like('LOWER(c.city_name)', strtolower($additional['searchKey']));
         }*/
         $this->db->order_by('c.city_id', 'desc');
        // $this->db->limit($limit, $start);
         $query = $this->db->get();
        // echo $this->db->last_query();
          return $query->result();
    }
    function getCitiesByAjaxTotal($additional)
    {
        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $this->db->select('count(city_id) as count');
        $this->db->from('city c');

        $this->db->where('c.city_language_code', 1);

        if ($additional['searchKey']!="") {
                  $this->db->like('LOWER(c.city_name)', strtolower($additional['searchKey']));
        }
                $this->db->order_by('c.city_id', 'desc');
                $this->db->limit($limit, $start);
                $query = $this->db->get();
               //  echo $this->db->last_query();
            return $query->row();
    }


    public function getDresstypeCondition($data)
    {
              $query = $this->db->order_by('dress_type_id', 'asc')->get_where('dress_type', $data);
            //  $this->db->order_by('country_language_code','ASC');
            // $this->db->last_query();
            return $query->result();
    }


    public function getclothtypeCondition($data)
    {
              $query = $this->db->order_by('cloth_type_id', 'asc')->get_where('cloth_type', $data);
            //  $this->db->order_by('country_language_code','ASC');
            // $this->db->last_query();
            return $query->result();
    }



    public function getCountriesCondition($data)
    {
              $query = $this->db->order_by('country_name', 'asc')->get_where('country', $data);
             //$this->db->order_by('country_language_code','ASC');
          // echo $this->db->last_query();
            return $query->result();
    }



    function getDressType($language, $id)
    {
        $query = $this->db->get_where('dress_type', array('dress_type_language_code'=>$language,'dress_type_id'=>$id));
        return $query->row();
    }



    function getclothType($language, $id)
    {
        $query = $this->db->get_where('cloth_type', array('cloth_type_language_code'=>$language,'cloth_type_id'=>$id));
        return $query->row();
    }


    function getCities($language, $id)
    {
        $query = $this->db->get_where('city', array('city_language_code'=>$language,'city_id'=>$id));
        return $query->row();
    }



    function deleteCity($id)
    {
               $this->db->trans_start();

              $this -> db -> where('city_id', $id);
              $this -> db -> delete('city');


              //admin audit trial //admin audit trial//admin audit trial//admin audit trial

                $auditArray                     =     array();
                $auditArray['admin_id']         =     $this->session->userdata('admin_id');
                $auditArray['module_id']        =     7;
                $auditArray['entity_id']        =     $id;
                $auditArray['action_id']        =     3;
                $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
                $auditArray['audit_note']       =     "city delete from admin module";
                $auditArray['menu_id']          =     5;
                $this->db->insert('admin_audit_trial', $auditArray);

                //admin audit trial //admin audit trial//admin audit trial//admin audit trial

              $this->db->trans_complete();



        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }



    function deleteDress_type($id)
    {
               $this->db->trans_start();

              $this -> db -> where('dress_type_id', $id);
              $this -> db -> delete('dress_type');


              //admin audit trial //admin audit trial//admin audit trial//admin audit trial

                $auditArray                     =     array();
                $auditArray['admin_id']         =     $this->session->userdata('admin_id');
                $auditArray['module_id']        =     7;
                $auditArray['entity_id']        =     $id;
                $auditArray['action_id']        =     3;
                $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
                $auditArray['audit_note']       =     "city delete from admin module";
                $auditArray['menu_id']          =     5;
                $this->db->insert('admin_audit_trial', $auditArray);

                //admin audit trial //admin audit trial//admin audit trial//admin audit trial

              $this->db->trans_complete();



        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }

    public function getSocialCategoryList()
    {
        return $this->db->select("social_category.*, social_category_lang.scategory_lang_text as cat_arabic")
                        ->from("social_category")
                        ->join("social_category_lang", "social_category_lang.scategory_id=social_category.scategory_id", "left")
                        ->where("social_category_lang.lang_code", "2")
                        ->order_by("scategory_name", "asc")
                        ->get()
                        ->result();
    }

    public function createSocialCategory($data)
    {
        $this->db->insert("social_category", $data);
        return $this->db->insert_id("social_category_scategory_id_seq");
    }

    public function createSocialCategoryLangs($data)
    {
        $this->db->insert("social_category_lang", $data);
        return $this->db->insert_id("social_category_lang_scategory_lang_id_seq");
    }

    public function updateSocialCategory($data, $category_id)
    {
        $this->db->where("scategory_id", $category_id)
                 ->update("social_category", $data);
        return $this->db->affected_rows();
    }

    public function updateSocialCategoryLangs($category_id, $lang_code, $lang_text)
    {
        $this->db->where("scategory_id", $category_id)
                 ->update("social_category_lang", array("scategory_lang_text" => $lang_text));
        return $this->db->affected_rows();
    }

    public function deleteSocialCategory($category_id)
    {
        $this->db->where("scategory_id", $category_id)
                        ->delete("social_category_lang");

        $this->db->where("scategory_id", $category_id)
                        ->delete("social_category");

        return $this->db->affected_rows();
    }

    public function getSocialCategory($scategory_id)
    {
        return $this->db->select("*")
                        ->from("social_category")
                        ->where("scategory_id", $scategory_id)
                        ->get()
                        ->row();
    }

    public function getSocialCategoryLang($scategory_id, $lang_code)
    {
        return $this->db->select("*")
                        ->from("social_category_lang")
                        ->where("scategory_id", $scategory_id)
                        ->where("lang_code", $lang_code)
                        ->get()
                        ->row();
    }

    public function getSocialCategoryPostContentCount($scategory_id)
    {
        return $this->db->select("count(scategory_id) as count")
                        ->from("social_post_content_categories")
                        ->where("scategory_id", $scategory_id)
                        ->get()
                        ->row()
                        ->count;
    }


    public function getCategoriesCondition($data)
    {




            $query = $this->db->order_by('category_name', 'asc')->get_where('category', $data);
            //$this->db->order_by('country_language_code','ASC');
            //echo $this->db->last_query();
            return $query->result();
    }
    function getCategoryWithParent()
    {
        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $this->db->select('c.*,c2.category_name as arbicname,c.category_name as englishname,c3.category_name as parentname');
        $this->db->from('category c');
        $this->db->join('category c2', 'c2.category_id =c.category_id', 'left');
        $this->db->join('category c3', '(c.category_parent_id =c3.category_id) AND (c3.category_language_code =1)', 'left');
        $this->db->where('c.category_language_code', 1);
        $this->db->where('c2.category_language_code', 2);
        $this->db->order_by('c.sort_order', 'asc');
        $query = $this->db->get();
        // echo $this->db->last_query();
        return $query->result();
    }
    function getCategories($language, $id)
    {
        $query = $this->db->get_where('category', array('category_language_code'=>$language,'category_id'=>$id));
         return $query->row();
    }
    function getParentCategories($language=1)
    {
        $query = $this->db->select('*')->from('category')->where(array('category_language_code'=>$language,'category_parent_id' => 0))->order_by('sort_order','asc');
         return$query = $this->db->get()->result();
    }
    function deleteCategory($id)
    {
               $this->db->trans_start();

               $this -> db -> where('category_id', $id);
               $this -> db -> delete('category');

               //admin audit trial //admin audit trial//admin audit trial//admin audit trial

                $auditArray                     =     array();
                $auditArray['admin_id']         =     $this->session->userdata('admin_id');
                $auditArray['module_id']        =     8;
                $auditArray['entity_id']        =     $id;
                $auditArray['action_id']        =     3;
                $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
                $auditArray['audit_note']       =     "country delete from admin module";
                $auditArray['menu_id']          =     5;
                $this->db->insert('admin_audit_trial', $auditArray);

               //admin audit trial //admin audit trial//admin audit trial//admin audit trial


                 $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }
    public function getUsersCondition($data)
    {




              $query = $this->db->order_by('user_first_name', 'asc')->get_where('user_table', $data);
              //$this->db->order_by('country_language_code','ASC');
              // echo $this->db->last_query();
              return $query->result();
    }
    public function getCitiesCondition($data)
    {




             $query = $this->db->order_by('city_name', 'asc')->get_where('city', $data);
             //$this->db->order_by('country_language_code','ASC');
             // echo $this->db->last_query();
             return $query->result();
    }

    public function saveCustomerUser($data)
    {
        $inputUserBasic['user_first_name']     =    $data['txt_first_name'];
        $inputUserBasic['user_last_name']     =    $data['txt_last_name'];
        $inputUserBasic['company_name']        =    $data['txt_first_name']." ".$data['txt_last_name'];
        $inputUserBasic['user_email_id']       =    $data['txt_email'];
        $inputUserBasic['user_country_id']     =    $data['select_country'];
        $inputUserBasic['user_city_id']        =    $data['select_city'];
        $inputUserBasic['user_password']       =    password_hash($data['txt_password'], PASSWORD_DEFAULT, ['cost' => 12]);
        $inputUserBasic['user_status']         =    0;
        $inputUserBasic['user_deleted']        =    0;
        $inputUserBasic['user_created_by']     =    'A';
        $inputUserBasic['user_created_date']   =    gmdate("Y-m-d H:i:s");
        $inputUserBasic['user_type']           =    $data['user_type'] ?? 'U';
        $inputUserBasic['user_custom_id']      =    $this->getUserCustomId();

        $inputUserBasic['dial_code']           =    $data['txt_dialcode'] ?? '';
        $inputUserBasic['trade_license_no']    =    $data['txt_trade_license'] ?? '';
        $inputUserBasic['phone_number']        =    $data['txt_phone'] ?? '';
        $inputUserBasic['phone_verified']      =    $data['phone_verified'] ?? 0;
        $inputUserBasic['image']               =    $data['image'] ?? '';
        $inputUserBasic['user_location']       =    $data['txt_location'] ?? '';
        $inputUserBasic['user_latitude']       =    $data['txt_latitude'] ?? '';
        $inputUserBasic['user_longitude']      =    $data['txt_longitude'] ?? '';

        $this->db->select('count(user_email_id) as count');
        $this->db->from('user_table c');
        $this->db->where('user_email_id', $inputUserBasic['user_country_id']);
        $query = $this->db->get();

        if ($query->row()->count>0) {
            return 3;
            exit;
        }

        $this->db->select('count(user_custom_id) as count');
        $this->db->from('user_table c');
        $this->db->where('user_custom_id', $data['user_custom_id']);
        $query = $this->db->get();

        if ($query->row()->count>0) {
            return 4;
            exit;
        }

        $this->db->trans_start();

        $this->db->insert('user_table', $inputUserBasic);
        $insertId = $this->db->insert_id();

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        $auditArray                     =    array();
        $auditArray['admin_id']         =    $this->session->userdata('admin_id');
        $auditArray['module_id']        =    1;
        $auditArray['entity_id']        =    $insertId;
        $auditArray['action_id']        =    1;
        $auditArray['audit_time']       =    gmdate("Y-m-d H:i:s");
        $auditArray['audit_note']       =    "Customer creation by admin module";
        $auditArray['menu_id']          =    3;
        $this->db->insert('admin_audit_trial', $auditArray);

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }

    public function updateCustomerUser($data)
    {
        $id =    $data['id'] ?? 0;
        if ( $id > 0 ) {
            $inputUserBasic['user_first_name']     =    $data['txt_first_name'];
            $inputUserBasic['user_last_name']      =    $data['txt_last_name'];
            $inputUserBasic['company_name']        =    $data['txt_company'];
            $inputUserBasic['user_email_id']       =    $data['txt_email'];
            $inputUserBasic['user_country_id']     =    $data['select_country'];
            $inputUserBasic['user_city_id']        =    $data['select_city'];
            $inputUserBasic['dial_code']           =    $data['txt_dialcode'] ?? '';
            $inputUserBasic['trade_license_no']    =    $data['txt_trade_license'] ?? '';
            $inputUserBasic['phone_number']        =    $data['txt_phone'] ?? '';
            $inputUserBasic['user_location']       =    $data['txt_location'] ?? '';
            $inputUserBasic['user_latitude']       =    $data['txt_latitude'] ?? '';
            $inputUserBasic['user_longitude']      =    $data['txt_longitude'] ?? '';

            $user_password = $data['txt_password'] ?? '';
            if ( !empty($user_password) ) {
                $inputUserBasic['user_password'] = password_hash($user_password, PASSWORD_DEFAULT, ['cost' => 12]);
            }

            $image = $data['image'] ?? '';
            if (! empty($image) ) {
                $inputUserBasic['image'] = $image;
            }

            $this->db->select('count(user_email_id) as count');
            $this->db->from('user_table c');
            $this->db->where('user_email_id', $inputUserBasic['user_email_id']);
            $this->db->where('user_id !=', $id);
            $query = $this->db->get();

            if ( $query->row()->count > 0 ) {
                return 3;
                exit;
            }            

            $this->db->trans_start();

            $this->db->where('user_id', $id);
            $this->db->update('user_table', $inputUserBasic);

            //admin audit trial //admin audit trial//admin audit trial//admin audit trial
            $auditArray                     =     array();
            $auditArray['admin_id']         =     $this->session->userdata('admin_id');
            $auditArray['module_id']        =     1;
            $auditArray['entity_id']        =     $id;
            $auditArray['action_id']        =     1;
            $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
            $auditArray['audit_note']       =     "Customer updation from admin module";
            $auditArray['menu_id']          =     3;
            $this->db->insert('admin_audit_trial', $auditArray);
            //admin audit trial //admin audit trial//admin audit trial//admin audit trial
            
            $this->db->trans_complete();
            if ($this->db->trans_status() === false) {
                $this->db->trans_rollback();
                return 0;
            } else {
                $this->db->trans_commit();
                return 1;
            }

        } else {
            return 0;
        }
    }

    function saveUser($data)
    {
        $inputUserBasic['user_first_name']     =    $data['txt_first_name'];
        $inputUserBasic['user_last_name']      =    $data['txt_last_name'];
        $inputUserBasic['user_email_id']       =    $data['txt_email'];
        $inputUserBasic['user_gender']         =    $data['radio_gender'];
        $inputUserBasic['user_country_id']     =    $data['select_country'];
        $inputUserBasic['user_password']       =    password_hash($data['txt_password'], PASSWORD_DEFAULT, ['cost' => 12]);
        $inputUserBasic['user_status']         =    0;
        $inputUserBasic['user_deleted']        =    0;
        $inputUserBasic['user_status']         =    0;
        $inputUserBasic['user_deleted']        =    0;
        $inputUserBasic['user_created_by']     =    'A';
        $inputUserBasic['user_created_date']   =    gmdate("Y-m-d H:i:s");
        $inputUserBasic['user_type']           =    'U';
        $inputUserBasic['user_custom_id']      =   $this->getUserCustomId();

        $inputUserBasic['phone_number']        =   $data['txt_Phone'][0];
        $inputUserBasic['phone_verified']      =   $data['phone_verified'] ?? 0;

        $this->db->select('count(user_email_id) as count');
        $this->db->from('user_table c');
        $this->db->where('user_email_id', $data['txt_email']);
        $query = $this->db->get();
        // echo $this->db->last_query();

        if ($query->row()->count>0) {
            return 3;
            exit;
        }

        $this->db->select('count(user_custom_id) as count');
        $this->db->from('user_table c');
        $this->db->where('user_custom_id', $data['user_custom_id']);
        $query = $this->db->get();
        // echo $this->db->last_query();

        if ($query->row()->count>0) {
            return 4;
            exit;
        }


               $this->db->trans_start();



                $this->db->insert('user_table', $inputUserBasic);
                $insertId = $this->db->insert_id();

                //admin audit trial //admin audit trial//admin audit trial//admin audit trial

                $auditArray                     =    array();
                $auditArray['admin_id']         =    $this->session->userdata('admin_id');
                $auditArray['module_id']        =    1;
                $auditArray['entity_id']        =    $insertId;
                $auditArray['action_id']        =    1;
                $auditArray['audit_time']       =    gmdate("Y-m-d H:i:s");
                $auditArray['audit_note']       =    "User creation by admin module";
                $auditArray['menu_id']          =    3;
                $this->db->insert('admin_audit_trial', $auditArray);

                //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        for ($i=0; $i<count($data['select_city']); $i++) {
                      $inputUserShiping['user_shiping_details_city']     =    $data['select_city'][$i];
              // $inputUserShiping['user_shiping_details_phone']    =    $data['txt_dial'][$i]."-".$data['txt_Phone'][$i];
              // new one start
               $inputUserShiping['user_shiping_details_dial_code']=    $data['txt_dial'][$i];
            $inputUserShiping['user_shiping_details_phone']    =    $data['txt_Phone'][$i];
              // new one end
              $inputUserShiping['user_shiping_details_loc']      =    $data['txt_location'][$i];
              $inputUserShiping['user_shiping_details_street']   =    $data['txt_street'][$i];
              $inputUserShiping['user_shiping_details_building'] =    $data['txt_building'][$i];
              $inputUserShiping['user_shiping_details_landmark'] =    $data['txt_land_mark'][$i];
              $inputUserShiping['user_shiping_details_floorno']  =    $data['txt_floor'][$i];
              $inputUserShiping['user_shiping_details_flatno']   =    $data['txt_flat'][$i];
              $inputUserShiping['user_shiping_details_note']     =    $data['txt_shipping_note'][$i];
              $inputUserShiping['user_shiping_details_area']     =    $data['select_area'][$i]>0?$data['select_area'][$i]:0;
              $inputUserShiping['user_shiping_details_loc_type']     =    $data['select_location_type'][$i]>0?$data['select_location_type'][$i]:0;
              $inputUserShiping['user_shiping_details_latitude']     =    $data['latti'][$i];
              $inputUserShiping['user_shiping_details_longitude']     =    $data['longi'][$i];
            // new one start
              $inputUserShiping['user_shiping_country_id']     =    $data['select_country2'][$i];
              $inputUserShiping['first_name']      =    $data['txt_first_name'];
              $inputUserShiping['last_name']      =    $data['txt_last_name'];
            // new one end
              $inputUserShiping['user_shiping_details_user_id']  =    $insertId;

            if ($data['select_city'][$i]!="" && $data['txt_Phone'][$i]!="" && $data['txt_location'][$i]!="") {
                         $this->db->insert('user_shiping_details', $inputUserShiping);
            }
        }

               $this->db->trans_complete();



        if ($this->db->trans_status() === false) {
             return 0;
        } else {
              return 1;
        }
    }
    function userDetails($data)
    {
        $query = $this->db->order_by('user_id', 'DESC')->get_where('user_table', $data);
        //$this->db->order_by('country_language_code','ASC');
        //  echo $this->db->last_query();
        return $query->result();
    }
    function getShipingDetails($data)
    {
            $query = $this->db->order_by('user_shiping_details_id', 'ASC')->get_where('user_shiping_details', $data);
              //$this->db->order_by('country_language_code','ASC');
              // echo $this->db->last_query();
              // die();
              return $query->result();
    }
     function updateUser($data)
    {
        $userId    =   $data['id'];

        $inputUserBasic['user_first_name']     =    $data['txt_first_name'];
        $inputUserBasic['user_last_name']      =    $data['txt_last_name'];
        // $inputUserBasic['user_email_id']     =    $data['txt_email'];
        $inputUserBasic['user_gender']         =    $data['radio_gender'];
        $inputUserBasic['user_country_id']     =    $data['select_country'];
        // $inputUserBasic['user_password']     =   password_hash($data['txt_password'], PASSWORD_DEFAULT, ['cost' => 12]);
        $inputUserBasic['user_status']         =    0;
        $inputUserBasic['user_deleted']        =    0;
        $inputUserBasic['user_status']         =    0;
        $inputUserBasic['user_deleted']        =    0;
        // $inputUserBasic['user_created_by']     =    'A';
        // $inputUserBasic['user_created_date']   =    gmdate("Y-m-d H:i:s");
        $inputUserBasic['user_type']           =    'U';
        $inputUserBasic['phone_number']           =   $data['txt_Phone'][0];

        $this->db->trans_start();

        $this->db->where('user_id', $userId);
        $this->db->update('user_table', $inputUserBasic);


        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        $auditArray                     =    array();
        $auditArray['admin_id']         =    $this->session->userdata('admin_id');
        $auditArray['module_id']        =     1;
        $auditArray['entity_id']        =     $userId;
        $auditArray['action_id']        =     2;
        $auditArray['audit_time']       =    gmdate("Y-m-d H:i:s");
        $auditArray['audit_note']       =    "User updation by admin module";
        $auditArray['menu_id']         =    3;
        $this->db->insert('admin_audit_trial', $auditArray);


        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        for ($i = 0; $i < count($data['select_city']); $i++) {
            $inputUserShiping                                  =    array();
            $inputUserShiping['user_shiping_details_city']     =    $data['select_city'][$i];
            $inputUserShiping['user_shiping_details_dial_code']=    $data['txt_dial'][$i];
            $inputUserShiping['user_shiping_details_phone']    =    $data['txt_Phone'][$i];
            $inputUserShiping['user_shiping_details_loc']      =    $data['txt_location'][$i];
            $inputUserShiping['user_shiping_details_street']   =    $data['txt_street'][$i];
            $inputUserShiping['user_shiping_details_building'] =    $data['txt_building'][$i];
            $inputUserShiping['user_shiping_details_landmark'] =    $data['txt_land_mark'][$i];
            $inputUserShiping['user_shiping_details_floorno']  =    $data['txt_floor'][$i];
            $inputUserShiping['user_shiping_details_flatno']   =    $data['txt_flat'][$i];
            $inputUserShiping['user_shiping_details_note']     =    $data['txt_shipping_note'][$i];
            $inputUserShiping['user_shiping_details_area']     =    $data['select_area'][$i]>0?$data['select_area'][$i]:0;
            $inputUserShiping['user_shiping_details_loc_type'] =    $data['select_location_type'][$i]>0?$data['select_location_type'][$i]:0;
            $inputUserShiping['user_shiping_details_latitude']     =    $data['latti'][$i];
            $inputUserShiping['user_shiping_details_longitude']     =    $data['longi'][$i];
            $inputUserShiping['user_shiping_country_id']     =    $data['select_country2'][$i];

            $inputUserShiping['first_name']     =    $data['txt_first_name'];
            $inputUserShiping['last_name']     =    $data['txt_last_name'];

            //  $inputUserShiping['user_shiping_country_id']     =    $data['select_city'][$i];
            $inputUserShiping['user_shiping_details_user_id']  =    $userId;

            if ($data['select_city'][$i]!="" && $data['txt_Phone'][$i]!="" && $data['txt_location'][$i]!="") {
                $t_record_id = $data['shipping_address_id'][$i];
                if ( $t_record_id > 0 ) {
                    $this->db->update('user_shiping_details', $inputUserShiping, ['user_shiping_details_id' => $t_record_id]);
                } else {
                    $this->db->insert('user_shiping_details', $inputUserShiping);
                }
            }
        }

        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }
      function deleteUserShippingAddressById( $id )
    {
        $this->db->where('shipping_address_id', $id);
        $count = $this->db->count_all_results('product_order_details');
        if ( $count > 0 ) {
            return 2;
        }

        $this->db->trans_start();

        $this->db->where('user_shiping_details_id', $id);
        $this->db->delete('user_shiping_details');

        $this->db->trans_complete();
        if ( $this->db->trans_status() === FALSE ) {
            return 0;
        }

        return 1;
    }
    function deleteUser($id)
    {

            $this->db->select('count(product_id) as count');
            $this->db->from('product c');
            $this->db->where('product_vender_id', $id);
            $query = $this->db->get();
           // echo $this->db->last_query();
        if ($query->row()->count>0) {
            return 3;
            exit;
        }
            $this->db->select('count(order_block_id) as count');
            $this->db->from('product_order_details c');
            $this->db->where('user_id', $id);
            $query = $this->db->get();
           // echo $this->db->last_query();
        if ($query->row()->count>0) {
            return 4;
            exit;
        }

             $user = $this->getUserType($id);
             $userType = $user->user_type;

        if ($userType=="U") {
             $module = 1;
        }
        if ($userType=="V") {
            $module = 2;
        }
        if ($userType=="D") {
            $module = 4;
        }
        if ($userType=="C") {
            $module = 3;
        }

            $this->db->trans_start();


            //admin audit trial //admin audit trial//admin audit trial//admin audit trial

            $auditArray                     =     array();
            $auditArray['admin_id']         =     $this->session->userdata('admin_id');
            $auditArray['module_id']        =     $module;
            $auditArray['entity_id']        =     $id;
            $auditArray['action_id']        =     3;
            $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
            $auditArray['audit_note']       =     "User deletion from admin module";
            $auditArray['menu_id']          =     3;

            $this->db->insert('admin_audit_trial', $auditArray);

            //admin audit trial //admin audit trial//admin audit trial//admin audit trial


              $this->db->where('user_id', $id);
              $this->db->delete('user_table');

              $this->db->where('user_shiping_details_user_id', $id);
              $this->db->delete('user_shiping_details');

              $this->db->where('user_id', $id);
              $this->db->delete('seller_details');

              /*$this->db->where('user_id', $id);
              $this->db->delete('driver_details');*/



             $this->db->trans_complete();


        if ($this->db->trans_status() === false) {
             return 0;
        } else {
              return 1;
        }
    }

    function getUserFulDetails($id)
    {
                //get shipping id from min
              $this->db->select('min(user_shiping_details_id) as min');
                                                                $this->db->from('user_shiping_details c');
                                                                $this->db->where('user_shiping_details_user_id', $id);
                                                                $query = $this->db->get();
                                                           //    echo $this->db->last_query();
        if ($query->row()->min>0) {
             $shippingid=$query->row()->min;
        }

            $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
         // if(getUserFulDetails>0)
          $this->db->select('c1.*,c2.*,u.*,s.*');
          $this->db->from('country c1');          
          $this->db->join('user_table u', '(c1.country_id =user_country_id) and (c1.country_language_code=1)', 'left');
          $this->db->join('city c2', '(u.user_city_id = c2.city_id) and (c2.city_language_code=1)', 'left');
          $this->db->join('user_shiping_details s', '(s.user_shiping_details_city =c2.city_id) AND (s.user_shiping_details_user_id=u.user_id) ', 'left');
          //$this->db->where('c1.country_language_code',$language);
         // $this->db->where('c2.city_language_code',$language);





        // if ($shippingid>0) {
        //     $this->db->where('s.user_shiping_details_id', $shippingid);
        //     $this->db->where('s.user_shiping_details_city =c2.city_id');
        // }
            $this->db->where('u.user_id', $id);
         // $this->db->order_by('c.category_id','desc');
          $query = $this->db->get();
            // echo $this->db->last_query();
          return $query->result();
    }
    function getUserFulAddresDetails($id)
    {
          $language =($this->session->userdata('language')?$this->session->userdata('language'):1);

          $sql =" select * from user_table u,user_shiping_details s,country c,city ct where

 u.user_id=user_shiping_details_user_id and user_shiping_country_id=c.country_id and user_shiping_details_city=ct.city_id and country_language_code=".$language." and
 city_language_code=".$language." and u.user_id=".$id." ";


         $rs            =            $this->db->query($sql);
        return    $result           =          $rs->result();
   /*
  $this->db->select('c1.*,c2.*,u.*,s.*');
  $this->db->from('country c1');
  $this->db->join('city c2','c1.country_id =c2.city_country_id','left');
  $this->db->join('user_table u','1=1','left');
  $this->db->join('user_shiping_details s','(s.user_shiping_details_city =c2.city_id) AND (s.user_shiping_details_user_id=u.user_id) ','left');
  $this->db->where('c1.country_language_code',$language);
  $this->db->where('c2.city_language_code',$language);
// $this->db->where('s.user_shiping_details_city =c2.city_id');
    $this->db->where('u.user_id',$id);
 // $this->db->order_by('c.category_id','desc');
  $query = $this->db->get();
//  echo $this->db->last_query();
  return $query->result();*/
    }
    function getUserFulDetails2($id)
    {
          $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
          $this->db->select('c1.*,c2.*,u.*,s.*');
          $this->db->from('country c1');
          $this->db->join('city c2', 'c1.country_id =c2.city_country_id', 'left');
          $this->db->join('user_table u', '1=1', 'left');
          $this->db->join('user_shiping_details s', '(s.user_shiping_details_city =c2.city_id) AND (s.user_shiping_details_user_id=u.user_id) ', 'left');
          $this->db->where('c1.country_language_code', $language);
          $this->db->where('c2.city_language_code', $language);
         $this->db->where('s.user_shiping_details_city =c2.city_id');
            $this->db->where('u.user_id', $id);
          $this->db->order_by('user_shiping_details_id', 'ASC');
          $query = $this->db->get();
       //  echo $this->db->last_query();
          return $query->result();
    }

    /**
     * [updateSeller description]
     * @param   [type] $updateArr [description]
     * @param   [type] $user_id   [description]
     * @return  [type]            [description]
     * @author Jitin Joseph <jitin.a2solution@gmail.com>
     * @created date              2018-09-15
     */
    function updateSeller($updateArr, $user_id)
    {

                $this->db->trans_start();



        if ($updateArr['verified_status']==1 || $updateArr['verified_status']==0) {
            if ($updateArr['verified_status']==1) {
                $action = 6;
            } else {
                 $action = 7;
            }
                //admin audit trial //admin audit trial//admin audit trial//admin audit trial

                   $auditArray                     =    array();
                   $auditArray['admin_id']         =    $this->session->userdata('admin_id');
                   $auditArray['module_id']        =    2;
                   $auditArray['entity_id']        =    $user_id;
                   $auditArray['action_id']        =    $action ;
                   $auditArray['audit_time']       =    gmdate("Y-m-d H:i:s");
                   $auditArray['audit_note']       =    "";
                   $auditArray['menu_id']          =    3;
                   $this->db->insert('admin_audit_trial', $auditArray);

                   //admin audit trial //admin audit trial//admin audit trial//admin audit trial
        }
        $this->db->where('user_id', $user_id);
        $this->db->update('seller_details', $updateArr);
        $this->db->trans_complete();


        if ($this->db->trans_status() === false) {
             return 0;
        } else {
            return 1;
        }
    }
    //---------------------------------------------------

    function approveUser()
    {

                        $userId          =  $_POST['id'];
                        $this->db->where('user_id', $userId);
                        $inputUserBasic['user_status']  =   $_POST['status'];
                        $this->db->update('user_table', $inputUserBasic);
                        $user = $this->getBasicUserDeatils($userId);

                       // print_r($user);
        if ($user->user_type=="V") {
            $module = 2;
        } else if ($user->user_type=="D") {
            $module = 4;
        } else if ($user->user_type=="C") {
            $module = 3;
        }
        if ($_POST['status']==1) {
            $action = 4;
        } else {
              $action = 5;
        }

                    //admin audit trial //admin audit trial//admin audit trial//admin audit trial

                            $auditArray                     =    array();
                            $auditArray['admin_id']         =    $this->session->userdata('admin_id');
                            $auditArray['module_id']        =    $module;
                            $auditArray['entity_id']        =    $userId;
                            $auditArray['action_id']        =    $action ;
                            $auditArray['audit_time']       =    gmdate("Y-m-d H:i:s");
                            $auditArray['audit_note']       =    "";
                            $auditArray['menu_id']          =    3;
                            $this->db->insert('admin_audit_trial', $auditArray);

                    //admin audit trial //admin audit trial//admin audit trial//admin audit trial


        if ($_POST['status']==1) {
            if ($user->user_type=="C" || $user->user_type=="V" || $user->user_type=="D") {
                                                                               $subject  =  "Welcome to Teyaar - Simply Sell and Buy! ";
                                                                               $to      =   $user->user_email_id;
                                                                               //$to      =  "syamca2s@gmail.com";
                                                                               $from    =  "info@teyaar.com";

                if ($user->user_type="V") {
                    $content ="Congratulations on successful registration. You can now proceed with logging into your account and adding products."  ;
                } else if ($user->user_type="D") {
                    $content ="Congratulations on successful registration. You can now proceed with logging into your account and shipping products."  ;
                } else if ($user->user_type="C") {
                    $content ="Congratulations on successful registration. You can now proceed with logging into your account and purchase/promote products." ;
                }


                                                                               $message ='<div style="background: #373242;max-width: 663px;
    margin: 0 auto;">
    <div style="background:url(http://a2itproducts.com/teyaar_final/images/logo_wht.png);background-size:cover;text-align:center;width:257px;height:100px;">

	</div>
   <div style="padding: 10px 20px">
		<div style="background: #fff;padding: 9px 30px;border-top: 7px solid #ef5b25;    padding-bottom: 0;overflow: hidden;margin: 20px 7px;border-radius: 0 0 3px 3px;">
			<h3 style="text-align: left;">'.$subject.'</h3>

			<p>Dear '.$user->user_first_name.',</p>
			<p>'.$content.'</p>

			<p style="margin-bottom:5px">Simply Sell and Buy!</p>
			<p style="margin:0">Teyaar.com</p>
			<span style="display: block;
    text-align: center;
    color: #000000a6;
    padding: 14px 0;
    font-size: 11px;">&copy 2018 Teyaar All rights reserved.</span>
		</div>
	</div>
</div>';


                $this->load->library("Email_teyaar");
                //$this->email_teyaar->SendEmail($message, $subject, $to);
            }
        }
                            return 1;
    }

    public function saveDriverDetails($data)
    {

        $inputUserBasic['user_first_name']     = $data['txt_first_name'];
        $inputUserBasic['user_last_name']      = $data['txt_last_name'];
        $inputUserBasic['user_email_id']       = $data['txt_email'];
        $inputUserBasic['user_gender']         = $data['radio_gender'];
        $inputUserBasic['user_country_id']     = $data['select_country'];
        $inputUserBasic['user_password']       = MD5($data['txt_password']);
        $inputUserBasic['user_status']         = 0;
        $inputUserBasic['user_deleted']        = 0;
        $inputUserBasic['user_status']         = 0;
        $inputUserBasic['user_deleted']        = 0;
        $inputUserBasic['user_created_by']     = 'S';
        $inputUserBasic['user_created_date']   = gmdate("Y-m-d H:i:s");
        $inputUserBasic['user_type']           = 'D';
        $inputUserBasic['user_custom_id']      = "";


        $email_row_count = $this->db->select('count(user_email_id) as count')
                                ->from('user_table c')
                                ->where('user_email_id', $data['txt_email'])
                                ->get()
                                ->row()
                                ->count;

        if ($email_row_count > 0) {
            return 3;
        }

        $config2['upload_path']     = $this->config->item('upload_path').$this->config->item('driver_document_upload_dir');
        echo json_encode($config2['upload_path']);exit;
        $config2['allowed_types']   = 'gif|jpg|jpeg|png|pdf|doc';
        $config2['encrypt_name']    = true;

        $this->load->library('upload', $config2);

        if (!$this->upload->do_upload('txt_driving_doc')) {
            return 4;
        } else {
            $arr_fields1['doument_name'] = $this->upload->data('file_name');
        }


        if (!$this->upload->do_upload('txt_doc_mulkiya')) {
            return 4;
        } else {
            $arr_fields1['mulkiya'] = $this->upload->data('file_name');
        }




        // $ext = pathinfo($driving_license_file, PATHINFO_EXTENSION);

        // $temp                   = explode(".",$_FILES["txt_driving_doc"]["name"]);
        // $driving_license_file   = time().".".$ext;
        // $filepath               = "uploads/driver_documents/".$driving_license_file;

        // move_uploaded_file($_FILES['txt_driving_doc']['tmp_name'],$filepath);

        // //mulkiya
        // $ext1       = pathinfo($mulkiya_file, PATHINFO_EXTENSION);
        // $temp1      = explode(".",$_FILES["txt_doc_mulkiya"]["name"]);
        // $mulkiya    = '000'.time().".".$ext1;
        // $filepath1  = "uploads/driver_documents/".$mulkiya;

        // move_uploaded_file($_FILES['txt_doc_mulkiya']['tmp_name'],$filepath1);

        $this->db->trans_start();
        $this->db->insert('user_table', $inputUserBasic);

        $arr_fields1['user_id']         = $this->db->insert_id();
        $arr_fields1['vehicle_no']      = $data['txt_vehicle_no'];
        $arr_fields1['street_name']     = $data['txt_street'];
        $arr_fields1['building_no']     = $data['txt_building'];
        $arr_fields1['mobile_no']       = $data['txt_Phone'];
        $arr_fields1['land_phone']      = "";
        $arr_fields1['location']        = $data['txt_location'];
        $arr_fields1['longitude']       = $data['longi'];
        $arr_fields1['latitude']        = $data['latti'];

        $arr_fields1['document_number'] = $data['txt_driving_doc_no'];
        //$arr_fields1['doument_name']    = $driving_license_file;
        $arr_fields1['city']            = $data['select_city'];

        $arr_fields1['license_exp_date']= date("Y-m-d", strtotime($data['txt_driving_doc_expiry']));
        $arr_fields1['mulkiya_exp_date']= date("Y-m-d", strtotime($data['txt_driving_doc_expiry']));

        $arr_fields1['country_id']      = $data['select_country'];
        $arr_fields1['vehicle_reg_no']  = $data['txt_vehicle_no'];
        //$arr_fields1['mulkiya']         = $mulkiya;
        $arr_fields1['vehicle_type_id'] = $data['select_vehicle_type'];

        $arr_fields1['added_by']        = 2;
        $arr_fields1['added_by_user_id']= (int) $this->session->userdata("user_id");

        $arr_fields1['driver_bank_id']      = $data['driver_bank_id'] ?? "";
        $arr_fields1['bank_account_number'] = $data['driver_bank_account_number'] ?? "";

        $this->db->insert('driver_details', $arr_fields1);

        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }

    public function updateDriverDetails($data)
    {

        $userId    =   $data['id'];

        $inputUserBasic['user_first_name']     = $data['txt_first_name'];
        $inputUserBasic['user_last_name']      = $data['txt_last_name'];
        $inputUserBasic['user_email_id']       = $data['txt_email'];
        $inputUserBasic['user_gender']         = $data['radio_gender'];
        $inputUserBasic['user_country_id']     = $data['select_country'];
        //$inputUserBasic['user_password']       = MD5($data['txt_password']);
        // $inputUserBasic['user_status']         = 0;
        // $inputUserBasic['user_deleted']        = 0;
        // $inputUserBasic['user_status']         = 0;
        // $inputUserBasic['user_deleted']        = 0;
        // $inputUserBasic['user_type']           = 'D';

        $email_row_count = $this->db->select('count(user_email_id) as count')
                                ->from('user_table c')
                                ->where('user_email_id', $data['txt_email'])
                                ->where('user_id <>', $userId, true)
                                ->get()
                                ->row()
                                ->count;

        if ($email_row_count > 0) {
            return 3;
        }

        $config2['upload_path']     = $this->config->item('upload_path').$this->config->item('driver_document_upload_dir');
        $config2['allowed_types']   = 'gif|jpg|jpeg|png|pdf|doc';
        $config2['encrypt_name']    = true;

        $this->load->library('upload', $config2);

        if (!empty($_FILES['txt_driving_doc']['name'])) {
            if (!$this->upload->do_upload('txt_driving_doc')) {
                return 4;
            } else {
                $arr_fields1['doument_name'] = $this->upload->data('file_name');
            }
        }


        if (!empty($_FILES['txt_doc_mulkiya']['name'])) {
            if (!$this->upload->do_upload('txt_doc_mulkiya')) {
                return 4;
            } else {
                $arr_fields1['mulkiya'] = $this->upload->data('file_name');
            }
        }


        // if(!empty($_FILES["txt_driving_doc"]["name"]) ) {
        //     $ext = pathinfo($driving_license_file, PATHINFO_EXTENSION);
        //     $temp                   = explode(".",$_FILES["txt_driving_doc"]["name"]);
        //     $driving_license_file   = time().".".$ext;
        //     $filepath               = "uploads/driver_documents/".$driving_license_file;

        //     move_uploaded_file($_FILES['txt_driving_doc']['tmp_name'],$filepath);


        //     $arr_fields1['doument_name']    = $driving_license_file;
        // }

        // //mulkiya
        // if(!empty($_FILES["txt_driving_doc"]["name"]) ) {

        //     $ext1       = pathinfo($mulkiya_file, PATHINFO_EXTENSION);
        //     $temp1      = explode(".",$_FILES["txt_doc_mulkiya"]["name"]);
        //     $mulkiya    = '000'.time().".".$ext1;
        //     $filepath1  = "uploads/driver_documents/".$mulkiya;

        //     move_uploaded_file($_FILES['txt_doc_mulkiya']['tmp_name'],$filepath1);

        //     $arr_fields1['mulkiya']         = $mulkiya;

        // }


        $this->db->trans_start();
        $this->db->where('user_id', $userId);
        $this->db->update('user_table', $inputUserBasic);

        $arr_fields1['vehicle_no']      = $data['txt_vehicle_no'];
        $arr_fields1['street_name']     = $data['txt_street'];
        $arr_fields1['building_no']     = $data['txt_building'];
        $arr_fields1['mobile_no']       = $data['txt_Phone'];
        $arr_fields1['land_phone']      = "";
        $arr_fields1['location']        = $data['txt_location'];
        $arr_fields1['longitude']       = $data['longi'];
        $arr_fields1['latitude']        = $data['latti'];

        $arr_fields1['document_number'] = $data['txt_driving_doc_no'];
        $arr_fields1['city']            = $data['select_city'];

        $arr_fields1['license_exp_date']= date("Y-m-d", strtotime($data['txt_driving_doc_expiry']));
        $arr_fields1['mulkiya_exp_date']= date("Y-m-d", strtotime($data['txt_doc_mulkiya_expiry']));

        $arr_fields1['country_id']      = $data['select_country'];
        $arr_fields1['vehicle_reg_no']  = $data['txt_vehicle_no'];
        $arr_fields1['vehicle_type_id'] = $data['select_vehicle_type'];


        $this->db->where('user_id', $userId);
        $this->db->update('driver_details', $arr_fields1);

        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }

    function saveStore($data)
    {

        $latitude   = "";
        $longitude  = "";
        $location   = "";

        $inputUserBasic['user_first_name']     = $data['txt_store'];
        $inputUserBasic['user_last_name']      = "";
        $inputUserBasic['user_email_id']       = $data['txt_email'];
        $inputUserBasic['user_gender']         = "0";//$data['radio_gender'];
        $inputUserBasic['user_country_id']     = $data['select_country'];
        $inputUserBasic['user_password']       = MD5($data['txt_password']);
        $inputUserBasic['user_status']         = 0;
        $inputUserBasic['user_deleted']        = 0;
        $inputUserBasic['user_status']         = 0;
        $inputUserBasic['user_deleted']        = 0;
        $inputUserBasic['user_created_by']     = 'A';
        $inputUserBasic['user_created_date']   = gmdate("Y-m-d H:i:s");
        $inputUserBasic['user_type']           = 'S'; //store
        $inputUserBasic['user_custom_id']      = "";//$data['txt_user_id'];


        $this->db->select('count(user_email_id) as count');
        $this->db->from('user_table c');
        $this->db->where('user_email_id', $data['txt_email']);

        $query = $this->db->get();

        if ($query->row()->count>0) {
            return 3;
            exit;
        }

        $this->db->select('count(user_custom_id) as count');
        $this->db->from('user_table c');
        $this->db->where('user_custom_id', $data['user_custom_id']);

        $query = $this->db->get();

        if ($query->row()->count>0) {
            return 4;
            exit;
        }

        $this->db->trans_start();
        $this->db->insert('user_table', $inputUserBasic);
        $insertId = $this->db->insert_id();

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial
        $auditArray                     =    array();
        $auditArray['admin_id']         =    $this->session->userdata('admin_id');
        $auditArray['module_id']        =    2;
        $auditArray['entity_id']        =    $insertId;
        $auditArray['action_id']        =    1;
        $auditArray['audit_time']       =    gmdate("Y-m-d H:i:s");
        $auditArray['audit_note']       =    "Store creation from admin module";
        $auditArray['menu_id']          =     3;
        $this->db->insert('admin_audit_trial', $auditArray);

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial




        $latitude   = $data['latti'];
        $longitude  = $data['longi'];
        $location   = $data['txt_location'];

        $inputUserShiping['city']             = $data['select_city'];
        $inputUserShiping['mobile_no']        = $data['txt_dialcode']."-".$data['txt_Phone'];
        $inputUserShiping['location']         = $data['txt_location'];
        $inputUserShiping['street_name']      = $data['txt_street'];
        $inputUserShiping['building_no']      = $data['txt_building'];


        $inputUserShiping['account_type']     = 0; //$data['select_acc_type'][$i]>0?$data['select_acc_type'][$i]:0;
        $inputUserShiping['mall_id']          = 0; //   $data['txt_mall'][$i]>0?$data['txt_mall'][$i]:1;

        $inputUserShiping['latitude']           = $data['latti'];
        $inputUserShiping['longitude']          = $data['longi'];
        $inputUserShiping['store_status']       = 0;
        $inputUserShiping['store_name']         = $data['txt_Store'];
        $inputUserShiping['store_name_arabic']  = "";
        $inputUserShiping['land_phone']         = "";

        $inputUserShiping['store_created_by']   = 1;
        $inputUserShiping['store_created_date'] = gmdate("Y-m-d H:i:s");

        if ($_FILES["txt_logo"]["name"]!="") {

            $digits     =  6;
            $randomNo   = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

            $filename2  = $_FILES["txt_logo"]["name"];
            $file_ext2  = pathinfo($filename2, PATHINFO_EXTENSION);


            $config2['upload_path']     =  $this->config->item('upload_path').'vendor_images/';
            $config2['allowed_types']   =  'gif|jpg|png|pdf|doc|jpeg';
            $config2['max_size']        =  1000;
            $config2['file_name']       =  $randomNo.".".$file_ext2;


            $this->load->library('upload', $config2);


            if (! $this->upload->do_upload('txt_logo')) {
                $data['status'] = 0;
                $data['errors'] = array(
                                        'txt_logo' => "File upload failed",
                                    );
                echo json_encode($data);
                exit();
            }
            else {
                $inputUserShiping['seller_logo']       = $config2['file_name'];
            }
        }


        $inputUserShiping['user_id']  =    $insertId;

        $this->db->insert('seller_details', $inputUserShiping);
        $this->db->trans_complete();



        if ($this->db->trans_status() === false)
            return 0;

        else
            return 1;

    }


    function updateStore($data) {

        $userId     =   $data['id'];

        $latitude   = "";
        $longitude  = "";
        $location   = "";

        $inputUserBasic['user_first_name']      = $data['txt_first_name'];
        $inputUserBasic['user_last_name']       = $data['txt_last_name'];
        // $inputUserBasic['user_email_id']     = $data['txt_email'];
        $inputUserBasic['user_gender']          = $data['radio_gender'];
        $inputUserBasic['user_country_id']      = $data['select_country'];

        if($data['txt_password'] != "#NOPASSCHANGE123#")
            $inputUserBasic['user_password']    = MD5($data['txt_password']);


        $this->db->trans_start();


        $this->db->where('user_id', $userId);
        $this->db->update('user_table', $inputUserBasic);


        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        $auditArray                     =    array();
        $auditArray['admin_id']         =    $this->session->userdata('admin_id');
        $auditArray['module_id']        =    2;
        $auditArray['entity_id']        =     $userId;
        $auditArray['action_id']        =    2;
        $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
        $auditArray['audit_note']       =     "Store updation from admin module";
        $auditArray['menu_id']          =     3;

        $this->db->insert('admin_audit_trial', $auditArray);

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial


        $latitude   = $data['latti'];
        $longitude  = $data['longi'];
        $location   = $data['txt_location'];

        $inputUserShiping['city']             = $data['select_city'];
        $inputUserShiping['mobile_no']        = $data['txt_dialcode']."-".$data['txt_Phone'];
        $inputUserShiping['location']         = $data['txt_location'];


        $inputUserShiping['latitude']         = $data['latti'];
        $inputUserShiping['longitude']        = $data['longi'];


        $inputUserShiping['store_name']        = $data['txt_Store'];
        $inputUserShiping['store_name_arabic'] = $data['txt_Store_Arabic'][$i];


        $inputUserShiping['store_updated_by']  =    1;
        $inputUserShiping['store_updated_date']        =    gmdate("Y-m-d H:i:s");

        if ($_FILES["txt_logo"]["name"]!="") {

            $digits     =  6;
            $randomNo   = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txt_doc"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path']          =  $this->config->item('upload_path').'vendor_images/';
            $config2['allowed_types']        =  'gif|jpg|png|pdf|doc';
            $config2['max_size']             =  1000;
            // $config2['max_width']            =  1024;
            // $config2['max_height']           =  768;
            $config2['file_name']            =  $randomNo.".".$file_ext2;

            $this->load->library('upload', $config2);


            if (! $this->upload->do_upload('txt_doc')) {
                    //die("file upload failed");
                    $data['status'] = 0;
                    $data['errors'] = array(
                                        'txt_logo' => "File upload failed",
                                    );
                    echo json_encode($data);
                    exit();
            }
            else {
                $inputUserShiping['seller_logo'] = $config2['file_name'];
            }
        }


        $this->db->where('user_id', $userId);
        $this->db->update('seller_details', $inputUserShiping);


        $this->db->trans_complete();



        if ($this->db->trans_status() === false)
             return 0;
        else
              return 1;

    }

    function saveVender($data)
    {
        $latitude   = "";
        $longitude  = "";
        $location  = "";

        $inputUserBasic['user_first_name']     =    $data['txt_first_name'];
        $inputUserBasic['user_last_name']      =    $data['txt_last_name'];
        $inputUserBasic['user_email_id']       =    $data['txt_email'];
        $inputUserBasic['user_gender']         =    $data['radio_gender'];
        $inputUserBasic['user_country_id']     =    $data['select_country'];
        $inputUserBasic['user_password']       =    password_hash($data['txt_password'], PASSWORD_DEFAULT, ['cost' => 12]);
        $inputUserBasic['user_status']         =    0;
        $inputUserBasic['user_deleted']        =    0;
        $inputUserBasic['user_status']         =    0;
        $inputUserBasic['user_deleted']        =    0;
        $inputUserBasic['user_created_by']     =    'A';
        $inputUserBasic['user_created_date']   =    gmdate("Y-m-d H:i:s");
        $inputUserBasic['user_type']           =    'V';
        $inputUserBasic['user_custom_id']      =    $data['txt_user_id'];
        $inputUserBasic['phone_verified']      =    $data['phone_verified'] ?? 0;

        $this->db->select('count(user_email_id) as count');
        $this->db->from('user_table c');
        $this->db->where('user_email_id', $data['txt_email']);
        $query = $this->db->get();

        // echo $this->db->last_query();
        if ($query->row()->count>0) {
            return 3;
            exit;
        }
            $this->db->select('count(user_custom_id) as count');
            $this->db->from('user_table c');
            $this->db->where('user_custom_id', $data['user_custom_id']);
            $query = $this->db->get();
           // echo $this->db->last_query();
        if ($query->row()->count>0) {
            return 4;
            exit;
        }

        $this->db->trans_start();

        $this->db->insert('user_table', $inputUserBasic);
        $insertId = $this->db->insert_id();

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial
        $auditArray                     =    array();
        $auditArray['admin_id']         =    $this->session->userdata('admin_id');
        $auditArray['module_id']        =    2;
        $auditArray['entity_id']        =    $insertId;
        $auditArray['action_id']        =    1;
        $auditArray['audit_time']       =    gmdate("Y-m-d H:i:s");
        $auditArray['audit_note']       =    "vendor creation from admin module";
        $auditArray['menu_id']          =     3;
        $this->db->insert('admin_audit_trial', $auditArray);
        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        for ($i=0; $i<count($data['select_city']); $i++) {
            $latitude   = $data['latti'][$i];
            $longitude  = $data['longi'][$i];
            $location  = $data['txt_location'][$i];


            $inputUserShiping['city']             =    $data['select_city'][$i];
            $inputUserShiping['mobile_no']        =    $data['txt_dialcode'][$i]."-".$data['txt_Phone'][$i];
            $inputUserShiping['location']         =    $data['txt_location'][$i];
            $inputUserShiping['street_name']      =    $data['txt_street'][$i];
            $inputUserShiping['building_no']      =    $data['txt_building'][$i];

            //$inputUserShiping['user_shiping_details_area']     =    $data['select_area'][$i]>0?$data['select_area'][$i]:0;
            $inputUserShiping['account_type']     =    $data['select_acc_type'][$i]>0?$data['select_acc_type'][$i]:0;
            $inputUserShiping['mall_id']     =    $data['txt_mall'][$i]>0?$data['txt_mall'][$i]:1;

            $inputUserShiping['latitude']         =    $data['latti'][$i];
            $inputUserShiping['longitude']        =    $data['longi'][$i];
            $inputUserShiping['store_status']        =    0;
            $inputUserShiping['store_name']        =    $data['txt_Store'][$i];
            $inputUserShiping['store_name_arabic']  =    $data['txt_Store_Arabic'][$i];
            $inputUserShiping['land_phone']        =    $data['txt_Land_Phone'][$i];

            $inputUserShiping['store_created_by']  =    1;
            $inputUserShiping['store_created_date']        =    gmdate("Y-m-d H:i:s");

            if ($_FILES["txt_doc"]["name"]!="") {
                $digits   =  6;
                $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

                $filename2 = $_FILES["txt_doc"]["name"];
                $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

                $config2['upload_path']          =  $this->config->item('upload_path').'vendor_images/';
                $config2['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
                $config2['max_size']             =  1000;
                //$config2['max_width']            =  1024;
                //$config2['max_height']           =  768;
                $config2['file_name']            =  $randomNo.".".$file_ext2;

                //$this->load->library('upload', $config2);
                    $this->load->library('upload', $config2);
                // $this->upload->initialize($config2);

                if (! $this->upload->do_upload('txt_doc')) {
                    $data['status'] = 0;
                    $data['errors'] = array(
                    'txt_doc' => "File upload failed",
                    );
                    echo json_encode($data);
                    exit();
                } else {
                    $inputUserShiping['document_number']  =    $data['txt_doc_no'][$i];
                    $inputUserShiping['document_type_id']     =    $data['select_doc_type'][$i]>0?$data['select_doc_type'][$i]:0;
                    $inputUserShiping['doument_name']  =    $config2['file_name'];
                }
            }

            $inputUserShiping['user_id']  = $insertId;
            $inputUserShiping['about_seller_desc']          =    $data['txt_about_desc'] ?? '';
            $inputUserShiping['about_seller_desc_arb']      =    $data['txt_about_desc_arabic'] ?? '';
            $inputUserShiping['seller_commission']          = $data['seller_commission'] ?? 0;
            $inputUserShiping['delivery_time_min']          = $data['delivery_time_min'] ?? 0;
            $inputUserShiping['delivery_time_max']          = $data['delivery_time_max'] ?? 0;
            $inputUserShiping['seller_bank_id']             = $data['seller_bank_id'] ?? "";
            $inputUserShiping['bank_account_number']        = $data['bank_account_number'] ?? "";
            $inputUserShiping['bank_ifsc_code']             = $data['bank_ifsc_code'] ?? "";
            $inputUserShiping['bank_swift_code']            = $data['bank_swift_code'] ?? "";

            $this->db->insert('seller_details', $inputUserShiping);
        }

        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }

    function getSellerDetails($data)
    {
         $query = $this->db->order_by('seller_details_id', 'ASC')->get_where('seller_details', $data);
              //$this->db->order_by('country_language_code','ASC');
             //  echo $this->db->last_query();
              return $query->result();
    }
    function updateVender($data)
    {
        $userId    =   $data['id'];

        $latitude   = "";
        $longitude  = "";
        $location  = "";

        $inputUserBasic['user_first_name']     =    $data['txt_first_name'];
        $inputUserBasic['user_last_name']      =    $data['txt_last_name'];
        // $inputUserBasic['user_email_id']     =    $data['txt_email'];
        $inputUserBasic['user_gender']         =    $data['radio_gender'];
        $inputUserBasic['user_country_id']     =    $data['select_country'];
        // $inputUserBasic['user_password']     =    MD5($data['txt_password']);
        $inputUserBasic['user_status']         =    0;
        $inputUserBasic['user_deleted']        =    0;
        $inputUserBasic['user_status']         =    0;
        $inputUserBasic['user_deleted']        =    0;
        // $inputUserBasic['user_created_by']     =    'A';
        // $inputUserBasic['user_created_date']   =    gmdate("Y-m-d H:i:s");
        $inputUserBasic['user_type']           =    'V';

        $this->db->trans_start();

        $this->db->where('user_id', $userId);
        $this->db->update('user_table', $inputUserBasic);

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial
        $auditArray                     =    array();
        $auditArray['admin_id']         =    $this->session->userdata('admin_id');
        $auditArray['module_id']        =    2;
        $auditArray['entity_id']        =     $userId;
        $auditArray['action_id']        =    2;
        $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
        $auditArray['audit_note']       =     "vendor updation from admin module";
        $auditArray['menu_id']          =     3;
        $this->db->insert('admin_audit_trial', $auditArray);
        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        for ($i=0; $i<count($data['select_city']); $i++) {
            $latitude   = $data['latti'][$i];
            $longitude  = $data['longi'][$i];
            $location  = $data['txt_location'][$i];
            $inputUserShiping['city']             =    $data['select_city'][$i];
            $inputUserShiping['city']             =    $data['select_city'][$i];
            $inputUserShiping['mobile_no']        =    $data['txt_dialcode'][$i]."-".$data['txt_Phone'][$i];
            $inputUserShiping['location']         =    $data['txt_location'][$i];
            $inputUserShiping['street_name']      =    $data['txt_street'][$i];
            $inputUserShiping['building_no']      =    $data['txt_building'][$i];

            //$inputUserShiping['user_shiping_details_area']     =    $data['select_area'][$i]>0?$data['select_area'][$i]:0;
            $inputUserShiping['account_type']     =    $data['select_acc_type'][$i]>0?$data['select_acc_type'][$i]:0;
            $inputUserShiping['mall_id']     =    $data['txt_mall'][$i]>0?$data['txt_mall'][$i]:1;

            $inputUserShiping['latitude']         =    $data['latti'][$i];
            $inputUserShiping['longitude']        =    $data['longi'][$i];
            $inputUserShiping['store_status']        =    0;
            $inputUserShiping['store_name']        =    $data['txt_Store'][$i];
            $inputUserShiping['store_name_arabic']        =    $data['txt_Store_Arabic'][$i];
            $inputUserShiping['land_phone']        =    $data['txt_Land_Phone'][$i];

            $inputUserShiping['store_updated_by']  =    1;
            $inputUserShiping['store_updated_date']        =    gmdate("Y-m-d H:i:s");

            if ($_FILES["txt_doc"]["name"]!="") {
                $digits   =  6;
                $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

                $filename2 = $_FILES["txt_doc"]["name"];
                $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

                $config2['upload_path']          =  $this->config->item('upload_path').'vendor_images/';
                $config2['allowed_types']        =  'gif|jpg|png|pdf|doc';
                $config2['max_size']             =  1000;
                $config2['max_width']            =  1024;
                $config2['max_height']           =  768;
                $config2['file_name']            =  $randomNo.".".$file_ext2;

                //$this->load->library('upload', $config2);
                    $this->load->library('upload', $config2);
                // $this->upload->initialize($config2);

                if (! $this->upload->do_upload('txt_doc')) {
                    //die("file upload failed");
                    $data['status'] = 0;
                    $data['errors'] = array(
                    'txt_doc' => "File upload failed",
                    );
                    echo json_encode($data);
                    exit();
                } else {
                    $inputUserShiping['doument_name']     =    $config2['file_name'];
                }
            }

            $inputUserShiping['document_number']            = $data['txt_doc_no'][$i];
            $inputUserShiping['document_type_id']           = $data['select_doc_type'][$i] > 0 ? $data['select_doc_type'][$i] : 0;
            $inputUserShiping['about_seller_desc']          = $data['txt_about_desc'] ?? '';
            $inputUserShiping['about_seller_desc_arb']      = $data['txt_about_desc_arabic'] ?? '';
            $inputUserShiping['seller_commission']          = $data['seller_commission'] ?? 0;
            $inputUserShiping['delivery_time_min']          = $data['delivery_time_min'] ?? 0;
            $inputUserShiping['delivery_time_max']          = $data['delivery_time_max'] ?? 0;
            $inputUserShiping['seller_bank_id']             = $data['seller_bank_id'] ?? "";
            $inputUserShiping['bank_account_number']        = $data['bank_account_number'] ?? "";
            $inputUserShiping['bank_ifsc_code']             = $data['bank_ifsc_code'] ?? "";
            $inputUserShiping['bank_swift_code']            = $data['bank_swift_code'] ?? "";

            $this->db->where('user_id', $userId);
            $this->db->update('seller_details', $inputUserShiping);
        }

        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }

    public function generateKandoraProducts( $user_id )
    {
        if (! empty($user_id) ) {
            $category_uid = $this->config->item('kandora_parent_category_uid');

            $kandora_prices = $this->input->post('kandora_price');
            $kandora_cash_points = $this->input->post('kandora_cash_point');
            if ( empty($kandora_prices) ) {
                return FALSE;
            }

            $sub_categories = $this->db->select('DISTINCT ON (sub_cat.category_id) sub_cat.category_id, sub_cat.category_uid, sub_cat.category_parent_id', TRUE)
                                       ->from('category sub_cat')
                                       ->join('category main_cat', 'sub_cat.category_parent_id = main_cat.category_id', 'inner')
                                       ->where('sub_cat.category_parent_id !=', 0)
                                       ->where('main_cat.category_uid', $category_uid)
                                       ->get()->result_array();

            $main_categories    = array_column($sub_categories, 'category_parent_id');
            $main_categories    = array_unique(array_filter($main_categories));
            $sub_categories     = array_column($sub_categories, 'category_id', 'category_uid');
            foreach ($sub_categories as $s_uid => $s_id) {
                $cat_arr[]=$s_id;
            }
            $products_master = array();
            $products = $this->db->select('DISTINCT ON (pattr.product_attribute_id) pattr.product_attribute_id, pattr.product_id, cat.category_uid')
                              ->from('product_attribute pattr')
                              ->join('product p', 'pattr.product_id = p.product_id', 'left')
                              ->join('product_category pcat', 'p.product_id = pcat.product_id', 'left')
                              ->join('category cat', 'pcat.category_id = cat.category_id', 'left')
                              ->where('p.is_kandora', 1)
                              ->where_in('pcat.category_id', $cat_arr)
                              ->where('p.product_vender_id', $user_id)
                              ->where('cat.category_language_code', 1)
                              ->get()->result_array();
            if (! empty($products) ) {
                $products_master = array_column($products, 'product_id', 'category_uid');
                $products = array_column($products, 'product_attribute_id', 'category_uid');
            }

            // Already generated
            if ( count($products) > 0 ) {
                $this->db->update('product', ['product_status' => 1], ['product_vender_id' => $user_id, 'is_kandora' => 1]);

                foreach ($products_master as $t_cat_id => $t_product_id) {
                    $t_cash_point = $kandora_cash_points[$t_cat_id] ?? 0;
                    $this->db->update('product', ['cash_points' => $t_cash_point], ['product_id' => $t_product_id]);
                }

                foreach ($sub_categories as $s_uid => $s_id) {
                    $t_price = $kandora_prices[$s_uid] ?? 0;
                    $t_row_id = $products[$s_uid] ?? NULL;
                    if (! $t_row_id) continue;

                    $this->db->update('product_attribute', ['regular_price' => $t_price, 'sale_price' => $t_price], ['product_attribute_id' => $t_row_id]);
                }
            } else {
                $this->config->load('kandora');
                $product_templates = $this->config->item('kandora');
                foreach ($product_templates as $key => $tmpl) {
                    $product_data = array_merge([
                        'is_kandora' => 1,
                        'product_type' => 1,
                        'product_vender_id' => $user_id,
                        'product_sale_from' => date('Y-m-d'),
                        'product_sale_to' => '2037-12-31',
                        'product_status' => 1,
                        'product_vendor_status' => 1,
                        'product_gender' => 'm',
                        'cash_points' => $kandora_cash_points[$key] ?? 0,
                    ], $tmpl);
                    $this->db->insert('product', $product_data);
                    $product_id = $this->db->insert_id();

                    $product_categories = [];
                    foreach ($main_categories as $t_cat_id) {
                        $product_categories[] = [
                            'product_id' => $product_id,
                            'category_id' => $t_cat_id,
                        ];
                    }
                    $t_cat_id = $sub_categories[$key] ?? 0;
                    if ( $t_cat_id > 0 ) {
                        $product_categories[] = [
                            'product_id' => $product_id,
                            'category_id' => $t_cat_id,
                        ];
                    }
                    $this->db->insert_batch('product_category', $product_categories);

                    $product_attribute = [
                        'product_id' => $product_id,
                        'allow_back_order' => 1,
                        'sold_individually' => 1,
                        'image' => $product_data['product_image'] ?? '',
                        'sale_price' => $kandora_prices[$key] ?? 0,
                        'regular_price' => $kandora_prices[$key] ?? 0,
                    ];
                    $this->db->insert('product_attribute', $product_attribute);
                }
            }

        }
        return TRUE;
    }

    public function disableKandoraProducts( $user_id )
    {
        if (! empty($user_id) ) {
            $this->db->update('product', ['product_status' => 0], ['product_vender_id' => $user_id, 'is_kandora' => 1]);
            return $this->db->affected_rows() > 0;
        }
        return TRUE;
    }

    public function getVendorKandoraPrices( $user_id )
    {
        $this->db->select('pattr.sale_price, cat.category_uid');
        $this->db->from('product p');
        $this->db->join('product_attribute pattr', 'p.product_id = pattr.product_id', 'left');
        $this->db->join('product_category pcat', 'p.product_id = pcat.product_id', 'left');
        $this->db->join('category cat', 'pcat.category_id = cat.category_id', 'left');
        $this->db->where('p.is_kandora', 1);
        $this->db->where('p.product_vender_id', $user_id);
        $this->db->where('cat.category_language_code', 1);
        $prices = $this->db->get()->result_array();
        if (! empty($prices) ) {
            $prices = array_column($prices, 'sale_price', 'category_uid');
        }
        return $prices;
    }

    public function getVendorKandoraCashPoints( $user_id )
    {
        $this->db->select('p.cash_points, cat.category_uid');
        $this->db->from('product p');
        $this->db->join('product_category pcat', 'p.product_id = pcat.product_id', 'left');
        $this->db->join('category cat', 'pcat.category_id = cat.category_id', 'left');
        $this->db->where('p.is_kandora', 1);
        $this->db->where('p.product_vender_id', $user_id);
        $this->db->where('cat.category_language_code', 1);
        $prices = $this->db->get()->result_array();
        if (! empty($prices) ) {
            $prices = array_column($prices, 'cash_points', 'category_uid');
        }
        return $prices;
    }

    public function getVendorKandoraImages( $user_id )
    {
        $this->db->select('pattr.image, cat.category_uid');
        $this->db->from('product p');
        $this->db->join('product_attribute pattr', 'p.product_id = pattr.product_id', 'left');
        $this->db->join('product_category pcat', 'p.product_id = pcat.product_id', 'left');
        $this->db->join('category cat', 'pcat.category_id = cat.category_id', 'left');
        $this->db->where('p.is_kandora', 1);
        $this->db->where('p.product_vender_id', $user_id);
        $this->db->where('cat.category_language_code', 1);
        $prices = $this->db->get()->result_array();
        if (! empty($prices) ) {
            $prices = array_column($prices, 'image', 'category_uid');
        }
        return $prices;
    }

    function getVenderFulDetails($id)
    {
          $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
          $this->db->select('c1.*,c2.*,u.*,s.*');
          $this->db->from('country c1');
          $this->db->join('city c2', 'c1.country_id =c2.city_country_id', 'left');
          $this->db->join('user_table u', 'c1.country_id =u.user_country_id', 'left');
          $this->db->join('seller_details s', '(s.city =c2.city_id) AND (s.user_id=u.user_id) AND (c2.city_language_code='.$language.') ', 'left');
          $this->db->where('c1.country_language_code', $language);
          $this->db->where('c2.city_language_code', $language);
          $this->db->where('s.city =c2.city_id');
            $this->db->where('u.user_id', $id);
         // $this->db->order_by('c.category_id','desc');
          $query = $this->db->get();
          //echo $this->db->last_query();
          return $query->result();
    }


    public function getVenderCondition()
    {
        $this->db->select('*,(select count(distinct(pod.order_block_id)) from product_order_details pod join product_order_history poh on poh.order_block_id=pod.order_block_id left join product on product.product_id=poh.product_id left join services on services.service_id=poh.service_id where product.product_vender_id=u.user_id  )::text as order_count,(select count(distinct(pod.order_block_id)) from product_order_details pod join product_order_history poh on poh.order_block_id=pod.order_block_id left join product on product.product_id=poh.product_id left join services on services.service_id=poh.service_id where  services.service_vendor_user_id=u.user_id  )::text as service_count');
        $this->db->from('user_table u');
        $this->db->join('seller_details s', 'u.user_id = s.user_id', 'left');
        $this->db->where('u.user_type', 'V');
        $this->db->where('s.user_id !=', NULL);
        $this->db->order_by('u.user_id', 'desc');
        $query = $this->db->get();

        return $query->result();
    }

    public function getVendorByUserId( $userId )
    {
        $language = ($this->session->userdata('language')?$this->session->userdata('language'):1);

        $this->db->select('*');
        $this->db->from('user_table u');
        $this->db->join('seller_details s', 'u.user_id = s.user_id', 'left');
        $this->db->join('(SELECT * FROM country WHERE country_language_code = '. $this->db->escape($language) .') country', 'u.user_country_id = country.country_id', 'left');
        $this->db->join('(SELECT * FROM city WHERE city_language_code = '. $this->db->escape($language) .') ct', 's.city = ct.city_id', 'left');
        $this->db->where('u.user_type', 'V');
        $this->db->where('u.user_id', $userId);
        $query = $this->db->get();

        return $query->result();
    }

    public function getShopList()
    {

          $this->db->select('*');
          $this->db->from('user_table u');
          $this->db->join('seller_details s', 'u.user_id =s.user_id', 'left');
          $this->db->where("u.user_type ='S'");
          $this->db->order_by('u.user_id', 'desc');
          $query = $this->db->get();

              return $query->result();
    }


    function saveDriver($data)
    {
        $this->db->select('count(user_email_id) as count');
        $this->db->from('user_table c');
        $this->db->where('user_email_id', $data['txt_email']);
        $query = $this->db->get();
        // echo $this->db->last_query();
        if ($query->row()->count>0) {
            return 3;
            exit;
        }

        $this->db->select('count(user_custom_id) as count');
        $this->db->from('user_table c');
        $this->db->where('user_custom_id', $data['user_custom_id']);
        $query = $this->db->get();
        // echo $this->db->last_query();
        if ($query->row()->count>0) {
            return 4;
            exit;
        }

        $inputUserBasic['user_first_name']     =    $data['txt_first_name'];
        $inputUserBasic['user_last_name']      =    $data['txt_last_name'];
        $inputUserBasic['user_email_id']       =    $data['txt_email'];
        $inputUserBasic['user_gender']         =    $data['radio_gender'];
        $inputUserBasic['user_country_id']     =    $data['select_country'];
        $inputUserBasic['user_password']       =    MD5($data['txt_password']);
        $inputUserBasic['user_status']         =    0;
        $inputUserBasic['user_deleted']        =    0;
        $inputUserBasic['user_created_by']     =    'A';
        $inputUserBasic['user_created_date']   =    gmdate("Y-m-d H:i:s");
        $inputUserBasic['user_type']           =    'D';
        $inputUserBasic['user_custom_id']      =   $data['txt_user_id'];
        $inputUserBasic['phone_verified']      =   $data['phone_verified'] ?? 0;

        if ( $_FILES["txt_image"]["name"] != "" ) {
            $digits   =  6;
            $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

            $filename = $_FILES["txt_image"]["name"];
            $file_ext = pathinfo($filename, PATHINFO_EXTENSION);

            $config2['upload_path']          =  'uploads/driver_images';
            $config2['allowed_types']        =  'gif|jpg|png|jpeg';
            $config2['max_size']             =  1000;
            $config2['max_width']            =  300;
            $config2['max_height']           =  300;
            $config2['file_name']            =  $randomNo.".".$file_ext;
            //echo json_encode($config2['upload_path']);exit;
            //$this->load->library('upload', $config2);
            $this->load->library('upload', $config2);
            $this->upload->initialize($config2);

            if (! $this->upload->do_upload('txt_image')) {
                $data['status'] = 0;
                $data['errors'] = array(
                    'txt_image' => $this->upload->display_errors(),
                );
                echo json_encode($data);
                exit();
            } else {
                $inputUserBasic['image'] = $config2['file_name'];
            }
        }

        $this->db->trans_start();
        $this->db->insert('user_table', $inputUserBasic);
        $insertId = $this->db->insert_id();

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial
        $auditArray                     =    array();
        $auditArray['admin_id']         =    $this->session->userdata('admin_id');
        $auditArray['module_id']        =     4;
        $auditArray['entity_id']        =     $insertId;
        $auditArray['action_id']        =     1;
        $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
        $auditArray['audit_note']       =     "driver creation from admin module";
        $auditArray['menu_id']          =     3;
        $this->db->insert('admin_audit_trial', $auditArray);
        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        for ( $i = 0; $i < count($data['select_city']); $i++ ) {
            $inputUserShiping['city']             =    $data['select_city'][$i] ?? "";
            $inputUserShiping['mobile_no']        =    $data['txt_dialcode'][$i]."-".$data['txt_Phone'][$i];
            $inputUserShiping['location']         =    $data['txt_location'][$i] ?? "";
            $inputUserShiping['street_name']      =    $data['txt_street'][$i] ?? "";
            // $inputUserShiping['building_no']      =    $data['txt_building'][$i] ?? "";
            $inputUserShiping['latitude']          =    $data['latti'][$i] ?? "";
            $inputUserShiping['longitude']         =    $data['longi'][$i] ?? "";
            $inputUserShiping['vehicle_no']        =    $data['txt_veh_no'][$i] ?? "";
            // $inputUserShiping['land_phone']        =    $data['txt_Land_Phone'][$i] ?? NULL;
            $inputUserShiping['document_number']   =    $data['txt_License'][$i] ?? "";
            // $inputUserShiping['vehicle_type_id']   =    $data['vehicle_type'][$i] ?? "";
            $inputUserShiping['vehicle_reg_no']    =    $data['txt_veh_no'][$i] ?? "";
            // $inputUserShiping['emirates_id_number'] =   $data['txt_emirates_id'][$i] ?? "";
            // $inputUserShiping['driver_earning_percentage'] = $data['txt_earning_percentage'][$i] ?? "";

            if ($_FILES["txt_doc"]["name"]!="") {
                $digits   =  6;
                $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

                $filename2 = $_FILES["txt_doc"]["name"];
                $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

                $config2['upload_path']          =  'uploads/driver_documents';
                $config2['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
                $config2['max_size']             =  1000;
                //$config2['max_width']            =  1024;
                // $config2['max_height']           =  768;
                $config2['file_name']            =  $randomNo.".".$file_ext2;

                //$this->load->library('upload', $config2);
                $this->load->library('upload', $config2);
                $this->upload->initialize($config2);

                if (! $this->upload->do_upload('txt_doc')) {
                //die("file upload failed");
                    $data['status'] = 0;
                    $data['errors'] = array(
                        'txt_doc' => $this->upload->display_errors(),
                    );
                    echo json_encode($data);
                    exit();
                } else {
                 // $inputUserShiping['document_number']      =    $data['txt_doc_no'][$i];
                    $inputUserShiping['document_type_id']     =    $data['select_doc_type'][$i] ?? 0;
                    $inputUserShiping['doument_name']         =    $config2['file_name'];
                }
            }

            if ($_FILES["txt_doc2"]["name"]!="") {
                $digits   =  6;
                $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

                $filename2 = $_FILES["txt_doc2"]["name"];
                $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

                $config2['upload_path']          =  'uploads/driver_documents';
                $config2['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
                $config2['max_size']             =  1000;
                // $config2['max_width']            =  1024;
                // $config2['max_height']           =  768;
                $config2['file_name']            =  $randomNo.".".$file_ext2;

                //$this->load->library('upload', $config2);
                $this->load->library('upload', $config2);
                $this->upload->initialize($config2);

                if (! $this->upload->do_upload('txt_doc2')) {
                  //die("file upload failed");
                    $data['status'] = 0;
                    $data['errors'] = array(
                        'txt_doc2' => $this->upload->display_errors(),
                    );
                    echo json_encode($data);
                    exit();
                } else {
                 // $inputUserShiping['vehicle_reg_no']         =    $data['txt_doc_no'][$i];
                  //$inputUserShiping['document_type_id']     =    $data['select_doc_type'][$i]>0?$data['select_doc_type'][$i]:0;
                    $inputUserShiping['mulkiya']                =    $config2['file_name'];
                }
            }

            if ( $_FILES["txt_doc3"]["name"] != "" ) {
                $digits   =  6;
                $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

                $filename3 = $_FILES["txt_doc3"]["name"];
                $file_ext3 = pathinfo($filename3, PATHINFO_EXTENSION);

                $config2['upload_path']          =  'uploads/driver_documents';
                $config2['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
                $config2['max_size']             =  1000;
                $config2['file_name']            =  $randomNo.".".$file_ext3;

                $this->load->library('upload', $config2);
                $this->upload->initialize($config2);

                if (! $this->upload->do_upload('txt_doc3')) {
                    $data['status'] = 0;
                    $data['errors'] = array(
                        'txt_doc3' => $this->upload->display_errors(),
                    );
                    echo json_encode($data);
                    exit();
                } else {
                    $inputUserShiping['emirates_id_file'] = $config2['file_name'];
                }
            }

            $inputUserShiping['driver_bank_id']      = $data['driver_bank_id'] ?? "";
            $inputUserShiping['bank_account_number'] = $data['driver_bank_account_number'] ?? "";
            $inputUserShiping['bank_ifsc_code']      = $data['driver_bank_ifsc_code'] ?? "";
            $inputUserShiping['bank_swift_code']     = $data['driver_bank_swift_code'] ?? "";

            $inputUserShiping['vendor_id']     = (int)$data['vender_id'];

            $inputUserShiping['user_id']  =    $insertId;
            $this->db->insert('driver_details', $inputUserShiping);
        }

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }

    public function getSellerDriverCondition($seller_id)
    {

        return $this->db->select('*')
                        ->from('user_table u')
                        ->join('driver_details s', 'u.user_id =s.user_id', 'inner')
                        ->where("u.user_type ='D'")
                        ->where("added_by_user_id", $seller_id)
                        ->order_by('u.user_id', 'desc')
                        ->get()
                        ->result();
    }
    function getDriverCondition( $condition = array() )
    {
        if ( !empty($condition) ) {
            $this->db->where($condition);
        }
        return $this->db->select('*')
                        ->from('user_table u')
                        ->join('driver_details s', 'u.user_id =s.user_id', 'inner')
                        ->where("u.user_type = 'D'")
                        ->order_by('u.user_id', 'desc')
                        ->get()
                        ->result();
    }
    function getDriverDetails($data)
    {
        $query = $this->db->order_by('driver_details_id', 'ASC')->get_where('driver_details', $data);
              //$this->db->order_by('country_language_code','ASC');
             //  echo $this->db->last_query();
              return $query->result();
    }
    function updateDriver($data)
    {
        $userId                                 =    $data['id'];
        $inputUserBasic['user_first_name']      =    $data['txt_first_name'];
        $inputUserBasic['user_last_name']       =    $data['txt_last_name'];
        $inputUserBasic['user_gender']          =    $data['radio_gender'];
        $inputUserBasic['user_country_id']      =    $data['select_country'];
        $inputUserBasic['user_status']          =    0;
        $inputUserBasic['user_deleted']         =    0;
        $inputUserBasic['user_status']          =    0;
        $inputUserBasic['user_deleted']         =    0;

        $user_password = $data['txt_password'] ?? '';
        if ( !empty($user_password) ) {
            $inputUserBasic['user_password'] = MD5($user_password);
        }

        if ( $_FILES["txt_image"]["name"] != "" ) {
            $digits   =  6;
            $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

            $filename = $_FILES["txt_image"]["name"];
            $file_ext = pathinfo($filename, PATHINFO_EXTENSION);

            //$config2['upload_path']          =  $this->config->item('upload_path').$this->config->item('user_profile_image_upload_dir');
            $config2['upload_path']          =  'uploads/driver_images/';
            $config2['allowed_types']        =  'gif|jpg|png|jpeg';
            $config2['max_size']             =  1000;
            $config2['max_width']            =  300;
            $config2['max_height']           =  300;
            $config2['file_name']            =  $randomNo.".".$file_ext;

            //$this->load->library('upload', $config2);
            $this->load->library('upload', $config2);
            $this->upload->initialize($config2);

            if (! $this->upload->do_upload('txt_image')) {
                $data['status'] = 0;
                $data['errors'] = array(
                    'txt_image' => $this->upload->display_errors(),
                );
                echo json_encode($data);
                exit();
            } else {
                $inputUserBasic['image'] = $config2['file_name'];
            }
        }

        $this->db->trans_start();

        $this->db->where('user_id', $userId);
        $this->db->update('user_table', $inputUserBasic);

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial
        $auditArray                     =     array();
        $auditArray['admin_id']         =     $this->session->userdata('admin_id');
        $auditArray['module_id']        =     4;
        $auditArray['entity_id']        =     $userId;
        $auditArray['action_id']        =     2;
        $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
        $auditArray['audit_note']       =     "driver updation from admin module";
        $auditArray['menu_id']          =     3;
        $this->db->insert('admin_audit_trial', $auditArray);
        //admin audit trial //admin audit trial//admin audit trial//admin audit trial



        for ($i = 0; $i < count($data['select_city']); $i++) {
            $inputUserShiping['city']             =    $data['select_city'][$i];
            $inputUserShiping['mobile_no']        =    $data['txt_dialcode'][$i]."-".$data['txt_Phone'][$i];
            $inputUserShiping['location']         =    $data['txt_location'][$i];
            $inputUserShiping['street_name']      =    $data['txt_street'][$i];
            // $inputUserShiping['building_no']      =    $data['txt_building'][$i];

            $inputUserShiping['latitude']         =    $data['latti'][$i];
            $inputUserShiping['longitude']        =    $data['longi'][$i];

            $inputUserShiping['vehicle_no']        =    $data['txt_veh_no'][$i];
            // $inputUserShiping['land_phone']        =    $data['txt_Land_Phone'][$i];

            $inputUserShiping['document_number']   =    $data['txt_License'][$i];
            // $inputUserShiping['vehicle_type_id']   =    $data['vehicle_type'][$i] > 0 ? $data['vehicle_type'][$i] : 0;
            $inputUserShiping['vehicle_reg_no']    =    $data['txt_veh_no'][$i];
            // $inputUserShiping['emirates_id_number'] =   $data['txt_emirates_id'][$i];
            // $inputUserShiping['driver_earning_percentage'] = $data['txt_earning_percentage'][$i];

            if ($_FILES["txt_doc"]["name"] != "") {
                $digits   =  6;
                $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

                $filename2 = $_FILES["txt_doc"]["name"];
                $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

                $config2['upload_path']          =  $this->config->item('upload_path').'vendor_images/';
                $config2['allowed_types']        =  'gif|jpg|png|pdf|doc';
                $config2['max_size']             =  1000;
                $config2['file_name']            =  $randomNo.".".$file_ext2;

                //$this->load->library('upload', $config2);
                $this->load->library('upload', $config2);
                // $this->upload->initialize($config2);

                if (! $this->upload->do_upload('txt_doc')) {
                    //die("file upload failed");
                      $data['status'] = 0;
                      $data['errors'] = array(
                        'txt_doc' => $this->upload->display_errors(),
                      );
                      echo json_encode($data);
                      exit();
                } else {
                   //$inputUserShiping['document_number']   =    $data['txt_doc_no'][$i];
                   //$inputUserShiping['document_type_id']  =    $data['select_doc_type'][$i]>0?$data['select_doc_type'][$i]:0;
                    $inputUserShiping['doument_name']       =    $config2['file_name'];
                }
            }

            if ($_FILES["txt_doc2"]["name"]!="") {
                $digits   =  6;
                $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

                $filename2 = $_FILES["txt_doc2"]["name"];
                $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

                $config2['upload_path']          =  $this->config->item('upload_path').$this->config->item('driver_document_upload_dir');
                $config2['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
                $config2['max_size']             =  1000;
                $config2['file_name']            =  $randomNo.".".$file_ext2;

                $this->load->library('upload', $config2);
                $this->upload->initialize($config2);

                if (! $this->upload->do_upload('txt_doc2')) {
                    $data['status'] = 0;
                    $data['errors'] = array(
                        'txt_doc2' => $this->upload->display_errors(),
                    );
                    echo json_encode($data);
                    exit();
                } else {
                    $inputUserShiping['mulkiya']                =    $config2['file_name'];
                }
            }

            if ( $_FILES["txt_doc3"]["name"] != "" ) {
                $digits   =  6;
                $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

                $filename3 = $_FILES["txt_doc3"]["name"];
                $file_ext3 = pathinfo($filename3, PATHINFO_EXTENSION);

                $config2['upload_path']          =  $this->config->item('upload_path').$this->config->item('driver_document_upload_dir');
                $config2['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
                $config2['max_size']             =  1000;
                $config2['file_name']            =  $randomNo.".".$file_ext3;

                $this->load->library('upload', $config2);
                $this->upload->initialize($config2);

                if (! $this->upload->do_upload('txt_doc3')) {
                    $data['status'] = 0;
                    $data['errors'] = array(
                        'txt_doc3' => $this->upload->display_errors(),
                    );
                    echo json_encode($data);
                    exit();
                } else {
                    $inputUserShiping['emirates_id_file'] = $config2['file_name'];
                }
            }

            $inputUserShiping['driver_bank_id']      = $data['driver_bank_id'] ?? "";
            $inputUserShiping['bank_account_number'] = $data['driver_bank_account_number'] ?? "";
            $inputUserShiping['bank_ifsc_code']      = $data['driver_bank_ifsc_code'] ?? "";
            $inputUserShiping['bank_swift_code']     = $data['driver_bank_swift_code'] ?? "";

            $this->db->where('user_id', $userId);
            $this->db->update('driver_details', $inputUserShiping);
        }

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }

    function deleteDriver($id)
    {
        $this->db->trans_start();

        $this->db->where('user_id', $id);
        $this->db->delete('user_table');

        $this->db->where('user_id', $id);
        $this->db->delete('driver_details');

        $this->db->trans_complete();


        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }

    function approveDriver()
    {
        $this->db->trans_start();

        $userId          =  $_POST['id'];
        $this->db->where('user_id', $userId);
        $inputUserBasic['user_status']  =   $_POST['status'];
        $this->db->update('user_table', $inputUserBasic);

        $verified_status = $_POST['status'] ?? 0;
        $verified_count  = $_POST['verified_count'] ?? 0;

        if ( $verified_status && $verified_count > 0 ) {
            $this->db->where('user_id', $userId);
            $this->db->update('driver_details', ['verified_count' => $verified_count]);
        }

        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }
    function getDriverFulDetails($id)
    {

        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $this->db->select('c1.*,c2.*,u.*,s.*,bm.bank_name');
        $this->db->from('country c1');
        $this->db->join('city c2', 'c1.country_id =c2.city_country_id', 'left');
        $this->db->join('user_table u', 'c1.country_id =u.user_country_id', 'left');
        $this->db->join('driver_details s', '(s.city =c2.city_id) AND (s.user_id=u.user_id) ', 'left');
        $this->db->join('bank_master bm', '(bm.bank_id =s.driver_bank_id) ', 'left');
        $this->db->where('c1.country_language_code', $language);
        $this->db->where('c2.city_language_code', $language);
        $this->db->where('s.city =c2.city_id');
        $this->db->where('u.user_id', $id);
 // $this->db->order_by('c.category_id','desc');
        $query = $this->db->get();
 //echo $this->db->last_query();
        return $query->result();
    }
    function getArticleTypes()
    {

        $query = $this->db->get_where('article_type', array());
        return $query->result();
    }
    function saveArticle($data)
    {
              $this->db->trans_start();



               $this->db->select('count(articles_id) as counter');
               $this->db->from('articles c');
               $this->db->where('articles_language_code', 1);
               $this->db->where('articles_type_id', $data['txt_article_type']);
               $query = $this->db->get();
              // echo $this->db->last_query();
               $res  =  $query->row();
               $count              =   ($res->counter>0?$res->counter:0);



        $inputArray[0]['articles_type_id']          =    $data['txt_article_type'] ;
        $inputArray[0]['articles_desc']             =    $data['txt_article'] ;
        $inputArray[0]['articles_status']           =    1 ;
        $inputArray[0]['articles_created_date']     =    gmdate("Y-m-d H:i:s") ;
        $inputArray[0]['articles_language_code']    =    1 ;

        $inputArray[0]['meta_title']                =    $data['txt_meta_title'] ;
        $inputArray[0]['meta_keyword']              =    $data['txt_meta_keyword'] ;
        $inputArray[0]['meta_description']          =    $data['txt_meta_description'] ;
        $inputArray[1]['meta_title']                =    $data['txt_meta_title'] ;
        $inputArray[1]['meta_keyword']              =    $data['txt_meta_keyword'] ;
        $inputArray[1]['meta_description']          =    $data['txt_meta_description'] ;


        $inputArray[1]                              =    $inputArray[0] ;
        $inputArray[1]['articles_language_code']    =    2 ;
         $inputArray[1]['articles_desc']             =    $data['txt_article_arb'] ;

        if ($count>0) {
           //$articleId                                  =    $data['id'];
            $inputArray[0]['articles_updated_date']     =    gmdate("Y-m-d H:i:s") ;
            $inputArray[1]['articles_updated_date']     =    gmdate("Y-m-d H:i:s") ;

            unset($inputArray[0]['articles_created_date']);
            unset($inputArray[1]['articles_created_date']);



            $this->db->where('articles_language_code', 1);
            $this->db->where('articles_type_id', $data['txt_article_type']);
            $this->db->update('articles', $inputArray[0]);

            $this->db->where('articles_language_code', 2);
            $this->db->where('articles_type_id', $data['txt_article_type']);
            $this->db->update('articles', $inputArray[1]);
        } else {
                           $this->db->select('max(articles_id) as maxid');
                           $this->db->from('articles c');
                           $this->db->where('articles_language_code', 1);
                           $query = $this->db->get();
                          // echo $this->db->last_query();
                           $res  =  $query->row();
                           $maxId              =   ($res->maxid>0?$res->maxid+1:1);

                           $inputArray[0]['articles_id']               =    $maxId ;

                           $inputArray[1]['articles_id']               =    $maxId ;



                          $this->db->insert_batch('articles', $inputArray);
        }


                    //admin audit trial //admin audit trial//admin audit trial//admin audit trial
                  /*
                    $auditArray                     =    array();
                    $auditArray['admin_id']         =    $this->session->userdata('admin_id');
                    $auditArray['module_id']        =    5;
                    $auditArray['entity_id']        =    $id;
                    $auditArray['action_id']        =    3 ;
                    $auditArray['audit_time']       =    gmdate("Y-m-d H:i:s");
                    $auditArray['audit_note']       =    "";
                    $auditArray['menu_id']          =    4;
                    $this->db->insert('admin_audit_trial',$auditArray);*/

                    //admin audit trial //admin audit trial//admin audit trial//admin audit trial

                    $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
             return 0;
        } else {
            return 1;
        }
    }
    function getArticles()
    {
        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $language=1;
        $this->db->select('DISTINCT ON (a.articles_id) a.articles_id, a3.article_type_desc,a.*,a.articles_desc as arbicname,a2.articles_desc as englishname');
        $this->db->from('articles a');
        $this->db->join('articles a2', 'a2.articles_id =a.articles_id', 'inner');
        $this->db->join('article_type a3', 'a3.article_type_id =a.articles_type_id', 'inner');
        $this->db->where('a.articles_language_code', 1);
        $this->db->where('a2.articles_language_code', 2);
        $this->db->where('a3.article_type_language_code', $language);
        $this->db->order_by('a.articles_id', 'desc');
         //$this->db->limit($limit, $start);
        $query = $this->db->get();
           //echo $this->db->last_query();
         return $query->result();
    }
    function getArticlesById($language, $id)
    {

         $query = $this->db->get_where('articles', array('articles_language_code'=>$language,'articles_id'=>$id));
        return $query->row();
    }
    function deleteArticle($id)
    {
        $this->db->trans_start();
        $this -> db -> where('articles_id', $id);
        $this -> db -> delete('articles');
        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
                         return 0;
        } else {
                       return 1;
        }
    }
    function getgetBrandList()
    {
        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $this->db->select('c.*,c2.brand_name as arbicname,c.brand_name as englishname');
        $this->db->from('brand c');
        $this->db->join('brand c2', 'c2.brand_id =c.brand_id', 'left');

        $this->db->where('c.brand_language_code', 1);
        $this->db->where('c2.brand_language_code', 2);
/* if($additional['searchKey']!="")
 {
     $this->db->like('LOWER(c.city_name)', strtolower($additional['searchKey']));
 }*/
        $this->db->order_by('c.brand_id', 'desc');
// $this->db->limit($limit, $start);
        $query = $this->db->get();
// echo $this->db->last_query();
        return $query->result();
    }
    function getBrands($language, $id)
    {
     /* $query = $this->db->get_where('country', array('country_language_code' => $language,'country_id'=>$id));
       $this->db->order_by('country_language_code','ASC');
     echo $this->db->last_query();
     return $query->row();
*/

        $this->db->select('*');
        $this->db->from('brand c');
        $this->db->where('brand_language_code', $language);
        $this->db->where('brand_id', $id);
        $this->db->order_by('brand_language_code', 'ASC');
        $query = $this->db->get();
//echo $this->db->last_query();
        return $query->row();
    }
    function deleteBrand($id)
    {

               $this->db->trans_start();

               $this -> db -> where('brand_id', $id);
               $this -> db -> delete('brand');


              //admin audit trial //admin audit trial//admin audit trial//admin audit trial

                $auditArray                     =     array();
                $auditArray['admin_id']         =     $this->session->userdata('admin_id');
                $auditArray['module_id']        =     11;
                $auditArray['entity_id']        =     $id;
                $auditArray['action_id']        =     3;
                $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
                $auditArray['audit_note']       =     "brand delete from admin module";
                $auditArray['menu_id']          =     5;
                $this->db->insert('admin_audit_trial', $auditArray);

               //admin audit trial //admin audit trial//admin audit trial//admin audit trial


                 $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }
    public function getMallsCondition($data)
    {




             $query = $this->db->order_by('mall_name', 'asc')->get_where('mall', $data);
             //$this->db->order_by('country_language_code','ASC');
           //  echo $this->db->last_query();
             return $query->result();
    }
    function getBasicUserDeatils($id)
    {
         $query = $this->db->get_where('user_table', array('user_id'=>$id));
        // echo $this->db->last_query();
         return $query->row();
    }
    public function getBrandCondition($data)
    {




             $query = $this->db->order_by('brand_name', 'asc')->get_where('brand', $data);
             //$this->db->order_by('country_language_code','ASC');
             // echo $this->db->last_query();
             return $query->result();
    }
    public function send($subject, $message, $to, $from)
    {


       // Always set content-type when sending HTML email
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
        $headers .= 'From: <'.$from.'>' . "\r\n";
//$headers .= 'Cc: myboss@example.com' . "\r\n";

        if (mail($to, $subject, $message, $headers)) {
            return true;
        } else {
            return false;
        }
    }
    function getBrandsByCondition($data)
    {
        $cateGoryId  =  $data['category_id'] ;
        $keyWord     =  strtolower($data['key_word']) ;

       // print_r($data);

        $language =($this->session->userdata('language')?$this->session->userdata('language'):$data['language']);
        $language = $language>0?$language:1;

         $sql = "select distinct brand_id,brand_name from product p,product_category pc,brand b,category c ,product_attribute pa where c.category_id=pc.category_id and pc.product_id=p.product_id and p.product_brand_id=b.brand_id
and brand_language_code=".$language." and b.brand_status=1  and p.product_status=1 and pa.product_id=p.product_id ";

        if ($cateGoryId>0) {
              $sql.= "     and  pc.category_id=".$cateGoryId." ";
        }
        if ($keyWord!="") {
              $sql.= "     and  (LOWER(brand_name) like  '%". $keyWord."%' or LOWER(product_name) like  '%". $keyWord."%' or LOWER(category_name) like  '%". $keyWord."%' or LOWER(product_name_arabic) like '%". $keyWord."%' ) ";
        }

        $sql.= "     and  (CASE WHEN allow_back_order = 0 THEN stock_quantity ELSE 1 END)>0 ";

        $date = date("Y-m-d");

        $sql.= "     and date(p.product_sale_from)<='".$date."' and   date(p.product_sale_to)>='".$date."' ";



        if ($cateGoryId<=0 && $keyWord=="") {
               $sql = "select distinct brand_id,brand_name from brand b where brand_language_code=".$language." and b.brand_status=1   ";
        }



   // echo    $sql;
           $rs = $this->db->query($sql);

               $result= $row = $rs->result();
               return $result;
    }
    function getCategoriesByCondition($data)
    {
        $cateGoryId  =  $data['category_id'] ;
        $keyWord     =  $data['key_word'] ;


       // print_r($data);

        $language =($this->session->userdata('language')?$this->session->userdata('language'):$data['language']);
        $language = $language>0?$language:1;

        $sql = "select distinct c.category_id,category_name from product p,product_category pc,brand b,category c where c.category_id=pc.category_id and pc.product_id=p.product_id and p.product_brand_id=b.brand_id
and brand_language_code=".$language." and category_language_code=".$language." and c.category_id!=4 and b.brand_status=1  and p.product_status=1 ";

        if ($cateGoryId>0) {
              $sql.= "     and  pc.category_id=".$cateGoryId." ";
        }
        if ($keyWord!="") {
              $sql.= "     and  (LOWER(brand_name) like  '%". $keyWord."%' or LOWER(product_name) like  '%". $keyWord."%' or LOWER(category_name) like  '%". $keyWord."%' or LOWER(product_name_arabic) like '%". $keyWord."%' ) ";
        }
/*if($cateGoryId<=0 && $keyWord=="")
{
       $sql = "select distinct brand_id,brand_name from brand b where brand_language_code=".$language." and b.brand_status=1   ";
}*/

  //  echo    $sql;
        $rs = $this->db->query($sql);

            $result= $row = $rs->result();
            return $result;
    }
    function getAttributesValuesForSearch($data)
    {
         $cateGoryId  =  $data['category_id'] ;

         $keyWord     =  strtolower($data['key_word']) ;

         //print_r($data);

        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $language = $language>0?$language:1;
        $sql = "select distinct a.attribute_id,attribute_name,attribute_name_arabic from product p,product_variations pv,attribute a,product_attribute pa,product_category pc,category c,brand b
where c.category_id=pc.category_id and c.category_language_code=".$language." and  b.brand_id=product_brand_id and brand_language_code=".$language." and pv.product_id=p.product_id and pa.product_id=p.product_id and pv.product_attribute_id=pa.product_attribute_id and pc.product_id=p.product_id and a.attribute_id=pv.attribute_id
 ";

        if ($cateGoryId>0) {
              $sql.= "     and  pc.category_id=".$cateGoryId." ";
        }
        if ($keyWord!="") {
            $sql.= "     and  (LOWER(brand_name) like  '%". $keyWord."%' or LOWER(product_name) like  '%". $keyWord."%' or LOWER(category_name) like  '%". $keyWord."%' or LOWER(product_name_arabic) like '%". $keyWord."%' or LOWER(attribute_name) like '%". $keyWord."%' ) ";
        }

        $sql.= "     and  (CASE WHEN allow_back_order = 0 THEN stock_quantity ELSE 1 END)>0 ";

        $date = date("Y-m-d");

        $sql.= "     and date(p.product_sale_from)<='".$date."' and   date(p.product_sale_to)>='".$date."' ";

  // echo    $sql;

         $rs = $this->db->query($sql);

             $result= $row = $rs->result();
             return $result;
    }

      //banner
    function getBannerList()
    {
         $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
         $this->db->select('*');
         $this->db->from('banner_images c');

         $this->db->where('bi_language_code', 1);

           $query = $this->db->get();
          // echo $this->db->last_query();
            return $query->result();
    }

      //App Home banner
    function getAppHomeBannerList()
    {
         $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
         $this->db->select('*');
         $this->db->from('app_homer_offer_popup c');

         $this->db->where('ahop_language_code', 1);
         $this->db->where('ahop_status', 1);
           $query = $this->db->get();
          // echo $this->db->last_query();
            return $query->result();
    }
    function getAppHomeBannerListbyID($lang, $id)
    {
        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $this->db->select('*');
        $this->db->from('app_homer_offer_popup c');

        $this->db->where('ahop_language_code', $lang);
        $this->db->where('ahop_id', $id);

          $query = $this->db->get();
         // echo $this->db->last_query();
             return $query->row();
    }
    function getBanner($language, $id)
    {
            /* $query = $this->db->get_where('country', array('country_language_code' => $language,'country_id'=>$id));
              $this->db->order_by('country_language_code','ASC');
            echo $this->db->last_query();
            return $query->row();
*/

        $this->db->select('*');
        $this->db->from('banner_images');
        $this->db->where('bi_language_code', $language);
        $this->db->where('bi_id', $id);

        $query = $this->db->get();
      //echo $this->db->last_query();
        return $query->row();
    }
    function getBannerApp($language, $id)
    {
          /* $query = $this->db->get_where('country', array('country_language_code' => $language,'country_id'=>$id));
            $this->db->order_by('country_language_code','ASC');
          echo $this->db->last_query();
          return $query->row();
*/

        $this->db->select('*');
        $this->db->from('banner_images_app');
        $this->db->where('bi_language_code', $language);
        $this->db->where('bi_id', $id);

        $query = $this->db->get();
    //echo $this->db->last_query();
        return $query->row();
    }
    function deleteBanner($id)
    {
           $this->db-> where('bi_id', $id);
        if ($this->db->delete('banner_images')) {
              return 1;
        } else {
                 return 0;
        }
    }
        ///slider

    function getSliderList()
    {
         $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
         $this->db->select('*');
         $this->db->from('slider_images c');

         $this->db->where('si_language_code', 1);

           $query = $this->db->get();
          // echo $this->db->last_query();
            return $query->result();
    }


    function getSlider($language, $id)
    {
            /* $query = $this->db->get_where('country', array('country_language_code' => $language,'country_id'=>$id));
              $this->db->order_by('country_language_code','ASC');
            echo $this->db->last_query();
            return $query->row();
*/

        $this->db->select('*');
        $this->db->from('slider_images');
        $this->db->where('si_language_code', $language);
        $this->db->where('si_id', $id);

        $query = $this->db->get();
      //echo $this->db->last_query();
        return $query->row();
    }
    function getSliderApp($language, $id)
    {
        /* $query = $this->db->get_where('country', array('country_language_code' => $language,'country_id'=>$id));
          $this->db->order_by('country_language_code','ASC');
        echo $this->db->last_query();
        return $query->row();
*/

        $this->db->select('*');
        $this->db->from('slider_images_app');
        $this->db->where('si_language_code', $language);
        $this->db->where('si_id', $id);

        $query = $this->db->get();
  //echo $this->db->last_query();
        return $query->row();
    }
    function getOfferSliderApp($language, $id)
    {
        /* $query = $this->db->get_where('country', array('country_language_code' => $language,'country_id'=>$id));
          $this->db->order_by('country_language_code','ASC');
        echo $this->db->last_query();
        return $query->row();
*/

        $this->db->select('*');
        $this->db->from('offer_banners_app');
        $this->db->where('si_language_code', $language);
        $this->db->where('si_id', $id);

        $query = $this->db->get();
  //echo $this->db->last_query();
        return $query->row();
    }
    function deleteSlider($id)
    {

             $this->db->trans_start();
             $this->db-> where('si_id', $id);
             $this->db->delete('slider_images');

            //admin audit trial //admin audit trial//admin audit trial//admin audit trial

             $auditArray                     =     array();
             $auditArray['admin_id']         =     $this->session->userdata('admin_id');
             $auditArray['module_id']        =     13;
             $auditArray['entity_id']        =     $id;
             $auditArray['action_id']        =     3;
             $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
             $auditArray['audit_note']       =     "slider delete from admin module";
             $auditArray['menu_id']          =     5;
             $this->db->insert('admin_audit_trial', $auditArray);

           //admin audit trial //admin audit trial//admin audit trial//admin audit trial

            $this->db->trans_complete();



        if ($this->db->trans_status() === false) {
               return 0;
        } else {
                  return 1;
        }
    }

        //Dragon slider images
    function getDragonSliderList()
    {
          $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
          $this->db->select('*');
          $this->db->from('dragon_slider_images');

          $this->db->where('dsi_language_code', 1);

            $query = $this->db->get();
           // echo $this->db->last_query();
             return $query->result();
    }

    function getDragonSlider($language, $id)
    {
            /* $query = $this->db->get_where('country', array('country_language_code' => $language,'country_id'=>$id));
              $this->db->order_by('country_language_code','ASC');
            echo $this->db->last_query();
            return $query->row();
*/

        $this->db->select('*');
        $this->db->from('dragon_slider_images');
        $this->db->where('dsi_language_code', $language);
        $this->db->where('dsi_id', $id);

        $query = $this->db->get();
      //echo $this->db->last_query();
        return $query->row();
    }
    function getDragonSliderApp($language, $id)
    {
          /* $query = $this->db->get_where('country', array('country_language_code' => $language,'country_id'=>$id));
            $this->db->order_by('country_language_code','ASC');
          echo $this->db->last_query();
          return $query->row();
*/

        $this->db->select('*');
        $this->db->from('dragon_slider_images_app');
        $this->db->where('dsi_language_code', $language);
        $this->db->where('dsi_id', $id);

        $query = $this->db->get();
    //echo $this->db->last_query();
        return $query->row();
    }
    function getDragonOfferBannerApp($language, $id)
    {
         /* $query = $this->db->get_where('country', array('country_language_code' => $language,'country_id'=>$id));
           $this->db->order_by('country_language_code','ASC');
         echo $this->db->last_query();
         return $query->row();
*/

        $this->db->select('*');
        $this->db->from('dragon_offer_banner');
        // $this->db->where('dsi_language_code',$language);
        $this->db->where('drag_offer_ban_id', $id);

        $query = $this->db->get();
   //echo $this->db->last_query();
        return $query->row();
    }
    function deleteDragonSlider($id)
    {
            $this->db->trans_start();

            $this -> db -> where('dsi_id', $id);
            $this -> db -> delete('dragon_slider_images');

           //admin audit trial //admin audit trial//admin audit trial//admin audit trial

             $auditArray                     =     array();
             $auditArray['admin_id']         =     $this->session->userdata('admin_id');
             $auditArray['module_id']        =     14;
             $auditArray['entity_id']        =     $id;
             $auditArray['action_id']        =     3;
             $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
             $auditArray['audit_note']       =     "dragon slider delete from admin module";
             $auditArray['menu_id']          =     5;
             $this->db->insert('admin_audit_trial', $auditArray);

           //admin audit trial //admin audit trial//admin audit trial//admin audit trial


          $this->db->trans_complete();



        if ($this->db->trans_status() === false) {
               return 0;
        } else {
                  return 1;
        }
    }
    function deleteDragonSliderApp($id)
    {

             $this->db->trans_start();

             $this -> db -> where('dsi_id', $id);
             $this -> db -> delete('dragon_slider_images_app');

            //admin audit trial //admin audit trial//admin audit trial//admin audit trial

              $auditArray                     =     array();
              $auditArray['admin_id']         =     $this->session->userdata('admin_id');
              $auditArray['module_id']        =     15;
              $auditArray['entity_id']        =     $id;
              $auditArray['action_id']        =     3;
              $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
              $auditArray['audit_note']       =     "app dragon slider  delete from admin module";
              $auditArray['menu_id']          =     5;
              $this->db->insert('admin_audit_trial', $auditArray);

            //admin audit trial //admin audit trial//admin audit trial//admin audit trial
            $this->db->trans_complete();



        if ($this->db->trans_status() === false) {
             return 0;
        } else {
                 return 1;
        }
    }
    function getBannerListApp()
    {
        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $this->db->select('*');
        $this->db->from('banner_images_app c');

        $this->db->where('bi_language_code', 1);

          $query = $this->db->get();
         // echo $this->db->last_query();
           return $query->result();
    }
    function getAppOfferBannerList()
    {
         $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $this->db->select('*');
        $this->db->from('dragon_offer_banner c');

       //$this->db->where('drag_offer_status',1);

         $query = $this->db->get();
        // echo $this->db->last_query();
          return $query->result();
    }
    function getSliderListApp()
    {

        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $this->db->select('*');
        $this->db->from('slider_images_app c');

        $this->db->where('si_language_code', 1);

        $query = $this->db->get();
     // echo $this->db->last_query();
        return $query->result();
    }
    function getOfferSliderListApp()
    {

        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $this->db->select('*');
        $this->db->from('offer_banners_app c');

        $this->db->where('si_language_code', 1);

        $query = $this->db->get();
     // echo $this->db->last_query();
        return $query->result();
    }

    function getCashPointReports()
    {
        $this->db->select('*');
        $this->db->from('user_table');
        $this->db->where_in('user_type', ['U', 'C']);
        $this->db->group_start();
            $this->db->where('user_points >', 0);
            $this->db->or_where('used_points >', 0);
        $this->db->group_end();
        $this->db->order_by('user_first_name asc');
        return $this->db->get()->result();
    }

    function getUserCashPointDetails($user_id)
    {
         return $this->db->query("select
                                            cash_points.*,
                                            product_order_details.order_no,
                                            (from_user_table.user_first_name || ' ' || from_user_table.user_last_name) as from_user_name,
                                            (to_user_table.user_first_name || ' ' || to_user_table.user_last_name) as to_user_name
                                        from cash_points
                                        left join product_order_details on product_order_details.order_block_id=cash_points.order_block_id
                                        left join cash_points_transfer on cash_points_transfer.cp_transfer_id = cash_points.transfer_id
                                        left join user_table from_user_table on from_user_table.user_id = cash_points_transfer.from_user_id
                                        left join user_table to_user_table on to_user_table.user_id = cash_points_transfer.to_user_id
                                        where cash_points.cp_user_id = {$user_id}")->result();
    }

    function CashPointDetails($id)
    {
         $sql = "  select u.user_id,u.user_first_name,u.user_last_name,o.product_id,o.order_block_id,purchase_qty ,p.product_name,sum(cash_points) from product p,product_order_history o,user_table u where o.user_id=u.user_id and p.product_id = o.product_id and o.user_id=".$id." group by u.user_id,u.user_first_name,u.user_last_name,o.product_id,o.order_block_id,purchase_qty ,p.product_name order by user_first_name,user_id ASC";

            $rs = $this->db->query($sql);
            // echo $this->db->last_query();
          return      $result  =   $rs->result_array();
    }
    function venderPaymentReport()
    {
         $sql = "  select u.user_id,u.user_first_name,u.user_last_name,sum(unit_price*purchase_qty) as sum from product p,product_attribute pa,product_order_history o,user_table u where p.product_vender_id=u.user_id and p.product_id = o.product_id and pa.product_attribute_id=o.product_attribute_id group by u.user_id,u.user_first_name,u.user_last_name order by user_first_name,user_id ASC";

            $rs = $this->db->query($sql);
            // echo $this->db->last_query();
          return      $result  =   $rs->result_array();
    }
    function venderPaymentDetails($id)
    {
        $sql = "  select u.user_id,u.user_first_name,u.user_last_name,o.product_id,o.order_block_id,purchase_qty ,p.product_name,sum(unit_price*purchase_qty) from product p,product_attribute pa,product_order_history o,user_table u where u.user_id=p.product_vender_id and p.product_id = o.product_id and p.product_vender_id=".$id." and pa.product_attribute_id=o.product_attribute_id  group by u.user_id,u.user_first_name,u.user_last_name,o.product_id,o.order_block_id,purchase_qty ,p.product_name order by user_first_name,user_id ASC
 ";

            $rs = $this->db->query($sql);
            // echo $this->db->last_query();
          return      $result  =   $rs->result_array();
    }
    function teyaarCommissionReport()
    {
        $sql = "select pa.image,u.user_id,u.user_first_name,u.user_last_name,u2.user_first_name as cusfname,u2.user_last_name as cuslname,purchase_qty,product_name, pod.order_block_id, pod.order_no, sum(khiat_commission) as sum, sum(category_commission) as sum2 from product p,product_attribute pa,product_order_history o, product_order_details pod, user_table u,user_table u2 where p.product_vender_id=u.user_id and o.order_block_id = pod.order_block_id and p.product_id = o.product_id and pa.product_attribute_id=o.product_attribute_id and o.user_id=u2.user_id group by u.user_id,u.user_first_name,u.user_last_name,u2.user_first_name,u2.user_last_name,purchase_qty,product_name, pod.order_block_id, pod.order_no, pa.image order by pod.order_block_id desc
 ";

        $rs = $this->db->query($sql);
        return      $result  =   $rs->result_array();
    }

    function commissionReport( $condition=[] )
    {
        $this->db->select("pod.order_no, pod.order_block_id, pod.order_placed_date, pod.product_order_id, product.product_name, pattr.image, poh.purchase_qty, poh.khiat_commission AS sum, poh.category_commission AS sum2, poh.vendor_commission, poh.product_sub_price AS sub_total, poh.product_total_tax, COALESCE(poh.product_total, 0) AS grand_total, user.user_id AS customer_id, user.company_name AS cusfname, '' AS cuslname, seller.store_name AS store_name, poh.deliver_status");
        $this->db->from('product_order_history poh');
        $this->db->join('product_order_details pod', 'poh.order_block_id = pod.order_block_id', 'left');
        $this->db->join('product_attribute pattr', 'poh.product_attribute_id = pattr.product_attribute_id', 'left');
        $this->db->join('product product', 'pattr.product_id = product.product_id', 'left');
        $this->db->join('user_table user', 'pod.user_id = user.user_id', 'left');
        $this->db->join('seller_details seller', 'product.product_vender_id = seller.user_id', 'left');
        $this->db->where('poh.deliver_status !=', ORDER_STATUS_CANCEL);
        $this->db->where('pod.order_block_id !=', NULL);

        $start_date = $condition['start_date'] ?? '';
        $end_date = $condition['end_date'] ?? '';

        if (! empty($start_date) ) {
            $this->db->where('(pod.order_placed_date)::DATE >=', $start_date);
        }
        if (! empty($end_date) ) {
            $this->db->where('(pod.order_placed_date)::DATE <=', $end_date);
        }

        $this->db->order_by('pod.order_block_id', 'desc');
        return $this->db->get()->result_array();
    }

    function deleteAppSlider($id)
    {
             $this->db->trans_start();

             $this -> db -> where('si_id', $id);
             $this -> db -> delete('slider_images_app');

            //admin audit trial //admin audit trial//admin audit trial//admin audit trial

             $auditArray                     =     array();
             $auditArray['admin_id']         =     $this->session->userdata('admin_id');
             $auditArray['module_id']        =     17;
             $auditArray['entity_id']        =     $id;
             $auditArray['action_id']        =     3;
             $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
             $auditArray['audit_note']       =     "app  slider  delete from admin module";
             $auditArray['menu_id']          =     5;
             $this->db->insert('admin_audit_trial', $auditArray);

            //admin audit trial //admin audit trial//admin audit trial//admin audit trial

             $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
               return 0;
        } else {
                   return 1;
        }
    }
    function deleteOfferSlider($id)
    {
             $this->db->trans_start();

             $this -> db -> where('si_id', $id);
             $this -> db -> delete('offer_banners_app');

            //admin audit trial //admin audit trial//admin audit trial//admin audit trial

             $auditArray                     =     array();
             $auditArray['admin_id']         =     $this->session->userdata('admin_id');
             $auditArray['module_id']        =     17;
             $auditArray['entity_id']        =     $id;
             $auditArray['action_id']        =     3;
             $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
             $auditArray['audit_note']       =     "banner offer  slider  delete from admin module";
             $auditArray['menu_id']          =     5;
             $this->db->insert('admin_audit_trial', $auditArray);

            //admin audit trial //admin audit trial//admin audit trial//admin audit trial

             $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
               return 0;
        } else {
                   return 1;
        }
    }
    function getDragonSliderListApp()
    {
         $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
         $this->db->select('*');
         $this->db->from('dragon_slider_images_app');

         $this->db->where('dsi_language_code', 1);

           $query = $this->db->get();
          // echo $this->db->last_query();
            return $query->result();
    }
    function deleteDragonOfferBannerApp($id)
    {

         $this->db->trans_start();

          $this -> db -> where('drag_offer_ban_id', $id);
          $this -> db -> delete('dragon_offer_banner');

         //admin audit trial //admin audit trial//admin audit trial//admin audit trial

           $auditArray                     =     array();
           $auditArray['admin_id']         =     $this->session->userdata('admin_id');
           $auditArray['module_id']        =     19;
           $auditArray['entity_id']        =     $id;
           $auditArray['action_id']        =     3;
           $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
           $auditArray['audit_note']       =     "dragon slider delete from admin module";
           $auditArray['menu_id']          =     5;
           $this->db->insert('admin_audit_trial', $auditArray);

         //admin audit trial //admin audit trial//admin audit trial//admin audit trial

         $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
                   return 0;
        } else {
                     return 1;
        }
    }
    function getDragonProfileListApp()
    {
         $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
         $this->db->select('*');
         $this->db->from('dragon_profile_image');

        // $this->db->where('status',1);

           $query = $this->db->get();
          // echo $this->db->last_query();
            return $query->result();
    }
    function saveDragonProfile($data)
    {
         $this->db->trans_start();


          $sql = "update dragon_profile_image set status=0";



         $rs = $this->db->query($sql);






         $this->db->insert('dragon_profile_image', $data);

         $entityId = $this->db->insert_id();

         //admin audit trial //admin audit trial//admin audit trial//admin audit trial

             $auditArray                     =     array();
             $auditArray['admin_id']         =     $this->session->userdata('admin_id');
             $auditArray['module_id']        =     21;
             $auditArray['entity_id']        =     $entityId;
             $auditArray['action_id']        =     1;
             $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
             $auditArray['audit_note']       =     "";
             $auditArray['menu_id']          =     5;
             $this->db->insert('admin_audit_trial', $auditArray);



             //admin audit trial //admin audit trial//admin audit trial//admin audit trial



         $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
                   return 0;
        } else {
                  return 1;
        }
    }
    function saveAdminDetails($data)
    {

         $this->db->trans_start();
         $input['email_id']  =  $data['txt_email'];
         $input['address']   =  $data['txt_address'];
         $input['phone_no']  =  $data['txt_dial']."-".$data['txt_phone'];
         $input['date']      =  gmdate("Y-m-d H:i:s");

         $input['fb_link']     = $data['txt_facebook'];
         $input['twitter_link']            = $data['txt_twitter'];
         $input['google_link']     = $data['txt_google'];
         $input['youtube_link']     = $data['txt_youtube'];
         $input['insta_link']     = $data['txt_insta'];

         $input['android_app_link']  = $data['txt_android_app'];
         $input['ios_app_link']      = $data['txt_ios_app'];
         $input['whatsapp_no']       = $data['txt_whats_app_no'];

         $input['download_content']       = $data['txt_download_content'];
         $input['download_content_arabic']       = $data['txt_download_content_arabic'];

        if ($data['table_id']>0) {
                 $this -> db -> where('id', $data['table_id']);
                 $this -> db -> update('admin_basics', $input);
                 $action =2;

                  $entityId  = $data['table_id'] ;
        } else {
                   $this->db->insert('admin_basics', $input);
                   $entityId  = $this->db->insert_id();
                   $action =1;
        }

                  //admin audit trial //admin audit trial//admin audit trial//admin audit trial

                        $auditArray                     =    array();
                        $auditArray['admin_id']         =    $this->session->userdata('admin_id');
                        $auditArray['module_id']        =     22;
                        $auditArray['entity_id']        =     $entityId;
                        $auditArray['action_id']        =     $action;
                        $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
                        $auditArray['audit_note']       =     "";
                        $auditArray['menu_id']          =     5;
                        $this->db->insert('admin_audit_trial', $auditArray);

                    //admin audit trial //admin audit trial//admin audit trial//admin audit trial


                        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
               return 0;
        } else {
            return 1;
        }
    }
    function getAdminBasics()
    {
        $sql = "  select * from admin_basics limit 1 ";
            $rs = $this->db->query($sql);
            // echo $this->db->last_query();
          return      $result  =   $rs->row();
    }
    function getBrandsByConditionDragon($data)
    {
        $cateGoryId  =  $data['category_id'] ;

        $language   =    $data['language'];

        $sql = "select distinct brand_id,brand_name from product p,product_category pc,brand b,seller_details s where pc.product_id=p.product_id and p.product_brand_id=b.brand_id
and brand_language_code=".$language." and b.brand_status=1 and p.product_status=1 and p.product_vender_id=s.user_id  and s.mall_id=2 ";

        if ($cateGoryId>0) {
              $sql.= "     and  pc.category_id=".$cateGoryId." ";
        }



        $rs = $this->db->query($sql);

          $result= $row = $rs->result();
          return $result;
    }
    function getAttributesValuesForSearchDragon($data)
    {
         $cateGoryId  =  $data['category_id'] ;

        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);

        $sql = "select distinct a.attribute_id,attribute_name from product p,product_variations pv,attribute a,product_attribute pa,product_category pc ,seller_details s
where pv.product_id=p.product_id and pa.product_id=p.product_id and pv.product_attribute_id=pa.product_attribute_id and pc.product_id=p.product_id and a.attribute_id=pv.attribute_id
  and p.product_vender_id=s.user_id  and s.mall_id=2 and product_status=1 ";

        if ($cateGoryId>0) {
              $sql.= "     and  pc.category_id=".$cateGoryId." ";
        }

  // echo    $sql;

         $rs = $this->db->query($sql);

             $result= $row = $rs->result();
             return $result;
    }

      //get all product list
    function getAllProductList()
    {
            $this->db->select('*');
            $this->db->from('product p1');
            $this->db->join('product_attribute p2', 'p2.product_id =p1.product_id', 'left');
            $this->db->where('p1.product_status', 1);
            $this->db->order_by('product_name', 'ASC');
            $query = $this->db->get();
             // echo $this->db->last_query();
             return $query->result();
    }

          //get all product list
    function getAllCategoryList()
    {
            $this->db->select('*');
            $this->db->from('category');
            $this->db->where('category_status', 1);
            $this->db->where('category_language_code', 1);
            $this->db->where('category_parent_id', 0);
            $this->db->order_by('category_name', 'ASC');

            $query = $this->db->get();
             // echo $this->db->last_query();
             return $query->result();
    }
    function saveCelebrityUser($data)
    {

               $inputUserBasic['user_first_name']      =    $data['txt_first_name'];
               $inputUserBasic['user_last_name']      =    $data['txt_last_name'];
               $inputUserBasic['user_email_id']       =    $data['txt_email'];
               $inputUserBasic['user_gender']         =    $data['radio_gender'];
               $inputUserBasic['user_country_id']     =    $data['select_country'];
               $inputUserBasic['user_password']       =    MD5($data['txt_password']);
               $inputUserBasic['user_status']         =    0;
               $inputUserBasic['user_deleted']        =    0;
               $inputUserBasic['user_status']         =    0;
               $inputUserBasic['user_deleted']        =    0;
               $inputUserBasic['user_created_by']     =    'A';
               $inputUserBasic['user_created_date']   =    gmdate("Y-m-d H:i:s");
               $inputUserBasic['user_type']           =    'C';
               $inputUserBasic['user_custom_id']      =    $data['txt_user_id'];


            $this->db->select('count(user_email_id) as count');
            $this->db->from('user_table c');
            $this->db->where('user_email_id', $data['txt_email']);
            $query = $this->db->get();
           // echo $this->db->last_query();
        if ($query->row()->count>0) {
            return 3;
            exit;
        }



               $this->db->trans_start();



                $this->db->insert('user_table', $inputUserBasic);
                $insertId = $this->db->insert_id();

               //admin audit trial //admin audit trial//admin audit trial//admin audit trial

                $auditArray                     =    array();
                $auditArray['admin_id']         =    $this->session->userdata('admin_id');
                $auditArray['module_id']        =     3;
                $auditArray['entity_id']        =     $insertId;
                $auditArray['action_id']        =     1;
                $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
                $auditArray['audit_note']       =     "celebrity creation from admin module";
                $auditArray['menu_id']          =     3;
                $this->db->insert('admin_audit_trial', $auditArray);

                //admin audit trial //admin audit trial//admin audit trial//admin audit trial

               $this->db->trans_complete();



        if ($this->db->trans_status() === false) {
             return 0;
        } else {
              return 1;
        }
    }
    function updateCelebrity($data)
    {


              $userId    =   $data['id'];

               $inputUserBasic['user_first_name']     =    $data['txt_first_name'];
               $inputUserBasic['user_last_name']      =    $data['txt_last_name'];
              // $inputUserBasic['user_email_id']     =    $data['txt_email'];
               $inputUserBasic['user_gender']         =    $data['radio_gender'];
               $inputUserBasic['user_country_id']     =    $data['select_country'];
              // $inputUserBasic['user_password']     =    MD5($data['txt_password']);
               $inputUserBasic['user_status']         =    0;
               $inputUserBasic['user_deleted']        =    0;
               $inputUserBasic['user_status']         =    0;
               $inputUserBasic['user_deleted']        =    0;
              // $inputUserBasic['user_created_by']     =    'A';
              // $inputUserBasic['user_created_date']   =    gmdate("Y-m-d H:i:s");
               $inputUserBasic['user_type']           =    'C';




               $this->db->trans_start();



                        $this->db->where('user_id', $userId);
                        $this->db->update('user_table', $inputUserBasic);

                //admin audit trial //admin audit trial//admin audit trial//admin audit trial

                $auditArray                     =    array();
                $auditArray['admin_id']         =    $this->session->userdata('admin_id');
                $auditArray['module_id']        =     3;
                $auditArray['entity_id']        =     $userId;
                $auditArray['action_id']        =     2;
                $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
                $auditArray['audit_note']       =     "celebrity creation from admin module";
                $auditArray['menu_id']          =     3;
                $this->db->insert('admin_audit_trial', $auditArray);

                //admin audit trial //admin audit trial//admin audit trial//admin audit trial


               $this->db->trans_complete();



        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }
    function thankuReport($data)
    {
          $sql = " select *,pa.image as product_image,u.user_first_name as cusfirsname,u.user_last_name as cuslasname,u2.user_first_name as celfirsname,u2.user_last_name as cellasname from thanku_commission t,product_order_history h,user_table u,product p,user_table u2,product_attribute pa  where
t.product_id=h.product_id and p.product_id=h.product_id and t.product_attribute_id=h.product_attribute_id and t.order_block_id=h.order_block_id and t.user_id=u.user_id and u2.user_id=t.celebrity_id and pa.product_attribute_id=h.product_attribute_id ";

        if ($this->session->userdata("user_type")=="V" && $this->session->userdata("user_id") >0) {
            $sql.= " and  p.product_vender_id = ".$this->session->userdata("user_id")." ";
        }
        if ($this->session->userdata("user_type")=="C" && $this->session->userdata("user_id") >0) {
               $sql.= " and t.celebrity_id = ".$this->session->userdata("user_id")." ";
        }
        $sql.= " order by thanku_commission_id DESC";
        $rs = $this->db->query($sql);
          $result = $rs->result_array();


        return $result;
    }
    function promotedCommissionReport($data)
    {
         $sql = " select *,pa.image as product_image,u.user_first_name as user_first_name,u.user_last_name as user_last_name,u2.user_first_name as userfirstname,u2.user_last_name as userlastname from product_order_history h,product_order_details d,product p,product_attribute pa,celebrity_commission_perc cp,user_table u,user_table u2 where h.product_id=p.product_id  and pa.product_id=p.product_id and h.product_attribute_id=pa.product_attribute_id
		      and h.celebrity_id is not null and h.celebrity_id=u.user_id and cp.cel_com_status=1 and d.order_block_id=h.order_block_id and h.user_id=u2.user_id ";

        if ($this->session->userdata("user_type")=="V" && $this->session->userdata("user_id") >0) {
            $sql.= " and  p.product_vender_id = ".$this->session->userdata("user_id")." ";
        }
        if ($this->session->userdata("user_type")=="C" && $this->session->userdata("user_id") >0) {
            $sql.= " and  h.celebrity_id = ".$this->session->userdata("user_id")." ";
        }
               $sql.= " order by h.order_block_id DESC ";

             $rs = $this->db->query($sql);
         return $result = $rs->result_array();
    }
    function getSocialArticles()
    {
               $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
               $language=1;
               $this->db->select('a3.article_type_desc,a.*,a.articles_desc as arbicname,a2.articles_desc as englishname');
               $this->db->from('articles_social a');
               $this->db->join('articles_social a2', 'a2.articles_id =a.articles_id', 'inner');
               $this->db->join('articles_type_social a3', 'a3.article_type_id =a.articles_type_id', 'inner');
               $this->db->where('a.articles_language_code', 1);
               $this->db->where('a2.articles_language_code', 2);
               $this->db->where('a3.article_type_language_code', $language);
               $this->db->order_by('a.articles_id', 'desc');
                //$this->db->limit($limit, $start);
               $query = $this->db->get();
                  //echo $this->db->last_query();
                return $query->result();
    }
    function getSocialArticleTypes()
    {

        $query = $this->db->get_where('articles_type_social', array());
        return $query->result();
    }
    function saveSocialArticle($data)
    {
              $this->db->trans_start();



               $this->db->select('count(articles_id) as counter');
               $this->db->from('articles_social c');
               $this->db->where('articles_language_code', 1);
               $this->db->where('articles_type_id', $data['txt_article_type']);
               $query = $this->db->get();
              // echo $this->db->last_query();
               $res  =  $query->row();
               $count              =   ($res->counter>0?$res->counter:0);



        $inputArray[0]['articles_type_id']          =    $data['txt_article_type'] ;
        $inputArray[0]['articles_desc']             =    $data['txt_article'] ;
        $inputArray[0]['articles_status']           =    1 ;
        $inputArray[0]['articles_created_date']     =    gmdate("Y-m-d H:i:s") ;
        $inputArray[0]['articles_language_code']    =    1 ;


        $inputArray[1]                              =    $inputArray[0] ;
        $inputArray[1]['articles_language_code']    =    2 ;
         $inputArray[1]['articles_desc']             =   $data['txt_article'] ;

        if ($count>0) {
           //$articleId                                  =    $data['id'];
            $inputArray[0]['articles_updated_date']     =    gmdate("Y-m-d H:i:s") ;
            $inputArray[1]['articles_updated_date']     =    gmdate("Y-m-d H:i:s") ;

            unset($inputArray[0]['articles_created_date']);
            unset($inputArray[1]['articles_created_date']);



            $this->db->where('articles_language_code', 1);
            $this->db->where('articles_type_id', $data['txt_article_type']);
            $this->db->update('articles_social', $inputArray[0]);

            $this->db->where('articles_language_code', 2);
            $this->db->where('articles_type_id', $data['txt_article_type']);
            $this->db->update('articles_social', $inputArray[1]);
        } else {
                           $this->db->select('max(articles_id) as maxid');
                           $this->db->from('articles_social c');
                           $this->db->where('articles_language_code', 1);
                           $query = $this->db->get();
                          // echo $this->db->last_query();
                           $res  =  $query->row();
                           $maxId              =   ($res->maxid>0?$res->maxid+1:1);

                           $inputArray[0]['articles_id']               =    $maxId ;

                           $inputArray[1]['articles_id']               =    $maxId ;



                          $this->db->insert_batch('articles_social', $inputArray);
        }


         $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
             return 0;
        } else {
            return 1;
        }
    }
    function getSocialArticlesById($language, $id)
    {

        $query = $this->db->get_where('articles_social', array('articles_language_code'=>$language,'articles_id'=>$id));
        return $query->row();
    }
    function deleteSocialArticle($id)
    {
        $this->db->trans_start();
        $this -> db -> where('articles_id', $id);
        $this -> db -> delete('articles_social');
        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
                         return 0;
        } else {
                           return 1;
        }
    }
    function getSocialArticleData($id)
    {
        //$id=25;
        $sql="select  * from articles_social s,articles_type_social t where t.article_type_id=s.articles_type_id and articles_language_code =article_type_language_code and article_type_language_code=1 and article_type_id=".$id."";
        $rs = $this->db->query($sql);
        return $result = $rs->row_array();
    }
    function getNewsLetters()
    {
        $sql="select  * from newsletter order by newsletter_id DESC ";
        $rs = $this->db->query($sql);
        return $result = $rs->result_array();
    }
    function getAllTeyaarCommission()
    {
        $sql="select  * from teyaar_commission order by teyaar_commission_id DESC ";
        $rs = $this->db->query($sql);
        return $result = $rs->result_array();
    }
    function getAllEnquieries()
    {
        $sql="select  * from contact_us order by id DESC ";
        $rs = $this->db->query($sql);
        return $result = $rs->result_array();
    }
    function saveTeyaarCommission($data)
    {
          $this->db->trans_start();

         //// print_r();

        if ($data['txtStatus']==1) {
            $update['status']   = 0;
            $this->db->update('teyaar_commission', $update);
        }
        //teyaar_commission_id  teyaar_commission   status  added_date


        $input['status']              =   $data['txtStatus'];
        $input['teyaar_commission']   =   $data['txt_teyaar_com'];

        if ($data['comm_id']>0) {
            $this->db->where('teyaar_commission_id', $data['comm_id']);
            $this->db->update('teyaar_commission', $input);

            $entityId  =  $data['comm_id'];
            $action    =  2;
        } else {
              $input['added_date']   =   gmdate("Y-m-d H:i:s");
              $this->db->insert('teyaar_commission', $input);
              $entityId   = $this->db->insert_id();
              $action    =  1;
        }


        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        $auditArray                     =    array();
        $auditArray['admin_id']         =    $this->session->userdata('admin_id');
        $auditArray['module_id']        =    25;
        $auditArray['entity_id']        =    $entityId;
        $auditArray['action_id']        =    $action;
        $auditArray['audit_time']       =    gmdate("Y-m-d H:i:s");
        $auditArray['audit_note']       =    "";
        $auditArray['menu_id']          =    5;
        $this->db->insert('admin_audit_trial', $auditArray);

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial



        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
                         return 0;
        } else {
                       return 1;
        }
    }
    function saveChangePassword($data)
    {
        $sql="select  count(admin_user_password) as count from admin_user where admin_user_password= '".MD5($data["txt_old_password"])."' ";
        $rs = $this->db->query($sql);
        $count = $result = $rs->row()->count;
        if ($count<=0) {
            return -1;
        } else {
            $this->db->trans_start();

             $input['admin_user_password']  =  MD5($data["txt_new_password"]);

             $this->db->where('admin_user_id', 1);
             $this->db->update('admin_user', $input);

             $this->db->trans_complete();


            if ($this->db->trans_status() === false) {
                             return 0;
            } else {
                           return 1;
            }
        }
    }
    function getCitywiseSalesCount()
    {
        $sql=" select city_name,count(order_block_id) from product_order_details d,user_shiping_details s ,city c where d.shipping_address_id=s.user_shiping_details_id
and c.city_id= user_shiping_details_city and  city_language_code=1 group by city_name order by city_name ASC";
        $rs = $this->db->query($sql);
        return $result = $rs->result_array();
    }
    function getGenderwiseSaleCount()
    {
        $sql=" select user_gender,count(order_block_id) from product_order_details d,user_table u  where d.user_id=u.user_id group by user_gender order by user_gender ASC";
        $rs = $this->db->query($sql);
        return $result = $rs->result_array();
    }
    function listGenderWiseReportCount($data)
    {

        $sql="select distinct product_name,p.product_id,u.user_gender,concat(u2.user_first_name,' ', u2.user_last_name) as vendor_name,store_name,count(d.order_block_id) from product p LEFT JOIN product_order_history h on p.product_id=h.product_id

LEFT JOIN product_order_details d ON d.order_block_id=h.order_block_id LEFT JOIN user_table u on u.user_id=d.user_id

LEFT JOIN user_table u2 ON p.product_vender_id=u2.user_id

LEFT JOIN seller_details s ON s.user_id=u2.user_id

WHERE p.product_status=1 ";

        if ($data['genderCombo']>0) {
                $sql.=      " and  u.user_gender=".$data['genderCombo']." ";
        }
        if ($data['txt_sale_datefrom']!="" && $data['txt_sale_dateto']!="") {
            $sql.=      " and date(d.order_placed_date)>='".$data['txt_sale_datefrom']."' and  date(d.order_placed_date)<='".$data['txt_sale_dateto']."' ";
        }

                    $sql.=      "GROUP BY product_name,p.product_id,u.user_gender,u2.user_first_name,u2.user_last_name,store_name order by product_name ASC  ";

                    $rs = $this->db->query($sql);

                    $rs = $this->db->query($sql);
                    $result = $rs->result_array();
                    $count = count($result);
                    $array['count']          = $count;
                    $array = (object) $array;
                    return $array;
    }
    function listGenderWiseReport($data, $limit_per_page, $start_index)
    {

         $sql="select distinct product_name,p.product_id,u.user_gender,concat(u2.user_first_name,' ', u2.user_last_name) as vendor_name,store_name,count(d.order_block_id) from product p LEFT JOIN product_order_history h on p.product_id=h.product_id

LEFT JOIN product_order_details d ON d.order_block_id=h.order_block_id LEFT JOIN user_table u on u.user_id=d.user_id

LEFT JOIN user_table u2 ON p.product_vender_id=u2.user_id

LEFT JOIN seller_details s ON s.user_id=u2.user_id

WHERE p.product_status=1 ";

        if ($data['genderCombo']>0) {
            $sql.=      " and u.user_gender=".$data['genderCombo']." ";
        }
        if ($data['txt_sale_datefrom']!="" && $data['txt_sale_dateto']!="") {
            $sql.=      " and date(d.order_placed_date)>='".$data['txt_sale_datefrom']."' and  date(d.order_placed_date)<='".$data['txt_sale_dateto']."' ";
        }

        $sql.=      "GROUP BY product_name,p.product_id,u.user_gender,u2.user_first_name,u2.user_last_name,store_name order by count DESC ";

        $sql.= "   offset ".$start_index."   limit  ".$limit_per_page."";
     // echo  $sql;

          $rs = $this->db->query($sql);

        return $row = $rs->result_array();
    }
    function listRegionWiseReportCount($data)
    {

                $sql="select distinct product_name,p.product_id,u.user_shiping_details_city,city_name,concat(u2.user_first_name,' ', u2.user_last_name) as vendor_name,store_name,count(h.order_block_id) from product p LEFT JOIN product_order_history h on p.product_id=h.product_id

LEFT JOIN product_order_details d ON d.order_block_id=h.order_block_id LEFT JOIN user_shiping_details u on u.user_shiping_details_id=d.shipping_address_id

LEFT JOIN user_table u2 ON p.product_vender_id=u2.user_id

LEFT JOIN seller_details s ON s.user_id=u2.user_id

LEFT JOIN city c ON c.city_id=u.user_shiping_details_city and c.city_language_code=1

WHERE p.product_status=1 ";

        if ($data['regionCombo']>0) {
            $sql.=      " and  u.user_shiping_details_city=".$data['regionCombo']." ";
        }
        if ($data['txt_sale_datefrom']!="" && $data['txt_sale_dateto']!="") {
            $sql.=      " and date(d.order_placed_date)>='".$data['txt_sale_datefrom']."' and  date(d.order_placed_date)<='".$data['txt_sale_dateto']."' ";
        }

        $sql.=      "GROUP BY product_name,p.product_id,u.user_shiping_details_city,u2.user_first_name,u2.user_last_name,store_name,city_name  order by count desc ";

                $rs = $this->db->query($sql);

          $rs = $this->db->query($sql);
          $result = $rs->result_array();
          $count = count($result);
          $array['count']          = $count;
          $array = (object) $array;
          return $array;
    }
    function listRegionWiseReport($data, $limit_per_page, $start_index)
    {

         $sql="select distinct product_name,p.product_id,u.user_shiping_details_city,city_name,concat(u2.user_first_name,' ', u2.user_last_name) as vendor_name,store_name,count(h.order_block_id) from product p LEFT JOIN product_order_history h on p.product_id=h.product_id

LEFT JOIN product_order_details d ON d.order_block_id=h.order_block_id LEFT JOIN user_shiping_details u on u.user_shiping_details_id=d.shipping_address_id

LEFT JOIN user_table u2 ON p.product_vender_id=u2.user_id

LEFT JOIN seller_details s ON s.user_id=u2.user_id

LEFT JOIN city c ON c.city_id=u.user_shiping_details_city and c.city_language_code=1

WHERE p.product_status=1 ";

        if ($data['regionCombo']>0) {
            $sql.=      " and u.user_shiping_details_city=".$data['regionCombo']." ";
        }
        if ($data['txt_sale_datefrom']!="" && $data['txt_sale_dateto']!="") {
            $sql.=      " and date(d.order_placed_date)>='".$data['txt_sale_datefrom']."' and  date(d.order_placed_date)<='".$data['txt_sale_dateto']."' ";
        }

        $sql.=      "GROUP BY product_name,p.product_id,u.user_shiping_details_city,u2.user_first_name,u2.user_last_name,store_name,city_name  order by count desc";

        $sql.= "   offset ".$start_index."   limit  ".$limit_per_page."";
     // echo  $sql;

          $rs = $this->db->query($sql);

        return $row = $rs->result_array();
    }
    function listSeasonWiseReportCount($data)
    {

                $sql="select distinct product_name,p.product_id,concat(u2.user_first_name,' ', u2.user_last_name) as vendor_name,store_name,count(h.order_block_id) from product p LEFT JOIN product_order_history h on p.product_id=h.product_id

LEFT JOIN product_order_details d ON d.order_block_id=h.order_block_id LEFT JOIN user_shiping_details u on u.user_shiping_details_id=d.shipping_address_id

LEFT JOIN user_table u2 ON p.product_vender_id=u2.user_id

LEFT JOIN seller_details s ON s.user_id=u2.user_id

LEFT JOIN city c ON c.city_id=u.user_shiping_details_city and c.city_language_code=1

WHERE p.product_status=1 ";

        if ($data['regionCombo']>0) {
            $sql.=      " and  u.user_shiping_details_city=".$data['regionCombo']." ";
        }
        if ($data['txt_sale_datefrom']!="" && $data['txt_sale_dateto']!="") {
            $sql.=      " and date(d.order_placed_date)>='".$data['txt_sale_datefrom']."' and  date(d.order_placed_date)<='".$data['txt_sale_dateto']."' ";
        }

        $sql.=      " GROUP BY product_name,p.product_id,u2.user_first_name,u2.user_last_name,store_name  order by count desc ";

                $rs = $this->db->query($sql);

          $rs = $this->db->query($sql);
          $result = $rs->result_array();
          $count = count($result);
          $array['count']          = $count;
          $array = (object) $array;
          return $array;
    }
    function listSeasonWiseReport($data, $limit_per_page, $start_index)
    {

         $sql=" select distinct product_name,p.product_id,concat(u2.user_first_name,' ', u2.user_last_name) as vendor_name,store_name,count(h.order_block_id) from product p LEFT JOIN product_order_history h on p.product_id=h.product_id

LEFT JOIN product_order_details d ON d.order_block_id=h.order_block_id LEFT JOIN user_shiping_details u on u.user_shiping_details_id=d.shipping_address_id

LEFT JOIN user_table u2 ON p.product_vender_id=u2.user_id

LEFT JOIN seller_details s ON s.user_id=u2.user_id

LEFT JOIN city c ON c.city_id=u.user_shiping_details_city and c.city_language_code=1

WHERE p.product_status=1  ";

        if ($data['regionCombo']>0) {
            $sql.=      " and u.user_shiping_details_city=".$data['regionCombo']." ";
        }
        if ($data['txt_sale_datefrom']!="" && $data['txt_sale_dateto']!="") {
            $sql.=      " and date(d.order_placed_date)>='".$data['txt_sale_datefrom']."' and  date(d.order_placed_date)<='".$data['txt_sale_dateto']."' ";
        }

        $sql.=      "GROUP BY product_name,p.product_id,u2.user_first_name,u2.user_last_name,store_name  order by count desc";

        $sql.= "   offset ".$start_index."   limit  ".$limit_per_page."";
     // echo  $sql;

          $rs = $this->db->query($sql);

        return $row = $rs->result_array();
    }
    function listPriceWiseReportCount($data)
    {

        if ($data['txt_price_from']=="" && $data['txt_price_to']=="") {
            $fromPrice   = 0;
            $toPrice     = 100000;
        } else if ($data['txt_price_from']=="" && $data['txt_price_to']!="") {
            $fromPrice   =  0;
            $toPrice     =  $data['txt_price_to'];
        } else if ($data['txt_price_from']!="" && $data['txt_price_to']=="") {
               $fromPrice   =  $data['txt_price_from'];
               $toPrice     =  $data['txt_price_from'];
        } else {
            $fromPrice   =  $data['txt_price_from'];
            $toPrice     =  $data['txt_price_to'];
        }
         $sql=" select distinct product_name,p.product_id,concat(u2.user_first_name,' ', u2.user_last_name) as vendor_name,store_name,pa.sale_price,count(h.order_block_id)
 from product p LEFT JOIN product_order_history h on p.product_id=h.product_id LEFT JOIN product_order_details d ON d.order_block_id=h.order_block_id
 LEFT JOIN user_shiping_details u on u.user_shiping_details_id=d.shipping_address_id
 LEFT JOIN user_table u2 ON p.product_vender_id=u2.user_id
 LEFT JOIN   seller_details s ON s.user_id=u2.user_id
 LEFT JOIN city c ON c.city_id=u.user_shiping_details_city and c.city_language_code=1
 LEFT JOIN product_attribute pa ON p.product_id=pa.product_id WHERE p.product_status=1
 ";

            $sql.=      " and pa.sale_price<=".$toPrice." and  pa.sale_price>=".$fromPrice." ";


        if ($data['txt_sale_datefrom']!="" && $data['txt_sale_dateto']!="") {
            $sql.=      " and date(d.order_placed_date)>='".$data['txt_sale_datefrom']."' and  date(d.order_placed_date)<='".$data['txt_sale_dateto']."' ";
        }

            $sql.=      " GROUP BY product_name,p.product_id,u2.user_first_name,  u2.user_last_name,store_name,pa.sale_price order by count desc ";

                $rs = $this->db->query($sql);

          $rs = $this->db->query($sql);
          $result = $rs->result_array();
          $count = count($result);
          $array['count']          = $count;
          $array = (object) $array;
          return $array;
    }
    function listPriceWiseReport($data, $limit_per_page, $start_index)
    {

        if ($data['txt_price_from']=="" && $data['txt_price_to']=="") {
            $fromPrice   = 0;
            $toPrice     = 100000;
        } else if ($data['txt_price_from']=="" && $data['txt_price_to']!="") {
            $fromPrice   =  0;
            $toPrice     =  $data['txt_price_to'];
        } else if ($data['txt_price_from']!="" && $data['txt_price_to']=="") {
               $fromPrice   =  $data['txt_price_from'];
               $toPrice     =  $data['txt_price_from'];
        } else {
            $fromPrice   =  $data['txt_price_from'];
            $toPrice     =  $data['txt_price_to'];
        }

         $sql="
             select distinct product_name,p.product_id,concat(u2.user_first_name,' ', u2.user_last_name) as vendor_name,store_name,pa.sale_price,count(h.order_block_id)
 from product p LEFT JOIN product_order_history h on p.product_id=h.product_id LEFT JOIN product_order_details d ON d.order_block_id=h.order_block_id
 LEFT JOIN user_shiping_details u on u.user_shiping_details_id=d.shipping_address_id
 LEFT JOIN user_table u2 ON p.product_vender_id=u2.user_id
 LEFT JOIN   seller_details s ON s.user_id=u2.user_id
 LEFT JOIN city c ON c.city_id=u.user_shiping_details_city and c.city_language_code=1
 LEFT JOIN product_attribute pa ON p.product_id=pa.product_id WHERE p.product_status=1 ";

            $sql.=      " and pa.sale_price<=".$toPrice." and  pa.sale_price>=".$fromPrice." ";


        if ($data['txt_sale_datefrom']!="" && $data['txt_sale_dateto']!="") {
            $sql.=      " and date(d.order_placed_date)>='".$data['txt_sale_datefrom']."' and  date(d.order_placed_date)<='".$data['txt_sale_dateto']."' ";
        }

            $sql.=      " GROUP BY product_name,p.product_id,u2.user_first_name,  u2.user_last_name,store_name,pa.sale_price order by count desc ";

            $sql.= "   offset ".$start_index."   limit  ".$limit_per_page."";
     // echo  $sql;

          $rs = $this->db->query($sql);

            return $row = $rs->result_array();
    }
    function listSellingWiseReportCount($data)
    {


         $sql=" select distinct product_name,p.product_id,concat(u2.user_first_name,' ', u2.user_last_name) as vendor_name,store_name,count(h.order_block_id)
 from product p LEFT JOIN product_order_history h on p.product_id=h.product_id LEFT JOIN product_order_details d ON d.order_block_id=h.order_block_id
 LEFT JOIN user_shiping_details u on u.user_shiping_details_id=d.shipping_address_id
 LEFT JOIN user_table u2 ON p.product_vender_id=u2.user_id
 LEFT JOIN   seller_details s ON s.user_id=u2.user_id
 LEFT JOIN city c ON c.city_id=u.user_shiping_details_city and c.city_language_code=1
 WHERE p.product_status=1
 ";




        if ($data['txt_sale_datefrom']!="" && $data['txt_sale_dateto']!="") {
            $sql.=      " and date(d.order_placed_date)>='".$data['txt_sale_datefrom']."' and  date(d.order_placed_date)<='".$data['txt_sale_dateto']."' ";
        }

        $sql.=      " GROUP BY product_name,p.product_id,u2.user_first_name,  u2.user_last_name,store_name order by count desc ";

                $rs = $this->db->query($sql);

          $rs = $this->db->query($sql);
          $result = $rs->result_array();
          $count = count($result);
          $array['count']          = $count;
          $array = (object) $array;
          return $array;
    }
    function listSellingWiseReport($data, $limit_per_page, $start_index)
    {
        //print_r($data);

         $sql="
             select distinct product_name,p.product_id,concat(u2.user_first_name,' ', u2.user_last_name) as vendor_name,store_name,count(h.order_block_id)
 from product p LEFT JOIN product_order_history h on p.product_id=h.product_id LEFT JOIN product_order_details d ON d.order_block_id=h.order_block_id
 LEFT JOIN user_shiping_details u on u.user_shiping_details_id=d.shipping_address_id
 LEFT JOIN user_table u2 ON p.product_vender_id=u2.user_id
 LEFT JOIN   seller_details s ON s.user_id=u2.user_id
 LEFT JOIN city c ON c.city_id=u.user_shiping_details_city and c.city_language_code=1
  WHERE p.product_status=1 ";




        if ($data['txt_sale_datefrom']!="" && $data['txt_sale_dateto']!="") {
            $sql.=      " and date(d.order_placed_date)>='".$data['txt_sale_datefrom']."' and  date(d.order_placed_date)<='".$data['txt_sale_dateto']."' ";
        }

        $sql.=      " GROUP BY product_name,p.product_id,u2.user_first_name,  u2.user_last_name,store_name  ";

        if ($data['sellingCombo']>0) {
            if ($data['sellingCombo']==1) {
                $sql.=      " order by count desc";
            } else {
                $sql.=      " order by count asc";
            }
        } else {
                $sql.=      " order by count desc";
        }

        $sql.= "   offset ".$start_index."   limit  ".$limit_per_page."";
     // echo  $sql;

          $rs = $this->db->query($sql);

        return $row = $rs->result_array();
    }
    function getAllCelebrityPerc($data, $limit_per_page, $start_index)
    {
        $vendorId = $this->session->userdata("user_id");

        $sql=      "  select perc_id,concat(u1.user_first_name,' ', u1.user_last_name) as celebrity_name,concat(u2.user_first_name,' ', u2.user_last_name) as vendor_name,p.product_name,perc_status,perc,perc_added_date,perc_from_date,perc_to_date

  FROM product_celebrity_perc pe,product p ,user_table u1,user_table u2

  WHERE pe.product_id=p.product_id and pe.celebrity_id=u1.user_id and p.product_vender_id=u2.user_id  ";

        if ($this->session->userdata("user_type")=="V") {
             $sql.=      " and pe.vendor_id=".$vendorId." ";
        }
        if ($data['search_key']!="") {
            $search_key          =   strtolower($data['search_key']);

            $sql.=      " and ( LOWER(u1.user_first_name) like  '%". $search_key."%' or LOWER(u1.user_last_name) like  '%". $search_key."%' or LOWER(u2.user_last_name) like  '%". $search_key."%' or LOWER(u2.user_first_name) like  '%". $search_key."%' or LOWER(product_name) like  '%". $search_key."%' ) ";
        }

        $sql.=      " order by perc_status DESC,product_name ASC,celebrity_name ASC ";

        $sql.= "   offset ".$start_index."   limit  ".$limit_per_page."";

        $rs = $this->db->query($sql);

        return $row = $rs->result_array();
    }
    function getAllCelebrityPercCount($data)
    {
        $vendorId = $this->session->userdata("user_id");

        $sql=      "  select concat(u1.user_first_name,' ', u1.user_last_name) as celebrity_name,concat(u2.user_first_name,' ', u2.user_last_name) as vendor_name,p.product_name,perc_status,perc,perc_added_date,perc_from_date,perc_to_date

  FROM product_celebrity_perc pe,product p ,user_table u1,user_table u2

  WHERE pe.product_id=p.product_id and pe.celebrity_id=u1.user_id and p.product_vender_id=u2.user_id  ";

        if ($this->session->userdata("user_type")=="V") {
             $sql.=      " and pe.vendor_id=".$vendorId." ";
        }

        if ($data['search_key']!="") {
            $search_key          =   strtolower($data['search_key']);

            $sql.=      " and ( LOWER(u1.user_first_name) like  '%". $search_key."%' or LOWER(u1.user_last_name) like  '%". $search_key."%' or LOWER(u2.user_last_name) like  '%". $search_key."%' or LOWER(u2.user_first_name) like  '%". $search_key."%' or LOWER(product_name) like  '%". $search_key."%' ) ";
        }


        $sql.=      " order by perc_status DESC,product_name ASC,celebrity_name ASC";
        $rs = $this->db->query($sql);

         $result = $rs->result_array();
          $count = count($result);
          $array['count']          = $count;
          $array = (object) $array;
          return $array;
    }
    function deleteCelebrityPerc($data)
    {
           $this->db->trans_start();

           $id= $data['id'];

              $this -> db -> where('perc_id', $id);
              $this -> db -> delete('product_celebrity_perc');



             $this->db->trans_complete();


        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }
    function getPendingCheckoutList()
    {
       /* $sql=      " select cart_id,product_name,p.product_id,pa.product_attribute_id,concat(u1.user_first_name,' ', u1.user_last_name) as name ,cart_created_date,sum(quantity) from cart c,user_table u1,product p,product_attribute pa

WHERE p.product_id=pa.product_id and c.user_id=u1.user_id and product_status=1 and pa.stock_quantity>0   ";



  $date = date("Y-m-d");

 $sql.= "     and date(p.product_sale_from)<='".$date."' and   date(p.product_sale_to)>='".$date."' and c.product_id=p.product_id and pa.product_attribute_id=c.product_attribute_id  ";


  $sql.= "  GROUP BY cart_id,u1.user_first_name,u1.user_last_name,product_name,pa.product_attribute_id,p.product_id  ORDER BY cart_created_date ASC "; */


        $sql=      "select distinct c.user_id,concat(u1.user_first_name,' ', u1.user_last_name) as name ,date(cart_created_date),count(c.user_id) from user_table u1

LEFT JOIN cart c ON u1.user_id=c.user_id

LEFT JOIN product p ON p.product_id=c.product_id

LEFT JOIN product_attribute pa ON pa.product_attribute_id=c.product_attribute_id

WHERE  c.user_id>0 and product_status=1 and pa.stock_quantity>0


GROUP BY  c.user_id,u1.user_first_name,u1.user_last_name,cart_created_date ORDER BY date(cart_created_date) ASC
 ";



        $rs = $this->db->query($sql);

        return $row = $rs->result_array();
    }
    function loadMyBag($userId)
    {



          /*  $sql = " select  p.*,pa.*,s.store_name
from product p,product_attribute pa,cart c,seller_details s      where  pa.product_id=p.product_id and c.product_id=p.product_id and pa.product_attribute_id=c.product_attribute_id and c.user_id=".$userId."  and s.user_id=p.product_vender_id ";*/

                   $sql = "   select  celebrity_id,product_vender_id,product_name,product_name_arabic,pa.image,p.product_desc_short,p.product_id,pa.sale_price,pa.product_attribute_id,pa.stock_quantity,s.store_name,s.mobile_no,sum(c.quantity) as count
from product p,product_attribute pa,cart c,seller_details s      where  pa.product_id=p.product_id and c.product_id=p.product_id
and pa.product_attribute_id=c.product_attribute_id
 ";
                $sql.= " and c.user_id='".$userId."' ";


             $sql.= " and s.user_id=p.product_vender_id  group by celebrity_id,product_vender_id,product_name,product_name_arabic,pa.image,p.product_desc_short,p.product_id,pa.sale_price,pa.product_attribute_id,pa.stock_quantity,s.store_name,s.mobile_no";
               $rs = $this->db->query($sql);
       // echo $this->db->last_query();


         $result  =   $rs->result_array();

        return $result;
    }
    function loadDesignation()
    {



         $sql     =  "   select  * from designation_master where designation_status=1 order by designation ASC";
         $rs      =  $this->db->query($sql);
         $result  =   $rs->result();

         return $result;
    }
    function getAdminUsers()
    {
         $sql     =  "   select  * from designation_master m,admin_user a where designation_status=1 and a.designation_id=designation_master_id ";
         $rs      =  $this->db->query($sql);
         $result  =   $rs->result();

         return $result;
    }
    function saveAdminUsers($data)
    {

        //Array ( [txt_first_name] => bvbvcb [txt_last_name] => bvcbv [txt_user_name] => vcbvcb [txt_email] => vbvcb@gmail.com [txt_password] => 3435545454 [txt_designation] => 2 [id] => 0 [txtStatus] => 0 [ci_csrf_token] => null )
         $input['admin_user_email']        =     $data['txt_email'] ;
         $input['admin_user_status']       =     $data['txtStatus'] ;
         $input['admin_user_created_date'] =     gmdate("Y-m-d H:i:s") ;
         $input['admin_user_password']     =     MD5($data['txt_password']) ;
         $input['admin_user_name']         =     $data['txt_user_name'] ;
         $input['admin_first_name']        =     $data['txt_first_name'] ;
         $input['admin_last_name']         =     $data['txt_last_name'] ;
         $input['designation_id']          =     $data['txt_designation'] ;

          $this->db->trans_start();
        if ($data['id']>0) {
              unset($input['admin_user_password']);

              $this->db->select('count(admin_user_email) as count');
              $this->db->from('admin_user c');
              $this->db->where('admin_user_email', $data['txt_email']);
              $this->db->where_not_in('admin_user_id', $data['id']);
              $query = $this->db->get();
              // echo $this->db->last_query();
            if ($query->row()->count>0) {
                return 3;
                exit;
            }

                $this->db->select('count(admin_user_email) as count');
                $this->db->from('admin_user c');
                $this->db->where('admin_user_name', $data['txt_user_name']);
                $this->db->where_not_in('admin_user_id', $data['id']);
                $query = $this->db->get();
                //    echo $this->db->last_query();
            if ($query->row()->count>0) {
                return 4;
                exit;
            }


                $this -> db -> where('admin_user_id', $data['id']);
                $this -> db -> update('admin_user', $input);
        } else {
            $this->db->select('count(admin_user_email) as count');
            $this->db->from('admin_user c');
            $this->db->where('admin_user_email', $data['txt_email']);
            $query = $this->db->get();
            // echo $this->db->last_query();
            if ($query->row()->count>0) {
                return 3;
                exit;
            }

            $this->db->select('count(admin_user_email) as count');
            $this->db->from('admin_user c');
            $this->db->where('admin_user_name', $data['txt_user_name']);
            $query = $this->db->get();
            //    echo $this->db->last_query();
            if ($query->row()->count>0) {
                return 4;
                exit;
            }


               $this -> db -> insert('admin_user', $input);
        }

                $this->db->trans_complete();


        if ($this->db->trans_status() === false) {
             return 0;
        } else {
              return 1;
        }
    }
    function approveAdmin($data)
    {
        $id                                =     $data['id'] ;
        $input['admin_user_status']        =     $data['status'] ;

        $this->db->trans_start();
        $this -> db -> where('admin_user_id', $id);
        $this -> db -> update('admin_user', $input);
        $this->db->trans_complete();


        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }
    function getMenus()
    {
         $sql     =  "   select  * from admin_menu where admin_menu_status=1	";
         $rs      =  $this->db->query($sql);
         $result  =   $rs->result();
         return $result;
    }
    function getAdminUserDetails($adminId)
    {
         $sql     =  "   select  * from admin_user where admin_user_id=".$adminId."	";
         $rs      =  $this->db->query($sql);
         $result  =   $rs->row();
         return $result;
    }
    function saveAdminPermission($data)
    {
                 $menu  =   $this->getMenus();
                 $i=0;
        foreach ($menu as $rows) {
            $input[$i]['menu_id']          =  $rows->admin_menu_id;
            $input[$i]['admin_user_id']    =  $data['admin_user_id'];
            $input[$i]['perm_view']        =  $data['txt_view'][$rows->admin_menu_id]>0?$data['txt_view'][$rows->admin_menu_id]:0 ;
     //  $input[$i]['perm_view']        =  1;
            $input[$i]['perm_add']         =  $data['txt_add'][$rows->admin_menu_id]>0?$data['txt_add'][$rows->admin_menu_id]:0 ;
            $input[$i]['perm_delete']      =  $data['txt_delete'][$rows->admin_menu_id]>0?$data['txt_delete'][$rows->admin_menu_id]:0 ;
            $input[$i]['perm_edit']        =  $data['txt_edit'][$rows->admin_menu_id]>0?$data['txt_edit'][$rows->admin_menu_id]:0 ;
            $input[$i]['perm_date']        =  gmdate("Y-m-d H:i:s");


            $i++;
        }


              $this->db->trans_start();

              $this -> db -> where('admin_user_id', $data['admin_user_id']);
              $this -> db -> delete('menu_permission');
              $this -> db -> insert_batch('menu_permission', $input);


              //admin audit trial //admin audit trial//admin audit trial//admin audit trial

                $auditArray                     =    array();
                $auditArray['admin_id']         =    $this->session->userdata('admin_id');
                $auditArray['module_id']        =    24;
                $auditArray['entity_id']        =    $data['admin_user_id'];
                $auditArray['action_id']        =    1;
                $auditArray['audit_time']       =    gmdate("Y-m-d H:i:s");
                $auditArray['audit_note']       =    "";
                $auditArray['menu_id']          =    2;
                $this->db->insert('admin_audit_trial', $auditArray);

                //admin audit trial //admin audit trial//admin audit trial//admin audit trial


              $this->db->trans_complete();


        if ($this->db->trans_status() === false) {
             return 0;
        } else {
              return 1;
        }
    }
    function getAdminPermissionsByMenu($adminId, $menuId)
    {
         $sql     =  "   select  * from menu_permission where admin_user_id=".$adminId." and menu_id=".$menuId."	";
         $rs      =  $this->db->query($sql);
         $result  =   $rs->row();
         return $result;
    }
    function deleteAdmin($data)
    {
              $this->db->trans_start();

              $this -> db -> where('admin_user_id', $data['admin_user_id']);
              $this -> db -> delete('admin_user');

              //admin audit trial //admin audit trial//admin audit trial//admin audit trial

                $auditArray                     =     array();
                $auditArray['admin_id']         =     $this->session->userdata('admin_id');
                $auditArray['module_id']        =     23;
                $auditArray['entity_id']        =     $data['admin_user_id'];
                $auditArray['action_id']        =     3;
                $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
                $auditArray['audit_note']       =     "";
                $auditArray['menu_id']          =     2;
                $this->db->insert('admin_audit_trial', $auditArray);

              //admin audit trial //admin audit trial//admin audit trial//admin audit trial


              $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
             return 0;
        } else {
            return 1;
        }
    }
    function changePasswordAdminUser($data)
    {
        $adminId                      =  $this->M_product->decryptId($data['pwdchid']);
        $input['admin_user_password'] =  MD5($data['txt_new_pwd']);

        $this->db->trans_start();
        $this->db->where("admin_user_id", $adminId);
        $this->db->update("admin_user", $input);

        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }
    function changePasswordUser($data)
    {
        $userId                     =  $this->M_product->decryptId($data['pwdchid']);
        $input['user_password']     =  password_hash($data['txt_new_pwd'], PASSWORD_DEFAULT, ['cost' => 12]);

        $this->db->trans_start();

        $this->db->where("user_id", $userId);
        $this->db->update("user_table", $input);

        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }
    function getUserType($userId)
    {
         $sql     =  "   select  user_type from user_table where user_id=".$userId."	";
         $rs      =  $this->db->query($sql);
         $result  =   $rs->row();
         return $result;
    }
    function getAudittrails()
    {
        $sql     =  "  select * from admin_audit_trial at,action_master am,admin_menu adm,module_master mm,admin_user au
WHERE at.action_id=am.action_id and adm.admin_menu_id=at.menu_id and mm.module_id=at.module_id and au.admin_user_id=at.admin_id order by audit_time desc	";
        $rs      =  $this->db->query($sql);
        $result  =   $rs->result();
        return $result;
    }
    function getDragonProfileImage($id)
    {
         $sql     =  "  select * from dragon_profile_image where profile_id=".$id." 	";
         $rs      =  $this->db->query($sql);
         $result  =   $rs->row();
         return $result;
    }
    function listauditTrailReportCount($data)
    {
         $sql     =  "  select * from admin_audit_trial at,action_master am,admin_menu adm,module_master mm,admin_user au
WHERE at.action_id=am.action_id and adm.admin_menu_id=at.menu_id and mm.module_id=at.module_id and au.admin_user_id=at.admin_id 	";

        $search_key  = strtolower($_POST['search_key']);

        if ($search_key!="") {
                $sql.=      " and ( LOWER(admin_menu_name) like  '%". $search_key."%' or LOWER(module_name) like  '%". $search_key."%' or LOWER(action_name) like  '%". $search_key."%' or LOWER(admin_first_name) like  '%". $search_key."%' or LOWER(admin_last_name) like  '%". $search_key."%' or LOWER(admin_user_email) like  '%". $search_key."%' or LOWER(admin_user_name) like  '%". $search_key."%') ";
        }
        if ($data['txt_sale_datefrom']!="" && $data['txt_sale_dateto']!="") {
            $sql.=      " and date(audit_time)>='".$data['txt_sale_datefrom']."' and  date(audit_time)<='".$data['txt_sale_dateto']."' ";
        }
        if ($data['txt_sale_datefrom']!="" && $data['txt_sale_dateto']=="") {
            $sql.=      " and date(audit_time)>='".$data['txt_sale_datefrom']."' and  date(audit_time)<='".$data['txt_sale_datefrom']."' ";
        }
        if ($data['txt_sale_datefrom']=="" && $data['txt_sale_dateto']!="") {
            $sql.=      " and date(audit_time)>='".$data['txt_sale_dateto']."' and  date(audit_time)<='".$data['txt_sale_dateto']."' ";
        }


         $rs      =  $this->db->query($sql);
         $result  =   $rs->result();
         $result = $rs->result_array();
         $count = count($result);
         $array['count']          = $count;
         $array = (object) $array;
         return $array;
    }
    function listauditTrailReport($data, $limit_per_page, $start_index)
    {
         $sql     =  "  select * from admin_audit_trial at,action_master am,admin_menu adm,module_master mm,admin_user au
                            WHERE at.action_id=am.action_id and adm.admin_menu_id=at.menu_id and mm.module_id=at.module_id and au.admin_user_id=at.admin_id 	";

        $search_key  = strtolower($_POST['search_key']);

        if ($search_key!="") {
                $sql.=      " and ( LOWER(admin_menu_name) like  '%". $search_key."%' or LOWER(module_name) like  '%". $search_key."%' or LOWER(action_name) like  '%". $search_key."%' or LOWER(admin_first_name) like  '%". $search_key."%' or LOWER(admin_last_name) like  '%". $search_key."%' or LOWER(admin_user_email) like  '%". $search_key."%' or LOWER(admin_user_name) like  '%". $search_key."%') ";
        }
        if ($data['txt_sale_datefrom']!="" && $data['txt_sale_dateto']!="") {
            $sql.=      " and date(audit_time)>='".$data['txt_sale_datefrom']."' and  date(audit_time)<='".$data['txt_sale_dateto']."' ";
        }
        if ($data['txt_sale_datefrom']!="" && $data['txt_sale_dateto']=="") {
            $sql.=      " and date(audit_time)>='".$data['txt_sale_datefrom']."' and  date(audit_time)<='".$data['txt_sale_datefrom']."' ";
        }
        if ($data['txt_sale_datefrom']=="" && $data['txt_sale_dateto']!="") {
            $sql.=      " and date(audit_time)>='".$data['txt_sale_dateto']."' and  date(audit_time)<='".$data['txt_sale_dateto']."' ";
        }

            $sql.= " order by audit_id DESC   offset ".$start_index."   limit  ".$limit_per_page."";

         $rs      =  $this->db->query($sql);

            return $result  =   $rs->result();
    }

    function getnotifications()
    {

        // $this->db->query('GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO a2itproducts');

        // $sql = "SELECT N.id,B.title,B.description,B.image,B.date,N.bulk_notification_id FROM notification AS N
        //           LEFT JOIN bulk_notifications AS B ON(N.bulk_notification_id = B.id)";

        // $this->db->select('DISTINCT("B"."id"),B.title,B.description,B.image,B.date,N.bulk_notification_id');
        // $this->db->from('notification N');
        // $this->db->join('bulk_notifications B', 'N.bulk_notification_id = B.id', 'left');

        $this->db->select('id,title,description,image,date');
        $this->db->from('bulk_notifications ');
        $rec = $this->db->get()->result_array();



        return $rec;
    }

    function deleteNotification($id)
    {
        $this->db->trans_start();

        $this->db->where('id', $id)
                 ->delete('bulk_notifications');

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
                return 0;
        } else {
            return 1;
        }
    }

    function get_user_fcm_token($condition = [])
    {

        if (count($condition) > 0) {
            $this->db->where($condition);
        }

        return $this->db->select("string_agg(user_device_token, ',') as fcm_tokens", false)
                        ->from("user_table")
                        ->get()
                        ->row();
    }

    function get_users($condition = [])
    {

        if (count($condition) > 0) {
            $this->db->where($condition);
        }

        return $this->db->select("*")
                        ->from("user_table")
                        ->get()
                        ->result();
    }

    function get_users1()
    {

        // return $this->db->query("select * from user_table where registration_type = 'U' OR registration_type = 'C'")->result();
         return $this->db->query("select * from user_table where user_type != 'V'")->result();


    }

    function get_user($condition = [])
    {

        return $this->db->select("*")
                        ->from("user_table")
                        ->where($condition)
                        ->get()
                        ->row();
    }

    function get_send_notification($notification_id)
    {
        return $this->db->select("*")
                        ->from("bulk_notifications")
                        ->where("id", $notification_id)
                        ->get()
                        ->row();
    }

    function get_customer_users( $condition=[] )
    {
        if (! empty($condition) ) {
            $this->db->where($condition);
        }
        return $this->db->select("*")
                        ->from("user_table")
                        ->order_by("user_first_name", "asc")
                        ->order_by("user_last_name", "asc")
                        ->where_in('user_type', ['C', 'U'])
                        ->get()
                        ->result();
    }

    function add_edit_notification()
    {

        //$this->load->model('Api_push_model', 'Api_push_model');

        if (!empty($_FILES['image']['tmp_name'])) {
            $digits   =  6;
            $_FILES['file']['name']     = $_FILES['image']['name'];
            $_FILES['file']['type']     = $_FILES['image']['type'];
            $_FILES['file']['tmp_name'] = $_FILES['image']['tmp_name'];
            $_FILES['file']['error']    = $_FILES['image']['error'];
            $_FILES['file']['size']     = $_FILES['image']['size'];

            $filename = $_FILES["file"]["name"];
            $file_ext = pathinfo($filename, PATHINFO_EXTENSION);
            $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

            $image_name             = "type".$randomNo.".".$file_ext;
            $full_image_name        = base_url().'uploads/notifications/' . $image_name;
            $uploadPath             = 'uploads/notifications/';
            $config['upload_path']  = $uploadPath;
            $config['allowed_types']= 'gif|GIF|jpg|JPG|jpeg|JPEG|png|PNG|';
            $config['file_name']    = $image_name;


            $this->load->library('upload', $config);
            $this->upload->initialize($config);

            if (!$this->upload->do_upload('file')) {
                $image_name         = '';
                $full_image_name    = '';
            }

            //$_POST['image'] = $image_name;
        }


        // $edit_id = $this->input->post('edit_id');
        $title          = $this->input->post('title');
        $description    = $this->input->post('description');
        $url            = $this->input->post('url');

        $data_array     = array('title'=>$title,
                                'description'=>$description,
                                'url' => $url,
                                'date'=>date('Y-m-d'),
                                'status'=>'1');

        if (!empty($image_name)) {
            $data_array['image'] =$image_name ;
        }

        $this->db->insert('bulk_notifications', $data_array);

        return $this->db->insert_id("bulk_notifications_id_seq");

        //No more execution from here

        if ($this->db->insert('bulk_notifications', $data_array)) {
            $bulk_notification_id =  $this->db->insert_id();

            $sql = "SELECT DISTINCT(user_device_token),firebase_user_key FROM user_table WHERE user_device_token != '' AND registration_type='c' OR registration_type='c' ";
            $rec = $this->db->query($sql)->result_array();
                  // print_r($rec);exit;

            if (count($rec) > 0) {
                $chek_array = [];

                foreach ($rec as $row) {
                    $chek_array[] = $dev_tockon;
                    if (in_array($chek_array, $dev_tockon)) {
                        continue;
                    } else if (!empty($row['firebase_user_key'])) {
                        $dev_tockon            =   $row['user_device_token'];
                    }
                        $firebase_user_key     =   $row['firebase_user_key'];

                        $title      = $title;
                        $body       = $description;
                        $clickaction='public-notification';

                        //   $params = array('type'=>$clickaction,'campaign_id'=>'','productId'=>'' );

                        $params = array('notificationType'=>$clickaction,'campaign_id'=>'0','order_id'=>'0','productId'=>'0','title'=>$title,'description'=>$body,'notification_id'=>$bulk_notification_id );

                        $this->Api_push_model->sendNotificationSingle($dev_tockon, $title, $body, $params, $clickaction);

                        $data_array = array(
                            'title'                 => $title,
                            'message'               => $body,
                            'type'                  => $clickaction,
                            'booking_id'            => '0',
                            'to_id'                 => $firebase_user_key,
                            'from_id'               => '0',
                            'notification_date'     => date('Y-m-d'),
                            'bulk_notification_id'  => $bulk_notification_id,
                            'status'                => 1
                        );

                        $this->db->insert('notification', $data_array);
                        $notification_id = $this->db->insert_id();



                        $push_data['data']['fromUserID']              = '';
                        $push_data['data']['touserID']                = $firebase_user_key;
                        $push_data['data']['title']                   = $title;
                        $push_data['data']['message']                 = $body;
                        $push_data['data']['order_id']                = '';
                        $push_data['data']['image']                   = ''.$full_image_name;
                        $push_data['data']['msg_type']                = $clickaction;
                        $push_data['data']['notification_id']         = $bulk_notification_id;

                        $push_data['data']['campaign_id']         = $campaign_id;
                        $push_data['data']['productId']         = $productId;


                        $this->load->view("firebase_notification", $push_data);
                }
            }
        } else {
            return false;
        }


        if (!empty($notification_id)) {
        }
        return true;
    }





    function create_privacy_policy($data)
    {
        $this->db->insert("privacy_policy", $data);
        return $this->db->insert_id("privacy_policy_privacy_policy_id_seq");
    }

    function update_privacy_policy($data, $condition)
    {
        $this->db->where($condition)
                 ->update("privacy_policy", $data);

        return $this->db->affected_rows();
    }

    function get_privacy_policies()
    {

        return $this->db->select("*")
                        ->from("privacy_policy")
                        ->order_by("privacy_policy_id", "desc")
                        ->get()
                        ->result();
    }

    function get_privacy_policy($id)
    {

        return $this->db->select("*")
                        ->from("privacy_policy")
                        ->where("privacy_policy_id", $id)
                        ->get()
                        ->row();
    }

    function delete_privacy_policy($id)
    {
        $this->db->where("privacy_policy_id", $id)
                 ->delete("privacy_policy");

        return $this->db->affected_rows();
    }

    function create_terms_and_conditions($data)
    {
        $this->db->insert("terms_and_conditions", $data);
        return $this->db->insert_id("terms_and_conditions_tc_id_seq");
    }

    function update_terms_and_conditions($data, $condition)
    {
        $this->db->where($condition)
                 ->update("terms_and_conditions", $data);

        return $this->db->affected_rows();
    }

    function get_terms_and_conditions_list()
    {

        return $this->db->select("*")
                        ->from("terms_and_conditions")
                        ->order_by("tc_id", "desc")
                        ->get()
                        ->result();
    }

    function get_terms_and_conditions($id)
    {

        return $this->db->select("*")
                        ->from("terms_and_conditions")
                        ->where("tc_id", $id)
                        ->get()
                        ->row();
    }

    function delete_terms_and_conditions($id)
    {
        $this->db->where("tc_id", $id)
                 ->delete("terms_and_conditions");

        return $this->db->affected_rows();
    }

    function create_faq($data)
    {
        $this->db->insert("faq", $data);
        return $this->db->insert_id("faq_faq_id_seq");
    }

    function update_faq($data, $condition)
    {
        $this->db->where($condition)
                 ->update("faq", $data);

        return $this->db->affected_rows();
    }

    function get_faq_list()
    {

        return $this->db->select("*")
                        ->from("faq")
                        ->order_by("faq_id", "desc")
                        ->get()
                        ->result();
    }

    function get_faq($id)
    {

        return $this->db->select("*")
                        ->from("faq")
                        ->where("faq_id", $id)
                        ->get()
                        ->row();
    }

    function delete_faq($id)
    {
        $this->db->where("faq_id", $id)
                 ->delete("faq");

        return $this->db->affected_rows();
    }

    public function get_user_list($condition = [])
    {

        if (count($condition) > 0) {
            $this->db->where($condition);
        }

        return $this->db->select("*")
                        ->from("user_table")
                        ->order_by("user_first_name", "asc")
                        ->order_by("user_last_name", "asc")
                        ->get()
                        ->result();
    }

    public function getAdminDepositedCashPoints()
    {

        return $this->db->select("*")
                        ->from("cash_points")
                        ->join("user_table", "cash_points.cp_user_id=user_table.user_id", "left")
                        ->where("cp_status", "5")
                        ->order_by('cash_points_id', 'desc')
                        ->get()
                        ->result();
    }

    public function getAdminDepositedCashPoint($cp_id)
    {
        return $this->db->select("*")
                        ->from("cash_points")
                        ->where("cash_points_id", $cp_id)
                        ->get()
                        ->row();
    }

    public function saveAdminCashPoints($data)
    {

        $i_data['cp_description']           = $data['txt_cash_point_desc'];
        $i_data['cp_user_id']               = (int) $data['txt_user'];
        $i_data['cp_status']                = 5;
        $i_data['used_earned_points']       = (float )$data['txt_cash_point'];

        $insertId = (int) $data["id"];


        $this->db->trans_start();

        $user_data = $this->get_user(["user_id" => $i_data['cp_user_id']]);

        if ($insertId  > 0) {
            $cash_point_data = $this->getAdminDepositedCashPoint($insertId);
            if ($cash_point_data) {
                $this->db->where("cash_points_id", $insertId)
                        ->update('cash_points', $i_data);

                if ($cash_point_data->cp_user_id == $i_data['cp_user_id']) {
                    $this->db->where("user_id", $i_data['cp_user_id'])
                            ->update("user_table", ["user_points" => ($user_data->user_points -  $cash_point_data->used_earned_points)  + $i_data['used_earned_points']]);
                } else {
                    $prev_user_data = $this->get_user(["user_id" => $cash_point_data->cp_user_id]);

                    $this->db->where("user_id", $cash_point_data->cp_user_id)
                        ->update("user_table", ["user_points" => $prev_user_data->user_points - $cash_point_data->used_earned_points ]);

                     $this->db->where("user_id", $i_data['cp_user_id'])
                        ->update("user_table", ["user_points" => $user_data->user_points + $i_data['used_earned_points']]);
                }
            } else {
                return 0;
            }
        } else {
            $i_data['cp_date'] = date("Y-m-d H:i:s");

            $this->db->insert('cash_points', $i_data);
            $insertId = $this->db->insert_id();

            $this->db->where("user_id", $i_data['cp_user_id'])
                     ->update("user_table", ["user_points" => $user_data->user_points + $i_data['used_earned_points']]);
        }

        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }

    public function deleteAdminCashPoint($data)
    {
        $this->db->trans_start();

        $cash_point_data = $this->getAdminDepositedCashPoint($data['id']);

        if ($cash_point_data) {
            $user_data = $this->get_user(["user_id" => $cash_point_data->cp_user_id]);

            $this->db->where("user_id", $i_data['cp_user_id'])
                            ->update("user_table", ["user_points" => ($user_data->user_points -  $cash_point_data->used_earned_points)  ]);


            $this->db->where('cash_points_id', $data['id']);
            $this->db->delete('cash_points');
        }



        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }


    public function getCouponDetails($data)
    {

        $this->db->select('*');
        $this->db->from('coupon p');
        // if ($data['user_id'] > 0) {
        //     $this->db->where('coupon_vender_id', $data['user_id']);
        // }
        $this->db->order_by('coupon_id', 'desc');
        $query = $this->db->get();
        //echo $this->db->last_query();
        return $query->result();
    }

    public function getCoupon($coupon_id)
    {
        return $this->db->select("*")
                        ->from("coupon")
                        ->where("coupon_id", $coupon_id)
                        ->get()
                        ->row();
    }

    public function deleteCoupon($data)
    {
        $this->db->trans_start();

        $this->db->where('coupon_id', $data['id']);
        $this->db->delete('coupon');

        $this->db->where('coupon_category_coupon_id', $data['id']);
        $this->db->delete('coupon_category');

        $this->db->where('coupon_products_coupon_id', $data['id']);
        $this->db->delete('coupon_products');

        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }
    public function getOrderListDetails( $datatable,$user_id,$filter )
    {


         return $datatable->query("select distinct pod.product_order_id as id,pod.order_no as order_no,pod.transaction_id_no as bill_no,pod.store_id,pod.vat_perc as  vat_price,pod.sub_total as sale_amount,pod.order_placed_date as date,pod.delivery_status as status,poh.khiat_commission as khiat_commission,poh.vendor_commission as vendor_commission from product_order_details  pod join product_order_history  poh on pod.order_block_id = poh.order_block_id   where 1=1  {$filter} and  pod.user_id=$user_id");


    }

    public function getOrderListDetails1( $datatable,$user_id,$filter )
    {


         return $datatable->query("select distinct pod.product_order_id as id,pod.order_no as order_no,pod.transaction_id_no as bill_no,pod.store_id,pod.vat_perc as  vat_price,pod.sub_total as sale_amount,pod.order_placed_date as date,pod.delivery_status as status,(select sum(product_order_history.khiat_commission) from product_order_history where pod.order_block_id=product_order_history.order_block_id) as khiat_commission,(select sum(product_order_history.vendor_commission) from product_order_history where pod.order_block_id=product_order_history.order_block_id) as vendor_commission from product_order_details  pod    where 1=1  {$filter} and  pod.user_id=$user_id");


    }
    public function get_customer_list($datatable, $filter = "")
    {
        return $datatable->query("select user_id::text as id,
                                user_first_name || ' ' || user_last_name as name,
                                user_email_id as email,
                                dial_code,
                                phone_number,
                                user_created_date::text as created_date,
                                user_status::text	as status,
                                user_type::text	as type
                            from user_table where 1=1 {$filter}");
    }

    public function get_privacy_meta_data() {
        return $this->db->select("meta_title, meta_keyword,	meta_description")
                        ->from("privacy_policy")
                        ->get()
                        ->row();

    }
    function update_privacy_policy_meta_data($data)
    {
        $this->db->update("privacy_policy", $data);

        return $this->db->affected_rows();
    }
    public function getUsersList($conditions)
    {
        $query = $this->db->order_by('user_first_name', 'asc')->get_where('user_table', $conditions);
        return $query->result();
    }
    function getMetaData()
    {
        $this->db->select('meta_tags_id,meta_title,meta_keyword,meta_description');
        $this->db->from('meta_tags');
        $query = $this->db->get();
        return $query->result();
    }
    function getMetaDataById( $id)
    {
        $query = $this->db->get_where('meta_tags', array('meta_tags_id'=>$id));
        return $query->row();
    }
    function saveMetaData($inputArray, $key, $tableName)
    {
        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $this->db->trans_start();
        if (isset($inputArray[$key]) && $inputArray[$key]>0) {

            $this->db->where($key, $inputArray[$key]);
            $this->db->update($tableName, $inputArray);
            $entityId =  $inputArray[$key];

            $action   = 2;
        } else {
            $this->db->select('max('.$key.') as maxid');
            $this->db->from(''.$tableName.' c');
            $query = $this->db->get();

            $res  =  $query->row();
            $maxId              =   ($res->maxid>0?$res->maxid+1:1);
            $inputArray[$key]     =   $maxId  ;
            $this->db->insert($tableName, $inputArray);
            $entityId =  $maxId;
            $action   = 1;
        }

        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }

    public function get_faq_meta_data() {
        return $this->db->select("meta_title, meta_keyword,	meta_description")
                        ->from("faq")
                        ->get()
                        ->row();
    }
    function update_faq_meta_data($data)
    {
        $this->db->update("faq", $data);
        return $this->db->affected_rows();
    }

    public function getCategoryByUID( $uid, $condition )
    {
        if (! empty($condition) ) {
            $this->db->where($condition);
        }
        return $this->db->get_where('category', ['category_uid' => $uid])
                        ->row();
    }

    /*
    | -------------------------------------------------------------------------
    | Category Attributes
    | -------------------------------------------------------------------------
    */
    public function getCategoryAttributeTypes()
    {
        return $this->db->order_by(array('cat_attribute_type_name', 'ASC'))
                        ->get('category_attribute_type')
                        ->result();
    }

    public function getCategoryAttributeTypeById($id)
    {
        return $this->db->get_where('category_attribute_type', array('cat_attribute_type_id' => $id))
                        ->row();
    }

    private function _getCategoryAttributes($condition=array())
    {
        $lang = $this->session->userdata('language') ?? 1;
        $condition['cat.category_language_code'] = $lang;
        $query = $this->db->select('c_attr.*, cat.category_name, c_attr_type.cat_attribute_type_name,c_attr_type.cat_attribute_type_uid')
                          ->from('category_attribute c_attr')
                          ->join('category cat', 'cat.category_id = c_attr.category_id', 'left')
                          ->join('category_attribute_type c_attr_type', 'c_attr_type.cat_attribute_type_id = c_attr.cat_attribute_type', 'left')
                          ->where($condition)
                          ->order_by('c_attr.cat_attribute_sort_order ASC, c_attr.cat_attribute_id ASC')
                          ->get();
        return $query;
    }

    public function getCategoryAttributes($condition=array())
    {
        return $this->_getCategoryAttributes($condition)->result();
    }

    public function getCategoryAttributeById($id)
    {
        return $this->_getCategoryAttributes(array('c_attr.cat_attribute_id' => $id))->row();
    }

    public function saveCategoryAttribute($data)
    {
        $this->db->trans_start();

        if ($data['cat_attribute_id'] > 0) {
            $this->db->where('cat_attribute_id', $data['cat_attribute_id']);
            $this->db->update('category_attribute', $data);
            $entityId = $data['cat_attribute_id'];
            $action = 2;

            $cat_attribute_type_id = $data['cat_attribute_type']??NULL;
            /**
             * If there is a change in attribute_type,
             * then enable/disable corresponding attribute values (if any)
             */
            if ( $cat_attribute_type_id ) {
                $attribute_type_rec = $this->getCategoryAttributeTypeById($cat_attribute_type_id);
                if (! $attribute_type_rec ) {
                    $this->db->trans_rollback();
                    return 0;
                }

                // Disable attribute values of old type
                $this->db->update('category_attribute_values',
                    array(
                        'cat_attribute_val_status' => 0,
                    ),
                    array(
                        'cat_attribute_id' => $entityId,
                        'cat_attribute_val_type_id !=' => $cat_attribute_type_id
                    )
                );
                // Enable attribute values of new type
                $this->db->update('category_attribute_values',
                    array(
                        'cat_attribute_val_status' => 1,
                    ),
                    array(
                        'cat_attribute_id' => $entityId,
                        'cat_attribute_val_type_id' => $cat_attribute_type_id
                    )
                );
                if ($attribute_type_rec->cat_attribute_type_uid == 'bool') {
                    $count_where = array(
                        'cat_attribute_id' => $entityId,
                        'cat_attribute_val_status' => 1,
                        'cat_attribute_val_type_id' => $cat_attribute_type_id
                    );
                    $bool_attrs_count = $this->db->where($count_where)
                                                 ->from('category_attribute_values')
                                                 ->count_all_results();
                    if (! ($bool_attrs_count > 0) ) {
                        $this->_addBooleanAttributeValues($entityId, $attribute_type_rec->cat_attribute_type_id);
                    }
                }
            }
        } else {
            if (empty($data)) {
                $this->db->trans_rollback();
                return 0;
            }
            $cat_attribute_type_id = $data['cat_attribute_type']??NULL;
            if (! $cat_attribute_type_id ) {
                $this->db->trans_rollback();
                return 0;
            }
            $attribute_type_rec = $this->getCategoryAttributeTypeById($cat_attribute_type_id);
            if (! $attribute_type_rec ) {
                $this->db->trans_rollback();
                return 0;
            }
            $this->db->insert('category_attribute', $data);
            $insertId = $this->db->insert_id();
            $entityId = $insertId;
            $action = 1;

            // If attribute type is Bool, then create attribute values automatically
            if ($attribute_type_rec->cat_attribute_type_uid == 'bool') {
               $this->_addBooleanAttributeValues($entityId, $attribute_type_rec->cat_attribute_type_id);
            }
        }

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial
        $auditArray = array();
        $auditArray['admin_id'] = $this->session->userdata('admin_id');
        $auditArray['module_id'] = 26;
        $auditArray['entity_id'] = $entityId;
        $auditArray['action_id'] = $action;
        $auditArray['audit_time'] = gmdate("Y-m-d H:i:s");
        $auditArray['audit_note'] = "category attribute creation/updation from admin module";
        $auditArray['menu_id'] = 5;
        $this->db->insert('admin_audit_trial', $auditArray);

        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }

    private function _addBooleanAttributeValues($cat_attribute_id, $cat_attribute_val_type_id)
    {
        $bool_attribute_vals = array(
            array(
                'cat_attribute_id' => $cat_attribute_id,
                'cat_attribute_val_value' => 1,
                'cat_attribute_val_value_arabic' => 1,
                'cat_attribute_val_label' => 'Yes',
                'cat_attribute_val_label_arabic' => 'نعم فعلا',
                'cat_attribute_val_type_id' => $cat_attribute_val_type_id,
                'cat_attribute_val_sort_order' => 1,
            ),
            array(
                'cat_attribute_id' => $cat_attribute_id,
                'cat_attribute_val_value' => 0,
                'cat_attribute_val_value_arabic' => 0,
                'cat_attribute_val_label' => 'No',
                'cat_attribute_val_label_arabic' => 'لا',
                'cat_attribute_val_type_id' => $cat_attribute_val_type_id,
                'cat_attribute_val_sort_order' => 0,
            )
        );
        $this->db->insert_batch('category_attribute_values', $bool_attribute_vals);
    }

    public function sortCategoryAttribute($id, $sort_order=1)
    {
        $this->db->update('category_attribute', array('cat_attribute_sort_order' => $sort_order), array('cat_attribute_id' => $id));
        return ($this->db->affected_rows() > 0);
    }

    public function deleteCategoryAttribute($id)
    {
        $count = $this->db->get_where('product_order_user_attribute', ['attribute_id' => $id])->num_rows();
        if ( $count > 0 ) {
            return 3;
        }

        $this->db->trans_start();

        $this->db->where('cat_attribute_id', $id);
        $this->db->delete('category_attribute');

        $this->db->where('cat_attribute_id', $id);
        $this->db->delete('category_attribute_values');

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        $auditArray = array();
        $auditArray['admin_id'] = $this->session->userdata('admin_id');
        $auditArray['module_id'] = 26;
        $auditArray['entity_id'] = $id;
        $auditArray['action_id'] = 3;
        $auditArray['audit_time'] = gmdate("Y-m-d H:i:s");
        $auditArray['audit_note'] = "category attribute delete from admin module";
        $auditArray['menu_id'] = 5;
        $this->db->insert('admin_audit_trial', $auditArray);

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }

    public function getCategoryAttributeVals($condition=array(), $active_only=FALSE)
    {
        if ($active_only) {
            $condition['cat_attribute_val_status'] = 1;
        }
        $query = $this->db->order_by('cat_attribute_val_sort_order ASC, cat_attribute_val_id ASC')
                          ->get_where('category_attribute_values', $condition);
        return $query->result();
    }

    public function saveCategoryAttributeValue($data)
    {
        $this->db->trans_start();

        $cat_attribute_val_id = $data['cat_attribute_val_id']??NULL;
        if ($cat_attribute_val_id && $cat_attribute_val_id > 0) {
            $cat_attribute_val_type_id = $data['cat_attribute_val_type_id']??NULL;
            if ($cat_attribute_val_type_id) {
                $attribute_type_rec = $this->getCategoryAttributeTypeById($cat_attribute_val_type_id);
                if (! $attribute_type_rec) {
                    $this->db->trans_rollback();
                    return 0;
                }
            }
            $this->db->where('cat_attribute_val_id', $cat_attribute_val_id);
            $this->db->update('category_attribute_values', $data);
            $entityId = $cat_attribute_val_id;
            $action = 2;
        } else {
            if (empty($data)) {
                $this->db->trans_rollback();
                return 0;
            }
            // cat_attribute_id is required
            $cat_attribute_id = $data['cat_attribute_id']??NULL;
            if ( $cat_attribute_id ) {
                $cat_attribute_id = $this->getCategoryAttributeById($cat_attribute_id);
            }
            if (! $cat_attribute_id ) {
                $this->db->trans_rollback();
                return 0;
            }
            $data['cat_attribute_val_type_id'] = $cat_attribute_id->cat_attribute_type;
            $this->db->insert('category_attribute_values', $data);
            $insertId = $this->db->insert_id();
            $entityId = $insertId;
            $action = 1;
        }

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial
        $auditArray = array();
        $auditArray['admin_id'] = $this->session->userdata('admin_id');
        $auditArray['module_id'] = 26;
        $auditArray['entity_id'] = $entityId;
        $auditArray['action_id'] = $action;
        $auditArray['audit_time'] = gmdate("Y-m-d H:i:s");
        $auditArray['audit_note'] = "category attribute value creation/updation from admin module";
        $auditArray['menu_id'] = 5;
        $this->db->insert('admin_audit_trial', $auditArray);

        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }

    public function sortCategoryAttributeValue($id, $sort_order=1)
    {
        $this->db->update('category_attribute_values', array('cat_attribute_val_sort_order' => $sort_order), array('cat_attribute_val_id' => $id));
        return ($this->db->affected_rows() > 0);
    }

    public function deleteCategoryAttributeValue($id)
    {
        $count = $this->db->get_where('product_order_user_attribute', ['attribute_value_id' => $id])->num_rows();
        if ( $count > 0 ) {
            return 3;
        }

        $this->db->trans_start();

        $this->db->where('cat_attribute_val_id', $id);
        $this->db->delete('category_attribute_values');

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        $auditArray = array();
        $auditArray['admin_id'] = $this->session->userdata('admin_id');
        $auditArray['module_id'] = 26;
        $auditArray['entity_id'] = $id;
        $auditArray['action_id'] = 3;
        $auditArray['audit_time'] = gmdate("Y-m-d H:i:s");
        $auditArray['audit_note'] = "category attribute value delete from admin module";
        $auditArray['menu_id'] = 5;
        $this->db->insert('admin_audit_trial', $auditArray);

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }

    /*
    | -------------------------------------------------------------------------
    | Category Measurement Points
    | -------------------------------------------------------------------------
    */
    private function _getMeasurementPoints($condition)
    {
        $lang = $this->session->userdata('language') ?? 1;
        $condition['cat.category_language_code'] = $lang;

        return $this->db->select('msr_point.*, cat.category_name')
                        ->from('measurement_point msr_point')
                        ->join('category cat', 'cat.category_id = msr_point.category_id', 'left')
                        ->where($condition)
                        ->get();
    }

    public function getMeasurementPoints($condition)
    {
        return $this->_getMeasurementPoints($condition)->result();
    }

    public function getMeasurementPointById($id)
    {
        return $this->_getMeasurementPoints(array( 'point_id' => $id ))->row();
    }

    public function saveMeasurementPoints( array $data = array() )
    {
        $this->db->trans_start();

        if ($data['point_id'] > 0) {
            $this->db->where('point_id', $data['point_id']);
            $this->db->update('measurement_point', $data);
            $entityId = $data['point_id'];
            $action = 2;
        } else {
            if (empty($data)) {
                $this->db->trans_rollback();
                return 0;
            }
            $category_id = $data['category_id']??NULL;
            if (! $category_id ) {
                $this->db->trans_rollback();
                return 0;
            }
            $category_rec = $this->getCategoriesCondition( array('category_id' => $category_id ) );
            if (! $category_rec ) {
                $this->db->trans_rollback();
                return 0;
            }
            $this->db->insert('measurement_point', $data);
            $insertId = $this->db->insert_id();
            $entityId = $insertId;
            $action = 1;
        }

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial
        $auditArray = array();
        $auditArray['admin_id'] = $this->session->userdata('admin_id');
        $auditArray['module_id'] = 28;
        $auditArray['entity_id'] = $entityId;
        $auditArray['action_id'] = $action;
        $auditArray['audit_time'] = gmdate("Y-m-d H:i:s");
        $auditArray['audit_note'] = "category measurement point creation/updation from admin module";
        $auditArray['menu_id'] = 5;
        $this->db->insert('admin_audit_trial', $auditArray);

        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }

    public function deleteCategoryMeasurementPoint($id)
    {
        $count = $this->db->get_where('user_measurement_value', ['measurement_point_id' => $id])->num_rows();
        if ( $count > 0 ) {
            return 3;
        }

        $this->db->trans_start();

        $this->db->where('point_id', $id);
        $this->db->delete('measurement_point');

        $this->db->where('measurement_point_id', $id);
        $this->db->delete('measurement_point_values');

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        $auditArray = array();
        $auditArray['admin_id'] = $this->session->userdata('admin_id');
        $auditArray['module_id'] = 28;
        $auditArray['entity_id'] = $id;
        $auditArray['action_id'] = 3;
        $auditArray['audit_time'] = gmdate("Y-m-d H:i:s");
        $auditArray['audit_note'] = "category measurement point delete from admin module";
        $auditArray['menu_id'] = 5;
        $this->db->insert('admin_audit_trial', $auditArray);

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }

    public function getMeasurementVals($condition)
    {
        return $this->db->order_by('point_val_value asc')
                        ->get_where('measurement_point_values', $condition)
                        ->result();
    }

    public function saveMeasurementValue( array $data = array() )
    {
        $this->db->trans_start();

        if ($data['point_val_id'] > 0) {
            $this->db->where('point_val_id', $data['point_val_id']);
            $this->db->update('measurement_point_values', $data);
            $entityId = $data['point_val_id'];
            $action = 2;
        } else {
            if (empty($data)) {
                $this->db->trans_rollback();
                return 0;
            }
            $this->db->insert('measurement_point_values', $data);
            $insertId = $this->db->insert_id();
            $entityId = $insertId;
            $action = 1;
        }

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial
        $auditArray = array();
        $auditArray['admin_id'] = $this->session->userdata('admin_id');
        $auditArray['module_id'] = 29;
        $auditArray['entity_id'] = $entityId;
        $auditArray['action_id'] = $action;
        $auditArray['audit_time'] = gmdate("Y-m-d H:i:s");
        $auditArray['audit_note'] = "category measurement point value creation/updation from admin module";
        $auditArray['menu_id'] = 5;
        $this->db->insert('admin_audit_trial', $auditArray);

        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }

    public function deleteCategoryMeasurementValue($id)
    {
        $this->db->trans_start();

        $this->db->where('point_val_id', $id);
        $this->db->delete('measurement_point_values');

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        $auditArray = array();
        $auditArray['admin_id'] = $this->session->userdata('admin_id');
        $auditArray['module_id'] = 29;
        $auditArray['entity_id'] = $id;
        $auditArray['action_id'] = 3;
        $auditArray['audit_time'] = gmdate("Y-m-d H:i:s");
        $auditArray['audit_note'] = "category measurement point value delete from admin module";
        $auditArray['menu_id'] = 5;
        $this->db->insert('admin_audit_trial', $auditArray);

        //admin audit trial //admin audit trial//admin audit trial//admin audit trial

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }

    /**
     * Vehicle Types
     */
    public function getVehicleTypeCondition( array $condition = array() )
    {
        return $this->db->get_where('vehicle_type', $condition)
                        ->result();
    }

    public function getAttributeCategoryMap( $category_id )
    {
        return $this->db->get_where('attribute_category_map', ['category_id' => $category_id])
                        ->result_array();
    }

    public function getDriverEarnings( $user_id, $order_id=NULL, $seller_user_id=NULL, $condition=[] )
    {
        if ( $order_id ) {
            $this->db->where('de.order_id', $order_id);
        }
        if ( $seller_user_id ) {
            $this->db->where('de.order_seller_id', $seller_user_id);
        }

        $start_date = $condition['start_date'] ?? '';
        if (! empty($start_date) ) {
            $gm_start_date = get_date_in_timezone('Etc/GMT', "{$start_date} 00:00:00", 'Y-m-d H:i:s', 'Asia/Dubai');
            $this->db->where('(de.created_date)::DATE >=', $gm_start_date);
        }

        $end_date = $condition['end_date'] ?? '';
        if (! empty($end_date) ) {
            $gm_end_date = get_date_in_timezone('Etc/GMT', "{$end_date} 23:59:59", 'Y-m-d H:i:s', 'Asia/Dubai');
            $this->db->where('(de.created_date)::DATE <=', $gm_end_date);
        }

        return $this->db->select('de.*, pod.order_no, pod.product_order_id, seller.store_name, SUM(poh.product_total) AS total_sale, COALESCE(pod_issue.issue_count, 0) AS issue_count')
                        ->from('driver_earning de')
                        ->join('product_order_details pod', 'de.order_id = pod.order_block_id', 'left')
                        ->join('product product', 'de.order_seller_id = product.product_vender_id', 'left')
                        ->join('product_order_history poh', 'product.product_id = poh.product_id AND de.order_id = poh.order_block_id', 'left')
                        ->join('seller_details seller', 'de.order_seller_id = seller.user_id', 'left')
                        ->join('(SELECT order_block_id, COUNT(order_issue_id) AS issue_count FROM product_order_report_issue GROUP BY order_block_id) pod_issue', 'pod.order_block_id = pod_issue.order_block_id', 'left')
                        ->where('de.user_id', $user_id)
                        ->group_by(['de.earning_id', 'pod.order_no', 'pod.product_order_id', 'seller.store_name', 'pod_issue.issue_count'])
                        ->order_by('de.earning_id desc')
                        ->get()->result();
    }

    public function payDriverEarning( $earning_id )
    {
        if ( $earning_id > 0 ) {
            $this->db->where('earning_id', $earning_id);
            $this->db->update('driver_earning', ['is_paid' => 1, 'paid_date' => gmdate("Y-m-d H:i:s")]);
            return $this->db->affected_rows() > 0 ? 1 : 0;
        }
        return 0;
    }

    public function getOrderIssuesReported( $order_id, $condition=[] )
    {
        if (! empty($condition) ) {
            $this->db->where($condition);
        }
        $this->db->select('pod_issue.*, pod.order_no, pod.order_placed_date');
        $this->db->from('product_order_report_issue pod_issue');
        $this->db->join('product_order_details pod', 'pod_issue.order_block_id = pod.order_block_id');
        $this->db->where('pod_issue.order_block_id', $order_id);
        $this->db->order_by('pod_issue.order_issue_id asc');
        return $this->db->get()->result();
    }
    public function getReviews( $product_id )
    {
        return $this->db->select('ur.*, u.user_first_name,u.user_last_name,p.product_name')
                        ->from('user_ratings ur')
                        ->join('user_table u', 'ur.user_id = u.user_id', 'left')
                        ->join('product p', 'p.product_id = ur.product_id', 'left')
                        ->where('ur.product_id', $product_id)
                        ->order_by('ur.id desc')
                        ->get()->result();
    }
    public function getVendorReviews( $seller_id )
    {
         return $this->db->select('ur.*, u.user_first_name,u.user_last_name')
                       ->from('user_rating_for_seller ur')
                        ->join('user_table u', 'ur.user_id = u.user_id', 'left')
                        ->where('ur.seller_id', $seller_id)
                        ->order_by('ur.id desc')
                        ->get()->result();
    }
    public function getProdcutInfo( $product_id )
    {
        return $this->db->get_where('product', ['product_id' => $product_id])->row();
    }
    public function getVendorInfo( $user_id )
    {
        return $this->db->get_where('seller_details', ['user_id' => $user_id])->row();
    }
    public function getDriverInfo( $user_id )
    {
        return $this->db->get_where('driver_details', ['user_id' => $user_id])->row();
    }
    public function getCustomerDetails( $user_id )
    {
        return $this->db->get_where('user_table', ['user_id' => $user_id])->row();
    }
    // public function getVendorReviews( $type )
    // {
    //     return $this->db->get_where('user_rating_for_seller', ['seller_id' => $type])->result();
    // }
    function checkOrderExists($cat_id)
    {
        $this->db->select('c_a.*');
        $this->db->from('product p');
        $this->db->join('product_order_history p_o', 'p.product_id =p_o.product_id');
        $this->db->join('product_category p_c', 'p_c.product_id =p.product_id');
        $this->db->join('category_attribute c_a', 'p_c.category_id =c_a.category_id','left');
        $this->db->where('p_c.category_id', $cat_id);

         $query = $this->db->get();

         return  $query->result();
         //  echo $this->db->last_query();
    }
    public function getKandoraDetails( $product_id )
    {
        return $this->db->distinct()
                        ->select('*')
                        ->from('product_category  pc')
                        ->join('category  c', 'pc.category_id = c.category_id','right')
                        ->join('category_attribute  ca', 'ca.category_id = pc.category_id','left')
                        ->where('pc.product_id', $product_id)
                        ->get()
                        ->result();
    }

    public function get_product_attribute_details($product_id,$block_id){

    $this->db->select("av.attribute_values_id,av.attribute_values as attribute_value_selected,at.attribute_name as attribute_name_selected");
    $this->db->from("product_order_history ph");
   // $this->db->join("product_order_history ph","po.order_block_id = ph.order_block_id");
    $this->db->join("product_variations pv","ph.product_attribute_id = pv.product_attribute_id");
    $this->db->join("attribute_values av","pv.attribute_values_id = av.attribute_values_id");
    $this->db->join("attribute at","av.attribute_id = at.attribute_id");
    $this->db->where("ph.product_id",$product_id);
    $this->db->where("ph.order_block_id",$block_id);
    $this->db->group_by("av.attribute_values_id,av.attribute_values,at.attribute_name");

    return $this->db->get()->result();

    }

    public function getProductAttributesByHistoryId($history_id)
    {
        $this->db->select("av.attribute_values_id,av.attribute_values as attribute_value_selected,at.attribute_name as attribute_name_selected");
        $this->db->from("product_order_history ph");
        $this->db->join("product_variations pv","ph.product_attribute_id = pv.product_attribute_id");
        $this->db->join("attribute_values av","pv.attribute_values_id = av.attribute_values_id");
        $this->db->join("attribute at","av.attribute_id = at.attribute_id");
        $this->db->where("ph.history_id",$history_id);
        $this->db->group_by("av.attribute_values_id,av.attribute_values,at.attribute_name");

        return $this->db->get()->result();
    }

    public function getKandoraDetails_by_product_id($product_id,$block_id){

    $this->db->select("pout.attribute_value,ca.cat_attribute_name,cav.cat_attribute_val_image as image");
    $this->db->from("product_order_history ph");
    //$this->db->join("product_order_history ph","po.order_block_id = ph.order_block_id");
    $this->db->join("product_order_user_attribute pout","ph.history_id = pout.history_id");
    $this->db->join("category_attribute ca","ca.cat_attribute_id = pout.attribute_id");
    $this->db->join("category_attribute_values cav","pout.attribute_value_id = cav.cat_attribute_val_id","left");
    $this->db->where("ph.product_id",$product_id);
    $this->db->where("ph.order_block_id",$block_id);

    return $this->db->get()->result();

    }

    public function getKandoraDetailsByHistoryId($history_id)
    {
        $this->db->select("pout.attribute_value,ca.cat_attribute_name,cav.cat_attribute_val_image as image");
        $this->db->from("product_order_history ph");
        //$this->db->join("product_order_history ph","po.order_block_id = ph.order_block_id");
        $this->db->join("product_order_user_attribute pout","ph.history_id = pout.history_id");
        $this->db->join("category_attribute ca","ca.cat_attribute_id = pout.attribute_id");
        $this->db->join("category_attribute_values cav","pout.attribute_value_id = cav.cat_attribute_val_id","left");
        $this->db->where("ph.history_id",$history_id);

        return $this->db->get()->result();
    }



    public function get_type_measurement($product_id,$block_id){//echo $product_id;exit;

    $this->db->select("ph.order_block_id,mp.point_name,umv.measurement_value");
    $this->db->from("product_order_history ph");
    //$this->db->join("product_order_history ph","po.order_block_id = ph.order_block_id");
    $this->db->join("user_measurement_point ump","ph.measurement_id = ump.user_measurement_id");
    $this->db->join("user_measurement_value umv","ump.user_measurement_id = umv.user_measurement_id");
    $this->db->join("measurement_point mp","umv.measurement_point_id = mp.point_id");
    $this->db->where("ph.product_id",$product_id);
    $this->db->where("ph.order_block_id",$block_id);

    return $this->db->get()->result();

    }

    public function getTypeMeasurementByHistoryId($history_id)
    {
        $this->db->select("ph.order_block_id,mp.point_name,umv.measurement_value");
        $this->db->from("product_order_history ph");
        $this->db->join("user_measurement_point ump","ph.measurement_id = ump.user_measurement_id");
        $this->db->join("user_measurement_value umv","ump.user_measurement_id = umv.user_measurement_id");
        $this->db->join("measurement_point mp","umv.measurement_point_id = mp.point_id");
        $this->db->where("ph.history_id", $history_id);

        return $this->db->get()->result();
    }

    public function get_measurement_points( $user_id, string $lang_code="1", array $condition=[] )
    {
        if (! empty($condition) ) {
            $this->db->where($condition);
        }
        return $this->db->select('ump.user_measurement_id AS measurement_id, ump.title, ump.category_id,ump.created_on, cat.category_name')
                        ->from('user_measurement_point ump')
                        ->join('category cat', 'ump.category_id = cat.category_id', 'left')
                        ->where('ump.user_id', $user_id)
                        ->where('ump.is_deleted', 0)
                        ->where('cat.category_language_code', $lang_code)
                        ->order_by('cat.category_name ASC, ump.user_measurement_id DESC')
                        ->get()->result();
    }

    public function get_measurement_point_detail( $user_id, $measurement_id, string $lang_code="1" )
    {
        $this->db->select('ump.user_measurement_id AS measurement_id, ump.title,ump.comments, ump.category_id, cat.category_name, cat.category_uid, mp.point_id, mp.point_uid');
        if ( $lang_code == "2" ) {
            $this->db->select('mp.point_name_arabic AS point_name');
        } else {
            $this->db->select('mp.point_name');
        }
        $this->db->select('point_is_required AS is_required, umv.measurement_value AS value');
        $data = $this->db->from('user_measurement_point ump')
                        ->join('category cat', 'ump.category_id = cat.category_id', 'left')
                        ->join('measurement_point mp', 'cat.category_id = mp.category_id', 'left')
                        ->join('(SELECT * FROM user_measurement_value WHERE user_measurement_id = '. $this->db->escape($measurement_id) .') umv', 'mp.point_id = umv.measurement_point_id', 'left')
                        ->where('ump.user_id', $user_id)
                        ->where('ump.is_deleted', 0)
                        ->where('ump.user_measurement_id', $measurement_id)
                        ->where('mp.point_status', 1)
                        ->where('cat.category_language_code', $lang_code)
                        ->order_by('cat.category_name ASC, ump.user_measurement_id DESC')
                        ->get()->result();

        $result = [];
        foreach ($data as $row) {
            $row->values = [];
            $result[$row->point_id] = $row;
        }

        if (! empty($result) ) {
            $point_ids = array_column($result, 'point_id');
            $point_ids = array_filter(array_unique($point_ids));
            $point_values = $this->db->select('measurement_point_id AS point_id, point_val_id, point_val_value')
                                     ->from('measurement_point_values')
                                     ->where_in('measurement_point_id', $point_ids)
                                     ->where('point_val_status', 1)
                                     ->get()->result();

            foreach ($point_values as $p_val) {
                if ( array_key_exists($p_val->point_id, $result) !== FALSE ) {
                    $result[$p_val->point_id]->values[] = [
                        'id' => $p_val->point_val_id,
                        'value' => $p_val->point_val_value,
                    ];
                }
            }
        }

        return $result;
    }
    public function getCustomerOrder( $customer_id, $order_id, $lang_code="1" )
    {
        $this->db->select("pod.order_no, pod.order_block_id AS order_id, pod.order_placed_date, pod.delivery_status AS order_status, user.user_id AS customer_id, user.user_first_name AS customer_first_name, user.user_last_name AS customer_last_name, pod.shipping_address_id, user_shipping.first_name::TEXT || ' ' || user_shipping.last_name::TEXT AS shipping_user, user_shipping.user_shiping_details_loc AS shipping_location, user_shipping.user_shiping_details_latitude AS shipping_latitude, user_shipping.user_shiping_details_longitude AS shipping_longitude, user_shipping.user_shiping_details_dial_code::TEXT || '-' || user_shipping.user_shiping_details_phone::TEXT AS shipping_phone, pod.sub_total_uc AS sub_total, pod.vat_price AS tax, pod.vat_perc AS tax_percentage, pod.shipping_charge_uc AS shipping_charge, pod.measurement_charge_uc AS measurement_charge, COUNT(product.product_id) AS total_products, COUNT(poh.history_id) AS total_quantity, pod.total_price_uc AS grand_total");

        $this->db->from('product_order_history poh');
        $this->db->join('product_order_details pod', 'poh.order_block_id = pod.order_block_id', 'left');
        $this->db->join('user_table user', 'pod.user_id = user.user_id', 'left');
        $this->db->join('user_shiping_details user_shipping', 'pod.shipping_address_id = user_shipping.user_shiping_details_id', 'left');
        $this->db->join('product product', 'poh.product_id = product.product_id', 'left');
        $this->db->join('seller_details seller', 'product.product_vender_id = seller.user_id', 'left');
        $this->db->where('pod.order_block_id', $order_id);
        $this->db->where('user.user_id', $customer_id);

        $this->db->group_by(['pod.order_no', 'pod.order_block_id', 'poh.order_block_id', 'pod.order_placed_date', 'pod.delivery_status', 'pod.vat_price', 'pod.sub_total_uc', 'pod.vat_perc', 'pod.shipping_charge_uc', 'pod.measurement_charge_uc', 'pod.total_price_uc', 'user.user_id', 'user.user_first_name', 'user.user_last_name', 'pod.shipping_address_id', 'user_shipping.first_name', 'user_shipping.last_name', 'user_shipping.user_shiping_details_loc', 'user_shipping.user_shiping_details_latitude', 'user_shipping.user_shiping_details_longitude', 'user_shipping.user_shiping_details_dial_code', 'user_shipping.user_shiping_details_phone']);

        $order = $this->db->get()->row();
        if ( $order ) {
            // Fetch products
            $this->db->select('product.product_id, pattr.product_attribute_id AS product_variant_id');
            if ( $lang_code == "2" ) {
                $this->db->select("product.product_name_arabic AS product_name, STRING_AGG((cattr.cat_attribute_name_arabic || ': ' || po_uattr.attribute_value), ', ') AS product_title");
            } else {
                $this->db->select("product.product_name AS product_name, STRING_AGG((cattr.cat_attribute_name || ': ' || po_uattr.attribute_value), ', ') AS product_title");
            }
            $this->db->select("pattr.image, poh.deliver_status AS delivery_status, poh.driver_status, poh.purchase_qty, poh.unit_price_uc AS unit_price, (poh.purchase_qty * poh.unit_price_uc) AS product_total, poh.unit_measurement_charge_uc AS measurement_charge, poh.product_total_uc AS total_amount, product.product_vender_id AS seller_id, seller.seller_details_id store_id");
            if ( $lang_code == "2" ) {
                $this->db->select('seller.store_name_arabic AS store_name');
            } else {
                $this->db->select('seller.store_name');
            }
            $this->db->select('seller.location AS store_location, seller.latitude AS store_latitude, seller.longitude AS store_longitude, seller.mobile_no AS store_phone, seller.delivery_time_min, seller.delivery_time_max');

            $this->db->from('product_order_history poh');
            $this->db->join('product_attribute pattr', 'poh.product_attribute_id = pattr.product_attribute_id', 'left');
            $this->db->join('product product', 'pattr.product_id = product.product_id', 'left');
            $this->db->join('seller_details seller', 'product.product_vender_id = seller.user_id', 'left');
            $this->db->join('product_order_user_attribute po_uattr', 'poh.history_id = po_uattr.history_id', 'left');
            $this->db->join('category_attribute cattr', 'po_uattr.attribute_id = cattr.cat_attribute_id', 'left');
            $this->db->where('poh.deliver_status !=', ORDER_STATUS_CANCEL);
            $this->db->where('poh.order_block_id', $order_id);
            $this->db->order_by('poh.history_id ASC');
            $this->db->group_by(['poh.history_id', 'product.product_id', 'product.product_vender_id', 'seller.seller_details_id', 'seller.location', 'seller.latitude', 'seller.longitude', 'seller.mobile_no', 'seller.delivery_time_min', 'seller.delivery_time_max', 'pattr.product_attribute_id', 'pattr.image', 'poh.deliver_status', 'poh.driver_status', 'poh.purchase_qty', 'poh.unit_price_uc', 'poh.unit_measurement_charge_uc', 'poh.product_total_uc']);
            if ( $lang_code == "2" ) {
                $this->db->group_by(['product.product_name_arabic', 'seller.store_name_arabic']);
            } else {
                $this->db->group_by(['product.product_name', 'seller.store_name']);
            }
            $order->products = $this->db->get()->result();
        }

        return $order;
    }

    function getWork()
    {
        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $language=1;
        $this->db->select('hw.*');
        $this->db->from('how_it_work hw');
        $this->db->order_by('hw.work_id', 'asc');
        $query = $this->db->get();
        return $query->result();
    }

    function getTestimonialList()
    {
        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $this->db->select('*');
        $this->db->from('testimonial c');
        $query = $this->db->get();
        return $query->result();
    }
    function getTestimonialById($testimonial_id)
    {
        $this->db->select('*');
        $this->db->from('testimonial');
        $this->db->where('testimonial_id', $testimonial_id);
        $query = $this->db->get();
        return $query->row();
    }

    function saveTestimonials($inputArray,  $key, $tableName)
    {
            $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
            $this->db->trans_start();
        if (isset($inputArray[$key]) && $inputArray[$key]>0) {
            $this->db->where($key, $inputArray[$key]);

            $this->db->update($tableName, $inputArray);
            $entityId =  $inputArray[$key];
            $action   = 2;
        } else {
            $this->db->select('max('.$key.') as maxid');
            $this->db->from(''.$tableName.' c');
            $query = $this->db->get();
            $res  =  $query->row();
            $maxId              =   ($res->maxid>0?$res->maxid+1:1);
            $inputArray[$key]     =   $maxId  ;
            $this->db->insert($tableName, $inputArray);

            $entityId =  $maxId;
            $action   = 1;
        }


        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }

    function deleteTestimonial($id)
    {

        $this->db->trans_start();
        $this->db-> where('testimonial_id', $id);
        $this->db->delete('testimonial');
        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }

    function getHowItWorkById($work_id)
    {
        $this->db->select('*');
        $this->db->from('how_it_work');
        $this->db->where('work_id', $work_id);
        $query = $this->db->get();
        return $query->row();
    }

    /**
     * Customer Order Details
     */
    public function getCustomerOrderDetail( $product_order_id, $lang_code="1" )
    {
        $this->db->select("pod.order_no, pod.transaction_id_no, pcy.category_id, pod.order_block_id AS order_id, pod.order_placed_date, pod.delivery_status AS order_status, user.user_id AS customer_id, user.user_first_name AS customer_first_name, user.user_last_name AS customer_last_name, user.company_name AS customer_company_name, pod.shipping_address_id, user_shipping.first_name::TEXT || ' ' || user_shipping.last_name::TEXT AS shipping_user, user_shipping.user_shiping_details_loc AS shipping_location, user_shipping.user_shiping_details_latitude AS shipping_latitude, user_shipping.user_shiping_details_longitude AS shipping_longitude, user_shipping.user_shiping_details_dial_code::TEXT || '-' || user_shipping.user_shiping_details_phone::TEXT AS shipping_phone, pod.redeemed_amount, pod.used_cash_points, pod.earned_cash_points, pod.discount_price, pod.sub_total_uc AS sub_total, pod.vat_price AS tax, pod.vat_perc AS tax_percentage, pod.shipping_charge_uc AS shipping_charge, pod.measurement_charge_uc AS measurement_charge, COUNT(product.product_id) AS total_products, COUNT(poh.history_id) AS total_quantity, pod.total_price AS grand_total, pod.actual_amount_paid, STRING_AGG(COALESCE(poh_history.vendor_comment, '') || '=' || COALESCE(poh_history.changed_date::TEXT, ''), '###') AS vendor_comment, STRING_AGG(COALESCE(poh_history.driver_comment, '') || '=' || COALESCE(poh_history.changed_date::TEXT, ''), '###') AS driver_comment");

        $this->db->from('product_order_history poh');
        $this->db->join('product_order_details pod', 'poh.order_block_id = pod.order_block_id', 'left');
        $this->db->join('(SELECT order_status_id, order_block_id, vendor_comment, driver_comment, changed_date FROM product_order_status_history WHERE vendor_comment IS NOT NULL OR driver_comment IS NOT NULL GROUP BY order_status_id, order_block_id, vendor_comment, driver_comment, changed_date ORDER BY order_status_id DESC) poh_history', 'pod.order_block_id = poh_history.order_block_id', 'left');
        $this->db->join('user_table user', 'pod.user_id = user.user_id', 'left');
        $this->db->join('user_shiping_details user_shipping', 'pod.shipping_address_id = user_shipping.user_shiping_details_id', 'left');
        $this->db->join('product product', 'poh.product_id = product.product_id', 'left');
        $this->db->join('product_category pcy', 'product.product_id = pcy.product_id', 'left');
        $this->db->join('seller_details seller', 'product.product_vender_id = seller.user_id', 'left');
        $this->db->where('pod.product_order_id', $product_order_id);

        $this->db->group_by(['pod.order_no', 'pod.transaction_id_no', 'pod.order_block_id', 'poh.order_block_id', 'pod.order_placed_date', 'pod.delivery_status', 'pod.redeemed_amount', 'pod.used_cash_points', 'pod.earned_cash_points', 'pod.discount_price', 'pod.vat_price', 'pod.sub_total_uc', 'pod.vat_perc', 'pod.shipping_charge_uc', 'pod.measurement_charge_uc', 'pod.total_price', 'pod.actual_amount_paid', 'user.user_id', 'user.user_first_name', 'user.user_last_name', 'user.company_name', 'pod.shipping_address_id', 'user_shipping.first_name', 'user_shipping.last_name', 'user_shipping.user_shiping_details_loc', 'user_shipping.user_shiping_details_latitude', 'user_shipping.user_shiping_details_longitude', 'user_shipping.user_shiping_details_dial_code', 'user_shipping.user_shiping_details_phone','pcy.category_id']);

        $order = $this->db->get()->row();
        if ( $order ) {
            $vendor_comment = explode('###', $order->vendor_comment);
            $order->vendor_comment = "";
            $order->vendor_comment_date = "";
            if (! empty($vendor_comment) && $order->order_status == ORDER_STATUS_CANCEL ) {
                $vendor_comment = array_filter($vendor_comment);
                $vendor_comment = array_values($vendor_comment);
                $vendor_comment = $vendor_comment[0] ?? "";
                if (! empty($vendor_comment) ) {
                    $vendor_comment = explode('=', $vendor_comment);
                    $order->vendor_comment = $vendor_comment[0] ?? "";
                    if (! empty($order->vendor_comment) ) {
                        $order->vendor_comment_date = $vendor_comment[1] ?? "";
                    }
                }
            }

            $driver_comment = explode('###', $order->driver_comment);
            $order->driver_comment = "";
            $order->driver_comment_date = "";
            if (! empty($driver_comment) ) {
                $driver_comment = array_filter($driver_comment);
                $driver_comment = array_values($driver_comment);
                $driver_comment = $driver_comment[0] ?? "";
                if (! empty($driver_comment) ) {
                    $driver_comment = explode('=', $driver_comment);
                    $order->driver_comment = $driver_comment[0] ?? "";
                    if (! empty($order->driver_comment) ) {
                        $order->driver_comment_date = $driver_comment[1] ?? "";
                    }
                }
            }

            // Fetch products
            $this->db->select('DISTINCT ON (poh.history_id) poh.history_id, product.product_id, pattr.product_attribute_id AS product_variant_id, poh.history_id');
            
            $this->db->select("pattr.image, poh.deliver_status AS delivery_status, poh.driver_status, poh.purchase_qty, poh.unit_price_uc AS unit_price, (poh.purchase_qty * poh.unit_price_uc) AS product_total, poh.unit_measurement_charge_uc AS measurement_charge, poh.product_total_uc AS total_amount, poh.product_total_tax, poh.vendor_commission, poh.khiat_commission, product.product_vender_id AS seller_id, poh.driver_id, seller.seller_details_id store_id, poh.comment,product.product_name");
            if ( $lang_code == "2" ) {
                $this->db->select('seller.store_name_arabic AS store_name');
            } else {
                $this->db->select('seller.store_name');
            }
            $this->db->select('seller.location AS store_location, seller.latitude AS store_latitude, seller.longitude AS store_longitude, seller.mobile_no AS store_phone, seller.delivery_time_min, seller.delivery_time_max, pod_history.changed_date AS status_changed_date, pod_history.changed_user_type AS status_changed_user_type');

            $this->db->from('product_order_history poh');
            $this->db->join('product_attribute pattr', 'poh.product_attribute_id = pattr.product_attribute_id', 'left');
            $this->db->join('product product', 'pattr.product_id = product.product_id', 'left');
            $this->db->join('seller_details seller', 'product.product_vender_id = seller.user_id', 'left');
            $this->db->join('product_order_user_attribute po_uattr', 'poh.history_id = po_uattr.history_id', 'left');            
            $this->db->join('(SELECT * FROM product_order_status_history WHERE order_block_id = '. $this->db->escape($order->order_id) .' ORDER BY order_status_id DESC) pod_history', 'poh.product_attribute_id = pod_history.product_attribute_id', 'left');
            $this->db->where('poh.order_block_id', $order->order_id);
            $this->db->where('product.product_id !=', NULL);
            $this->db->order_by('poh.history_id ASC');
            $this->db->group_by(['poh.history_id', 'product.product_id', 'product.product_vender_id', 'seller.seller_details_id', 'seller.location', 'seller.latitude', 'seller.longitude', 'seller.mobile_no', 'seller.delivery_time_min', 'seller.delivery_time_max', 'pattr.product_attribute_id', 'pattr.image', 'poh.deliver_status', 'poh.driver_status', 'poh.purchase_qty', 'poh.unit_price_uc', 'poh.unit_measurement_charge_uc', 'poh.product_total_uc', 'poh.product_total_tax', 'poh.driver_id', 'poh.vendor_commission', 'poh.khiat_commission', 'poh.comment', 'pod_history.changed_date', 'pod_history.changed_user_type']);
            if ( $lang_code == "2" ) {
                $this->db->group_by(['product.product_name_arabic', 'seller.store_name_arabic']);
            } else {
                $this->db->group_by(['product.product_name', 'seller.store_name']);
            }
            $products = $this->db->get()->result();

            $product_variant_ids = array_filter(array_column($products, 'product_variant_id'));
            $product_attribute_values = $this->getProductAttributeVals($product_variant_ids);

            foreach ( $products as $i => $product ) {
                $products[$i]->status_changed_date = $product->status_changed_date ?? $order->order_placed_date;
                $products[$i]->status_changed_user_type = $product->status_changed_user_type ?? 'U';

                // Product Attributes
                $products[$i]->product_attributes = [];
                if ( ($product->product_variant_id) > 0 && (array_key_exists($product->product_variant_id, $product_attribute_values) !== FALSE) ) {
                    $t_values = $product_attribute_values[$product->product_variant_id];
                    foreach ( $t_values as $t_val ) {
                        $t_image = $t_val->attribute_value_image ?? "";
                        if (! empty($t_image) ) {
                            $t_image = base_url() . $this->config->item('upload_path') . $this->config->item('product_attribute_value_icon_upload_dir') . $t_image;
                        }
                        $products[$i]->product_attributes[] = [
                            'name' => $t_val->attribute_name,
                            'value' => $t_val->attribute_values,
                            'image' => $t_image,
                            'color' => $t_val->attribute_value_color,
                            'type' => $t_val->attribute_type,
                        ];
                    }
                }
            }

            $order->products = $products;

            ##Fetch services
            $this->db->select("poh.order_block_id,poh.history_id,poh.purchase_qty,poh.unit_price,poh.deliver_status,poh.product_total,poh.coupon_discount,poh.product_sub_price,s.service_name as product_name,s.service_description,s.service_image,seller.*");
            if ( $lang_code == "2" ) {
                $this->db->select("s.service_name_arabic as product_name,s.service_description_arabic as service_description");
            }
            $this->db->from("product_order_history poh");
            $this->db->join("services s","s.service_id=poh.service_id");
            $this->db->join("seller_details seller","s.service_vendor_user_id=seller.user_id");
            $this->db->where('poh.order_block_id', $order->order_id);

            $order->services = $this->db->get()->result();
        }

        return $order;
    }

    public function getProductAttributeVals( array $product_attribute_ids=array() )
    {
        if (! empty($product_attribute_ids) ) {
            $this->db->select(
                'pvar.product_variations_id,
                pvar.product_id,
                pvar.product_attribute_id,
                attr.attribute_id,
                attrv.attribute_values_id,
                attr_type.attribute_type_uid AS attribute_type'
            );

            if ( $this->lang_code == 2 ) {
                $this->db->select('attr.attribute_name_arabic AS attribute_name, attrv.attribute_values_arabic AS attribute_values, attrv.attribute_value_label_arabic AS attribute_value_label');
            } else {
                $this->db->select('attr.attribute_name, attrv.attribute_values, attrv.attribute_value_label');
            }

            $this->db->select('attrv.attribute_value_in, attrv.attribute_value_color, attrv.attribute_value_image');

            $this->db->from('product_variations pvar');
            $this->db->join('attribute attr', 'attribute_id', 'inner');
            $this->db->join('attribute_values attrv', 'attribute_values_id', 'inner');
            $this->db->join('attribute_type attr_type', 'attr.attribute_type = attr_type.attribute_type_id', 'left');
            $this->db->where_in('pvar.product_attribute_id', $product_attribute_ids);

            $this->db->group_by(['pvar.product_attribute_id', 'pvar.product_id', 'pvar.product_variations_id', 'attr.attribute_id', 'attr.attribute_name', 'attrv.attribute_values_id', 'attr_type.attribute_type_uid']);

            $this->db->order_by('attrv.attribute_value_sort_order', 'asc');

            $result = $this->db->get()->result();
            $attribute_values = [];
            foreach ( $result as $row ) {
                $attribute_values[$row->product_attribute_id][] = $row;
            }

            return $attribute_values;
        }
        return [];
    }

    public function getCustomerShippingAddressById($shipping_id, $lang_code="1") {
        return $this->db->select("*, user_shiping_details.user_shiping_details_loc_type AS address_type, user_shiping_details.first_name as s_first_name, user_shiping_details.last_name as s_last_name")
                        ->from("user_shiping_details")
                        ->join("user_table", "user_table.user_id = user_shiping_details.user_shiping_details_user_id", "left")
                        ->join("country", "country.country_id = user_shiping_details.user_shiping_country_id and country_language_code={$lang_code}", "left")
                        ->join("city", "city.city_id = user_shiping_details.user_shiping_details_city and city_language_code={$lang_code}", "left")
                        ->where("user_shiping_details_id", $shipping_id)
                        ->order_by("user_shiping_details_id", "desc")
                        ->get()
                        ->row();
    }

    public function getDeliveryStatusTimeline( $order_block_id, $product_attribute_id )
    {
        $this->db->select('*');
        $this->db->from('product_order_status_history');
        $this->db->where('order_block_id', $order_block_id);
        $this->db->where('product_attribute_id', $product_attribute_id);
        $this->db->order_by('changed_date', 'asc');
        return $this->db->get()->result();
    }

    public function getBankList()
    {
        return $this->db->select('bank_id,bank_name,bank_name_arabic')
                        ->from('bank_master')
                        ->order_by('bank_name', 'asc')
                        ->get()->result();
    }

    public function getBankById( $id )
    {
        return $this->db->select('bank_id,bank_name,bank_name_arabic')
                        ->from('bank_master')
                        ->where('bank_id', $id)
                        ->get()->row();
    }

    public function saveBank( array $data=[] )
    {
        if (! empty($data) ) {
            $id = $data['id'] ?? 0;
            $bank_row = [
                'bank_name' => $data['bank_name'],
                'bank_name_arabic' => $data['bank_name_arabic'] ?? '',
            ];
            if ( $id > 0 ) {
                $this->db->where('bank_id', $id);
                $this->db->update('bank_master', $bank_row);
                return $this->db->affected_rows() > 0;
            } else {
                $this->db->insert('bank_master', $bank_row);
                return $this->db->insert_id() > 0;
            }
        }
        return FALSE;
    }

    public function deleteBank( $id )
    {
        $count = $this->db->get_where('seller_details', ['seller_bank_id' => $id])->num_rows();
        if ( $count == 0 ) {
            $count = $this->db->get_where('driver_details', ['driver_bank_id' => $id])->num_rows();
        }
        if ( $count > 0 ) {
            return 3;
        }

        $this->db->trans_start();

        $this->db->where('bank_id', $id);
        $this->db->delete('bank_master');

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }

    /*
    *Offer banks section
    */
    public function getOfferBankList()
    {
        return $this->db->select('bank_id,bank_name,bank_name_arabic')
                        ->from('offer_bank_master')
                        ->order_by('bank_name', 'asc')
                        ->get()->result();
    }

    public function getOfferBankById( $id )
    {
        return $this->db->select('bank_id,bank_name,bank_name_arabic,bank_image')
                        ->from('offer_bank_master')
                        ->where('bank_id', $id)
                        ->get()->row();
    }

    public function saveOfferBank( array $data=[] )
    {
        if (! empty($data) ) {
            $id = $data['id'] ?? 0;
            $bank_row = [
                'bank_name' => $data['bank_name'],
                'bank_name_arabic' => $data['bank_name_arabic'] ?? '',
            ];
            if($data['bank_image'] != ""){
                $bank_row['bank_image']=$data['bank_image'];
            }
            if ( $id > 0 ) {
                $this->db->where('bank_id', $id);
                $this->db->update('offer_bank_master', $bank_row);
                return $this->db->affected_rows() > 0;
            } else {
                $this->db->insert('offer_bank_master', $bank_row);
                return $this->db->insert_id() > 0;
            }
        }
        return FALSE;
    }

    public function deleteOfferBank( $id )
    {
        $count = $this->db->get_where('bank_offers', ['bank_id' => $id])->num_rows();
        if ( $count > 0 ) {
            return 3;
        }

        $this->db->trans_start();

        $this->db->where('bank_id', $id);
        $this->db->delete('offer_bank_master');

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }

    /*
    * banks Offer  section
    */
    public function getBankOfferList()
    {
        return $this->db->select('*')
                        ->from('offer_bank_master obm')
                        ->join("bank_offers bo","bo.bank_id=obm.bank_id")
                        ->order_by('bank_name', 'asc')
                        ->get()->result();
    }

    public function getBankOfferById( $id )
    {
        return $this->db->select('*')
                        ->from('bank_offers')
                        ->where('offer_id', $id)
                        ->get()->row();
    }

    public function saveBankOffer( array $data=[] )
    {
        if (! empty($data) ) {
            $id = $data['id'] ?? 0;
            $bank_row = [
                'bank_id' => $data['bank_name'],
                'offer_title' => $data['offer_title'] ?? '',
                'offer_description' => $data['offer_description'] ?? '',
            ];
            if($data['offer_image'] != ""){
                $bank_row['offer_image']=$data['offer_image'];
            }
            if ( $id > 0 ) {
                $this->db->where('offer_id', $id);
                $this->db->update('bank_offers', $bank_row);
                return $this->db->affected_rows() > 0;
            } else {
                $this->db->insert('bank_offers', $bank_row);
                return $this->db->insert_id() > 0;
            }
        }
        return FALSE;
    }

    public function deleteBankOffer( $id )
    {
        $count = $this->db->get_where('bank_offers', ['offer_id' => $id])->num_rows();
        if ( $count > 0 ) {
            return 3;
        }

        $this->db->trans_start();

        $this->db->where('offer_id', $id);
        $this->db->delete('bank_offers');

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }



    public function getUserCustomId()
    {
        $this->load->helper('string');

        $custom_id = '';
        $count = 0;
        do {
            $custom_id = random_string('alnum', 5);
            $count = $this->db->get_where('user_table', ['user_custom_id' => $custom_id])->num_rows();
        } while ($count > 0);

        return $custom_id;
    }

    public function updateCustomId( $user_id, $custom_id )
    {
        $this->db->where('user_id', $user_id);
        $this->db->update('user_table', ['user_custom_id' => $custom_id]);
        return $this->db->affected_rows() > 0 ? 1 : 0;
    }

    public function setupFabricName()
    {
        /*$sellers = $this->db->get_where('seller_details', ['is_kandora_seller' => 1])->result();
        $seller_user_ids = array_column($sellers, 'user_id');

        $this->db->select('cattr_val.*');
        $this->db->from('category_attribute_values cattr_val');
        $this->db->join('category_attribute cattr', 'cattr_val.cat_attribute_id = cattr.cat_attribute_id', 'left');
        $this->db->where('cattr.cat_attribute_is_fabric_name', 1);
        $cat_attributes_values = $this->db->get()->result();

        $insert_data = [];
        foreach ($seller_user_ids as $store_id) {
            foreach ($cat_attributes_values as $row) {
                $t_row = (array) $row;

                unset($t_row['cat_attribute_val_id']);
                $t_row['cat_attribute_val_status'] = 1;
                $t_row['cat_attribute_val_store_id'] = $store_id;
                $insert_data[] = $t_row;
            }
        }

        $this->db->insert_batch('category_attribute_values', $insert_data);*/
    }

    public function getReportedIssues()
    {
        $this->db->select('pod_issue.*, pod.order_no, pod.product_order_id, user.user_first_name, user.user_last_name, seller.store_name');
        $this->db->from('product_order_report_issue pod_issue');
        $this->db->join('product_order_details pod', 'pod_issue.order_block_id = pod.order_block_id', 'left');
        $this->db->join('seller_details seller', 'pod_issue.store_id = seller.user_id', 'left');
        $this->db->join('user_table user', 'pod.user_id = user.user_id', 'left');
        $this->db->order_by('pod_issue.order_issue_id', 'desc');
        return $this->db->get()->result();
    }

    public function getReportedIssue( $id )
    {
        $this->db->select('pod_issue.*, pod.order_no, user.user_email_id');
        $this->db->from('product_order_report_issue pod_issue');
        $this->db->join('product_order_details pod', 'pod_issue.order_block_id = pod.order_block_id', 'left');
        $this->db->join('user_table user', 'pod.user_id = user.user_id', 'left');
        $this->db->where('pod_issue.order_issue_id', $id);
        return $this->db->get()->row();
    }

    public function saveReplyToIssue( $id, array $data=[] )
    {
        if (! empty($data) ) {
            $this->db->where('order_issue_id', $id);
            $this->db->update('product_order_report_issue', $data);
            return TRUE;
        }
        return FALSE;
    }

    public function getSiteConfig( $key=NULL )
    {
        $result = $this->db->get_where('config', ['config_status' => 1])->result();
        $result = array_column($result, 'config_value', 'config_key');
        if (! empty($key) ) {
            return $result[$key] ?? '';
        }
        return $result;
    }

    public function setSiteConfig( array $data=[] )
    {
        if (! empty($data) ) {

            $time_now = gmdate("Y-m-d H:i:s");

            $this->db->trans_start();

            $insert_data = [];
            $updated_keys = [];
            foreach ($data as $key => $value) {
                $insert_data[] = [
                    'config_key' => $key,
                    'config_value' => (float)$value,
                    'config_status' => 1,
                    'created_date' => $time_now,
                    'updated_date' => $time_now,
                ];
                $updated_keys[] = $key;
            }

            $this->db->where('config_status', 1);
            $this->db->where_in('config_key', $updated_keys);
            $this->db->update('config', ['updated_date' => $time_now, 'config_status' => 0]);

            $this->db->insert_batch('config', $insert_data);

            $this->db->trans_complete();
            if ($this->db->trans_status() === false) {
                return 0;
            } else {
                return 1;
            }
        }

        return 0;
    }

    public function getTableCount( $table, $condition=NULL )
    {
        if (! empty($condition) ) {
            $this->db->where($condition);
        }
        return $this->db->get($table)->num_rows();
    }

    public function getSalesGroupByMonth($condition=[])
    {
        $start_date     = $condition['start_date'] ?? '';
        $end_date       = $condition['end_date'] ?? '';
        $status         = $condition['status'] ?? '';
        $store_id       = $condition['store_id'] ?? '';

        if (! empty($start_date) ) {
            $this->db->where('(pod.order_placed_date)::DATE >=', $start_date);
        }
        if (! empty($end_date) ) {
            $this->db->where('(pod.order_placed_date)::DATE <=', $end_date);
        }
        if ( $store_id > 0 ) {
            $this->db->where('store.user_id', $store_id);            
        } else {
            if (! empty($status) ) {
                $this->db->where('pod.delivery_status', $status);
            }
        }

        $this->db->select("to_char(pod.order_placed_date, 'YYYY-MM') AS order_date, COUNT(pod.order_block_id) AS count");
        $this->db->from('product_order_details pod');
        if ( $store_id > 0 && !empty($status) ) {
            $this->db->join('(SELECT DISTINCT ON (order_block_id) order_block_id, product_id, deliver_status FROM product_order_history WHERE deliver_status = '. $this->db->escape($status) .') poh', 'pod.order_block_id = poh.order_block_id', 'left');
        } else {
            $this->db->join('(SELECT DISTINCT ON (order_block_id) order_block_id, product_id, deliver_status FROM product_order_history) poh', 'pod.order_block_id = poh.order_block_id', 'left');
        }        
        $this->db->join('product product', 'poh.product_id = product.product_id', 'left');
        $this->db->join('seller_details store', 'product.product_vender_id = store.user_id', 'left');
        $this->db->group_by("to_char(pod.order_placed_date, 'YYYY-MM')");
        $result = $this->db->get()->result_array();
        if (! empty($result) ) {
            $result = array_column($result, 'count', 'order_date');
        }
        return $result;
    }

    public function getTotalEarnings( $condition=[] )
    {
        /*$store_id   = $condition['store_id'] ?? '';
        if ( $store_id > 0 ) {
            $this->db->where('store.user_id', $store_id);
        }*/

        $this->db->where('poh.deliver_status', ORDER_STATUS_DELIVERED);

        $this->db->select('SUM(poh.khiat_commission) AS khiat_commission, SUM(poh.vendor_commission) AS vendor_commission');
        $this->db->from('product_order_history poh');
        $this->db->join('product_order_details pod', 'poh.order_block_id = pod.order_block_id', 'left');
        return $this->db->get()->row_array();
    }

    public function getEarningsGroupByMonth( $condition=[] )
    {
        $start_date = $condition['start_date'] ?? '';
        $end_date   = $condition['end_date'] ?? '';
        $store_id   = $condition['store_id'] ?? '';

        if (! empty($start_date) ) {
            $this->db->where('(pod.order_placed_date)::DATE >=', $start_date);
        }
        if (! empty($end_date) ) {
            $this->db->where('(pod.order_placed_date)::DATE <=', $end_date);
        }
        if ( $store_id > 0 ) {
            $this->db->where('store.user_id', $store_id);
        }

        $this->db->where('poh.deliver_status', ORDER_STATUS_DELIVERED);

        $this->db->select("to_char(pod.order_placed_date, 'YYYY-MM') AS order_date, SUM(poh.khiat_commission) AS khiat_commission, SUM(poh.vendor_commission) AS vendor_commission");
        $this->db->from('product_order_history poh');
        $this->db->join('product_order_details pod', 'poh.order_block_id = pod.order_block_id', 'left');
        $this->db->join('product product', 'poh.product_id = product.product_id', 'left');
        $this->db->join('seller_details store', 'product.product_vender_id = store.user_id', 'left');
        $this->db->group_by("to_char(pod.order_placed_date, 'YYYY-MM')");
        return $this->db->get()->result_array();
    }

    /**
     * Freelancer
     */
    public function getFreelancerCondition( $condition = array() )
    {
        if ( !empty($condition) ) {
            $this->db->where($condition);
        }
        return $this->db->select('*')
                        ->from('user_table u')
                        ->where("u.user_type", "F")
                        ->order_by('u.user_id', 'desc')
                        ->get()
                        ->result();
    }
    /**
     * Owners
     */
    public function getOwnerCondition( $condition = array() )
    {
        if ( !empty($condition) ) {
            $this->db->where($condition);
        }
        return $this->db->select('*')
                        ->from('user_table u')
                        ->where("u.user_type", "O")
                        ->order_by('u.user_id', 'desc')
                        ->get()
                        ->result();
    }

    public function getOwnerConditionIncludingOrderCount( $condition = array() )
    {
        if ( !empty($condition) ) {
            $this->db->where($condition);
        }
        return $this->db->select('*,(select count(distinct(pod.order_block_id)) from product_order_details pod join product_order_history poh on poh.order_block_id=pod.order_block_id where pod.user_id=u.user_id and poh.is_it_service=0) as order_count,(select count(distinct(pod.order_block_id)) from product_order_details pod join product_order_history poh on poh.order_block_id=pod.order_block_id where pod.user_id=u.user_id and poh.is_it_service=1) as service_count ')
                        ->from('user_table u')
                        ->where("u.user_type", "O")
                        ->order_by('u.user_id', 'desc')
                        ->get()
                        ->result();
    }

    /**
     * Architects
     */
    public function getArchitectCondition( $condition = array() )
    {
        if ( !empty($condition) ) {
            $this->db->where($condition);
        }
        return $this->db->select('*')
                        ->from('user_table u')
                        ->where("u.user_type", "A")
                        ->order_by('u.user_id', 'desc')
                        ->get()
                        ->result();
    }

    /**
     * Contractors
     */
    public function getContractorCondition( $condition = array() )
    {
        if ( !empty($condition) ) {
            $this->db->where($condition);
        }
        return $this->db->select('*')
                        ->from('user_table u')
                        ->where("u.user_type", "C")
                        ->order_by('u.user_id', 'desc')
                        ->get()
                        ->result();
    }

    /**
     * Projects
     */
    public function admin_list_projects( $params=[] )
    {
        $this->db->select('p.*, u.company_name, u.user_email_id');
        $this->db->from('project p');
        $this->db->join('user_table u', 'p.user_id = u.user_id', 'left');
        $this->db->order_by('p.project_id', 'desc');
        return $this->db->get()->result_array();
    }

    public function get_project_details( $project_id )
    {
        $this->db->select('p.*, u.company_name, u.user_email_id, u.image, u.trade_license_no');
        $this->db->from('project p');
        $this->db->join('user_table u', 'p.user_id = u.user_id', 'left');
        $this->db->where('p.project_id', $project_id);
        $rec = $this->db->get()->row_array();

        $record = $this->db->get_where('project_documents', ['Project_id' => $project_id])->result_array();
        $docs = [];
        foreach ($record as $row) {
            $docs[] = $row['uploads'];
        }
        $rec['document'] = $docs;

        $record = $this->db->get_where('project_documents_doc', ['Project_id' => $project_id])->result_array();
         $docs_file = [];
        foreach ($record as $row) {
            $docs_file[] = $row['documents'];
        }
        $rec['document_files'] = $docs_file;

        return $rec;
    }

    public function approveProject( $project_id, $status )
    {
        $this->db->where('project_id', $project_id);
        $this->db->update('project', ['status' => $status]);
        return 1;
    }

    public function deleteProject( $project_id )
    {
        $this->db->trans_start();

        $architect_requests = $this->db->get_where('architect_request', ['project_id' => $project_id])->result_array();
        if ( count($architect_requests) > 0 ) {
            $request_ids = array_column($architect_requests, 'request_id');
            $this->deleteArchitectRequest($request_ids, FALSE);
        }

        $this->db->delete('project_documents', ['Project_id' => $project_id]);

        $this->db->delete('project', ['project_id' => $project_id]);

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }

    public function deleteArchitectRequest( $request_ids=[], $transaction=FALSE )
    {
        if (! empty($request_ids) ) {

            if ( $transaction ) {
                $this->db->trans_start();
            }

            $this->db->where_in('request_id', $request_ids);
            $tenders = $this->db->get('tenders')->result_array();
            $tender_ids = array_column($tenders, 'tender_id');
            $this->deleteTender($tender_ids, FALSE);

            $this->db->where_in('request_id', $request_ids);
            $this->db->delete('boq_uploads');

            $this->db->where_in('request_id', $request_ids);
            $this->db->delete('design_uploads');

            $this->db->where_in('request_id', $request_ids);
            $this->db->delete('architect_request');

            if ( $transaction ) {
                $this->db->trans_complete();
                if ($this->db->trans_status() === false) {
                    return 0;
                } else {
                    return 1;
                }
            }
        }       

        return 1;
    }

    public function deleteTender( $tender_ids=[], $transaction=FALSE )
    {
        if (! empty($tender_ids) ) {

            if ( $transaction ) {
                $this->db->trans_start();
            }

            $this->db->where_in('tender_id', $tender_ids);
            $this->db->delete('tender_uploads');

            $this->db->where_in('tender_id', $tender_ids);
            $this->db->delete('tenders');

            $this->db->where_in('tender_id', $tender_ids);
            $this->db->delete('bidding');

            if ( $transaction ) {
                $this->db->trans_complete();
                if ($this->db->trans_status() === false) {
                    return 0;
                } else {
                    return 1;
                }
            }
        }

        return 1;
    }

    public function approved_architect( $project_id=0 )
    {
        $this->db->select('r.request_id, u.company_name, u.user_email_id, u.dial_code, u.phone_number');
        $this->db->from('user_table u');
        $this->db->join('architect_request r', 'r.architect_user_id = u.user_id', 'left');
        $this->db->where('r.status', 1);
        $this->db->where('r.project_id', $project_id);
        return $this->db->get()->result_array();
    }

    public function listBoqFiles( $request_id=0 )
    {
        $rec = $this->db->get_where('boq_uploads', ['request_id' => $request_id])->result_array();
        if ( count($rec) > 0 ) {
            $i = 0;
            foreach($rec as $row) {
                $rec[$i]['boq_upload'] = ($row['boq_upload']!='')? base_url().'uploads/architect/'.$row['boq_upload']:'';
                $i++;
            }
        }

        return $rec;
    }

    public function approveProjectRequest( $request_id, $status )
    {
        $this->db->where('request_id', $request_id);
        $this->db->update('architect_request', ['status' => $status]);
        return 1;
    }

    public function getProjectRequestDetails( $request_id )
    {
        if ( $request_id > 0 ) {
            $this->db->select('a.request_id, a.action_time as req_date, a.price, a.description as req_descript, p.project_id, p.project_title, p.location, p.description as proj_descript, p.post_date as proj_post_date,
            ar.company_name as architect, ar.user_location as arch_location, ar.user_email_id as arch_email, ar.trade_license_no as arch_lisence, ar.image as arch_profile_img, u.company_name as owner, u.image as owner_profile_img, u.trade_license_no as owner_lisence, u.user_email_id as owner_email');
            $this->db->from('architect_request a');
            $this->db->join('project p', 'a.project_id = p.project_id', 'left');
            $this->db->join('user_table u', 'p.user_id = u.user_id', 'left');
            $this->db->join('user_table ar', 'a.architect_user_id = ar.user_id', 'left');
            $this->db->where('a.request_id', $request_id);
            return $this->db->get()->result_array();
        }

        return [];
    }

    public function getProjectRequestDesignUploads( $request_id )
    {
        if ( $request_id > 0 ) {
            return $this->db->get_where('design_uploads', ['request_id' => $request_id])->result_array();
        }
        return [];
    }

    public function getProjectRequestBOQUploads( $request_id )
    {
        if ( $request_id > 0 ) {
            return $this->db->get_where('boq_uploads', ['request_id' => $request_id])->result_array();
        }
        return [];
    }

    public function listBoqDocFiles( $request_id )
    {
        $rec = $this->db->get_where('boq_uploads_doc', ['request_id' => $request_id])->result_array();
        if ( count($rec) > 0 ) {
            $i = 0;
            foreach($rec as $row) {
                $rec[$i]['boq_upload_doc'] = ($row['boq_upload_doc']!='')? base_url().'uploads/architect/'.$row['boq_upload_doc']:'';
                $i++;
            }
        }

        return $rec;
    }

    public function list_Design_files( $request_id=0 )
    {
        $rec = $this->db->get_where('design_uploads', ['request_id' => $request_id])->result_array();
        $i = 0;
        foreach ($rec as $row) {
            $rec[$i]['design_upload'] = ($row['design_upload']!='')? base_url().'uploads/architect/'.$row['design_upload']:'';
            $i++;
        }

        return $rec;
    }

    public function listdesignDocFiles( $request_id )
    {
        $rec = $this->db->get_where('design_upload_doc', ['request_id' => $request_id])->result_array();
        if ( count($rec) > 0) {
            $i=0;
            foreach($rec as $row) {
                $rec[$i]['design_upload_doc'] = ($row['design_upload_doc']!='')? base_url().'uploads/architect/'.$row['design_upload_doc']:'';
                $i++;
            }            
        }

        return $rec;
    }

    public function architect_requests( $params=[] )
    {
        $this->db->select("DISTINCT (a.request_id), o.company_name AS owner, a.status, a.request_id, p.project_title, p.location, a.action_time AS req_date, u.company_name AS architect, CASE WHEN boq.boq_upload IS NOT NULL THEN '1' ELSE '0' END AS boq_status, CASE WHEN des.design_upload IS NOT NULL THEN '1' ELSE '0' END AS des_status");
        $this->db->from('architect_request a');
        $this->db->join('project p', 'a.project_id = p.project_id', 'left');
        $this->db->join('user_table u', 'a.architect_user_id = u.user_id', 'left');
        $this->db->join('user_table o', 'p.user_id = o.user_id', 'left');
        $this->db->join('boq_uploads boq', 'a.request_id = boq.request_id', 'left');
        $this->db->join('design_uploads des', 'a.request_id = des.request_id', 'left');

        $project_id = $params['project_id'] ?? 0;
        if ( $project_id > 0 ) {
            $this->db->where('p.project_id', $project_id);
        }

        return $this->db->get()->result_array();
    }

    /**
     * Tender
     */
    public function tender_details( $request_id=0)
    {
        return $this->db->get_where('tenders', ['request_id' => $request_id])->result_array();
    }

    public function tender_list( $request_id=0 )
    {
        $this->db->from('tender_uploads tu');
        $this->db->join('tenders t', 'tu.tender_id = t.tender_id', 'left');
        $this->db->where('t.request_id', $request_id);
        return $this->db->get()->result_array();
    }

    public function get_tender_id( $request_id=0 )
    {
        $rec = $this->db->get_where('tenders', ['request_id' => $request_id])->row_array();
        if ( $rec ) {
            return $rec['tender_id'];
        }

        return NULL;
    }

    public function won_bid( $tender_id=0 )
    {
        $today = gmdate('Y-m-d H:i:s');

        $this->db->select('MIN(b.bidding_amount) AS won_amount, b.action_time AS bid_date, u.company_name AS contractor, u.user_email_id, u.dial_code, u.phone_number');
        $this->db->from('bidding b');
        $this->db->join('tenders t', 'b.tender_id = t.tender_id', 'left');
        $this->db->join('user_table u', 'b.contractor_id = u.user_id', 'left');
        $this->db->where('t.tender_id', $tender_id);
        $this->db->where('t.closing_date <', $today);

        return $this->db->get()->result_array();
    }

    public function get_tenders( $params=[] )
    {
        $time_now = gmdate('Y-m-d H:i:s');        

        $this->db->select("DISTINCT (t.tender_id), u.company_name, t.tender_no, t.tenderBudget, t.closing_date, t.status, p.project_title, CASE WHEN t.closing_date < '$time_now' THEN 'E' ELSE 'L' END AS live_status, CASE WHEN (SELECT COUNT(bidding_id) AS cnt FROM bidding WHERE tender_id = t.tender_id) > 0 THEN '1' ELSE '0' END AS bid_status");
        $this->db->from('tenders t');
        $this->db->join('architect_request a', 't.request_id = a.request_id', 'left');
        $this->db->join('project p', 'a.project_id = p.project_id', 'left');
        $this->db->join('user_table u', 'p.user_id = u.user_id', 'left');

        $request_id = $params['request_id'] ?? 0;
        if ( $request_id > 0 ) {
            $this->db->where('t.request_id', $request_id);
        }
        $this->db->order_by('t.tender_id', 'desc');

        return $this->db->get()->result_array();
    }

    public function getTenderDetails( $tender_id )
    {
        $result = [
            'data' => [],
            'uploads' => [],
        ];

        if ( $tender_id > 0) {
            $this->db->select('p.project_title, u.company_name, u.trade_license_no as user_license, t.tender_no, t.closing_date, t.description,
            t.tenderBudget, p.location, p.latitude, p.longitude, p.description as project_descr');
            $this->db->from('tenders t');
            $this->db->join('architect_request a', 't.request_id = a.request_id', 'left');
            $this->db->join('project p', 'a.project_id = p.project_id', 'left');
            $this->db->join('user_table u', 'p.user_id = u.user_id', 'left');
            $this->db->where('t.tender_id', $tender_id);
            $result['data'] = $this->db->get()->row_array();

            $this->db->select('upload_id, tender_file, action_time');
            $this->db->from('tender_uploads');
            $this->db->where('tender_id', $tender_id);
            $result['uploads'] = $this->db->get()->result_array();
        }

        return $result;
    }

    public function getWonBidList( $params=[] )
    {
        $time_now = gmdate('Y-m-d H:i:s');

        $this->db->select("b.bidding_id, b.tender_id, b.action_time, t.tender_no, p.project_title, u.company_name AS owner, c.company_name AS contractor, t.tenderBudget, t.closing_date, MIN(b.bidding_amount) AS bidding_amount");
        $this->db->from('bidding b');
        $this->db->join('tenders t', 'b.tender_id = t.tender_id', 'left');
        $this->db->join('architect_request a', 't.request_id = a.request_id', 'left');
        $this->db->join('project p', 'a.project_id = p.project_id', 'left');
        $this->db->join('user_table u', 'p.user_id = u.user_id', 'left');
        $this->db->join('user_table c', 'b.contractor_id = c.user_id', 'left');
        $this->db->where('t.closing_date <', $time_now);

        $tender_id = $params['tender_id'] ?? 0;
        if ( $tender_id > 0 ) {
            $this->db->where('t.tender_id', $tender_id);
        }

        $this->db->group_by(['t.tender_id', 'b.bidding_id', 'b.tender_id', 'b.action_time', 't.tender_no', 'p.project_title', 'u.company_name', 'c.company_name', 't.tenderBudget', 't.closing_date']);
        $this->db->order_by('b.action_time', 'asc');

        return $this->db->get()->result_array();
    }

    public function getWonBidDetails( $bidding_id )
    {
        $this->db->select("u.company_name AS owner, u.user_email_id AS owner_email, u.trade_license_no AS owner_license, u.image AS owner_img, p.project_id, p.project_title, p.location, p.description, t.tender_id, t.tender_no, t.tenderBudget, t.closing_date, b.bidding_id, b.action_time, c.company_name AS contractor, c.image AS contractor_img, MIN(b.bidding_amount) AS bidding_amount");
        $this->db->from('bidding b');
        $this->db->join('tenders t', 'b.tender_id = t.tender_id', 'left');
        $this->db->join('architect_request a', 't.request_id = a.request_id', 'left');
        $this->db->join('project p', 'a.project_id = p.project_id', 'left');
        $this->db->join('user_table u', 'p.user_id = u.user_id', 'left');
        $this->db->join('user_table c', 'b.contractor_id = c.user_id', 'left');
        $this->db->where('t.tender_id', $bidding_id);
        $this->db->group_by(['b.tender_id', 'u.user_email_id', 'u.company_name', 'u.trade_license_no', 'u.image', 'p.project_id', 'p.project_title', 'p.location', 'p.description', 't.tender_id', '', 't.tender_no', 't.tenderBudget', 't.closing_date', 'b.bidding_id', 'b.action_time', 'c.company_name', 'c.image']);
        $this->db->order_by('b.action_time', 'asc');

        $result['data'] = $this->db->get()->result_array();

        $project_id =   $result['data'][0]['project_id'] ?? 0;
        $tender_id  =   $result['data'][0]['tender_id'] ?? 0;

        $this->db->select('uploads');
        $this->db->from('project_documents');
        $this->db->where('Project_id', $project_id);
        $result['project_doc'] = $this->db->get()->result_array();

        $this->db->select('tender_file');
        $this->db->from('tender_uploads');
        $this->db->where('tender_id', $tender_id);
        $result['tender_doc'] = $this->db->get()->result_array();

        return $result;
    }

    public function getPropertyTypes( $condition=[] )
    {
        if (! empty($condition) ) {
            $this->db->where($condition);
        }
        $this->db->order_by('property_types', 'asc');
        return $this->db->get('property_types')->result();
    }

    public function savePropertyType( $data=[] )
    {
        $pk_id = $data['pk_id'] ?? 0;
        if ( isset($data['pk_id']) ) {
            unset($data['pk_id']);
        }

        if ( $pk_id == 0 ) {
            $this->db->order_by('id', 'desc');
            $rec = $this->db->get('property_types')->row_array();
            if (! empty($rec) ) {
                $data['id'] = $rec['id'] + 1;
            } else {
                $data['id'] = 1;
            }
            $this->db->insert('property_types', $data);
        } else {
            $this->db->update('property_types', $data, ['pk_id' => $pk_id]);
        }

        return true;
    }

    public function deletePropertyType( $pk_id )
    {
        $this->db->update('property_types', ['status' => 0], ['pk_id' => $pk_id]);
        return 1;
    }

    public function getContractorTypes( $condition=[] )
    {
        if (! empty($condition) ) {
            $this->db->where($condition);
        }
        $this->db->order_by('contractor_type_name', 'asc');
        return $this->db->get('contractor_type')->result();
    }

    public function saveContractorType( $data=[] )
    {
        $contractor_type_id = $data['contractor_type_id'] ?? 0;
        if ( isset($data['contractor_type_id']) ) {
            unset($data['contractor_type_id']);
        }

        if ( $contractor_type_id == 0 ) {
            $data['added_date'] = gmdate("Y-m-d H:i:s");
            $this->db->insert('contractor_type', $data);
        } else {
            $this->db->update('contractor_type', $data, ['contractor_type_id' => $contractor_type_id]);
        }

        return true;
    }

    public function deleteContractorType( $id )
    {
        $this->db->update('contractor_type', ['contractor_type_status' => 0], ['contractor_type_id' => $id]);
        return 1;
    }


    ##Collection Section Start
    function getCollectionList()
    {
        $language =($this->session->userdata('language')?$this->session->userdata('language'):1);
        $this->db->select('c.*,c2.collection_name as arbicname,c.collection_name as englishname');
        $this->db->from('collection c');
        $this->db->join('collection c2', 'c2.collection_id =c.collection_id', 'left');

        $this->db->where('c.collection_language_code', 1);
        $this->db->where('c2.collection_language_code', 2);
        $this->db->order_by('c.collection_id', 'desc');
        $query = $this->db->get();
        return $query->result();
    }
    function getCollection($language, $id)
    {

        $this->db->select('*');
        $this->db->from('collection c');
        $this->db->where('collection_language_code', $language);
        $this->db->where('collection_id', $id);
        $this->db->order_by('collection_language_code', 'ASC');
        $query = $this->db->get();
//echo $this->db->last_query();
        return $query->row();
    }
    function collectionList($language)
    {

        $this->db->select('*');
        $this->db->from('collection c');
        $this->db->where('collection_language_code', $language);
        $query = $this->db->get();
        return $query->result();
    }
    function deleteCollection($id)
    {

               $this->db->trans_start();

               $this -> db -> where('collection_id', $id);
               $this -> db -> delete('collection');


              //admin audit trial //admin audit trial//admin audit trial//admin audit trial

                $auditArray                     =     array();
                $auditArray['admin_id']         =     $this->session->userdata('admin_id');
                $auditArray['module_id']        =     11;
                $auditArray['entity_id']        =     $id;
                $auditArray['action_id']        =     3;
                $auditArray['audit_time']       =     gmdate("Y-m-d H:i:s");
                $auditArray['audit_note']       =     "collection delete from admin module";
                $auditArray['menu_id']          =     5;
                $this->db->insert('admin_audit_trial', $auditArray);

               //admin audit trial //admin audit trial//admin audit trial//admin audit trial


                 $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return 1;
        }
    }

    protected  function _getCustomerReport($filter)
    {
        return ("select ut.user_first_name,ut.user_last_name,ut.user_email_id,CONCAT(ut.dial_code,'-',ut.phone_number) AS mobile_no,city.city_name,c.country_name,ut.user_status::text AS user_status,ut.user_created_date::text AS user_created_date,(select count(order_block_id) from product_order_details where user_id=ut.user_id)::text as order_count,ut.user_id::text as user_id
                from user_table ut 
                left join seller_details sd ON (ut.user_id=sd.user_id)
                left join country c ON (c.country_id=ut.user_country_id and c.country_language_code=1)
                left join city ON (city.city_id=ut.user_city_id and city.city_language_code=1)
                where 1=1 {$filter} AND ut.user_type='O'");
    }

    public function getCustomerReport($datatable, $filter = "")
    {
        $sql =  $this->_getCustomerReport($filter);
        return $datatable->query($sql);
    }

    public function getStoreExcelReport($filter = "")
    {
        $sql =  $this->_getStoreReport($filter);
        return $this->db->query($sql)->result();
    }

    public function getStoreReport($datatable, $filter = "")
    {
        $sql =  $this->_getStoreReport($filter);
        return $datatable->query($sql);
    }

    protected function _getStoreReport($filter = "")
    {
        return ("select ut.user_first_name,ut.user_last_name,sd.store_name,ut.user_email_id,sd.mobile_no,city.city_name,c.country_name,ut.user_status::text AS user_status,ut.user_created_date::text AS user_created_date,(select count(distinct(pod.order_block_id)) from product_order_details pod join product_order_history poh on poh.order_block_id=pod.order_block_id left join product on product.product_id=poh.product_id left join services on services.service_id=poh.service_id where product.product_vender_id=ut.user_id or services.service_vendor_user_id=ut.user_id  )::text as order_count,ut.user_id::text as user_id
        from user_table ut 
        left join seller_details sd ON (ut.user_id=sd.user_id)
        left join country c ON (c.country_id=ut.user_country_id and c.country_language_code=1)
        left join city ON (city.city_id=sd.city and city.city_language_code=1)
        where 1=1 {$filter} AND  ut.user_type='V'");
    }

    function getvendorList()
    {
        return $this->db->query("select ut.user_first_name,ut.user_last_name,ut.user_email_id,ut.user_status,ut.user_created_date,sd.mobile_no,sd.store_name,c.country_name,city.city_name
        from user_table ut 
        left join seller_details sd ON (ut.user_id=sd.user_id)
        left join country c ON (c.country_id=ut.user_country_id and c.country_language_code=1)
        left join city ON (city.city_id=sd.city and city.city_language_code=1)
        where ut.user_type='V'")->result();
    }

    public function getCustomerExcelReport($filter = "")
    {
        $sql =  $this->_getCustomerReport($filter);
        return $this->db->query($sql)->result();
    }

    function _getDriversList($filter = "")
    {
        /*return "select CONCAT(ut.user_first_name,' ',ut.user_last_name) as user_name, ut.user_email_id, dd.mobile_no, sd.store_name,dd.vehicle_no, ut.user_status::text AS user_status, ut.user_created_date::text AS user_created_date
            from user_table ut 
            inner join driver_details dd ON (ut.user_id=dd.user_id)
            left join seller_details sd ON (dd.vendor_id=sd.user_id)
            where 1=1 {$filter} and ut.user_type='D'";*/

            return "select concat(ut.user_first_name,' ',ut.user_last_name) as user_name, ut.user_email_id, dd.mobile_no, sd.store_name,dd.vehicle_no, ut.user_status::text AS user_status, ut.user_created_date::text AS user_created_date, cast(count(distinct(pod.order_block_id)) AS TEXT) orders_assigned, poh.driver_id::text as driver_id, city.city_name, country.country_name, bm.bank_name, dd.bank_account_number, dd.bank_ifsc_code, dd.bank_swift_code
                from user_table ut 
                inner join driver_details dd ON (ut.user_id=dd.user_id)
                left join seller_details sd ON (dd.vendor_id=sd.user_id)
                left join product_order_history poh ON (dd.user_id=poh.driver_id)
                left join product_order_details pod ON (pod.order_block_id=poh.order_block_id)
                left join city ON (city.city_id=dd.city and city_language_code=1)
                left join country ON (country.country_id=ut.user_country_id and country_language_code=1)
                left join bank_master bm ON (bm.bank_id=dd.driver_bank_id)
                where 1=1 {$filter} and ut.user_type='D'
                group by ut.user_first_name, ut.user_last_name, ut.user_email_id, dd.mobile_no, sd.store_name,dd.vehicle_no, ut.user_status, ut.user_created_date, poh.driver_id,city.city_name, country.country_name, bm.bank_name, dd.bank_account_number, dd.bank_ifsc_code, dd.bank_swift_code
                order by cast(count(poh.driver_id) AS TEXT) DESC";
    }
    function getDriversExcelList( $filter = "")
    {
        $sql = $this->_getDriversList($filter);
        return $this->db->query($sql)->result();
    }
    function getDriversList($datatable, $filter = "")
    {
        $sql = $this->_getDriversList($filter);
        return $datatable->query($sql);
    }
    public function get_orders_count($params=[]){
        $this->db->select("count(distinct(pod.order_block_id)) as count");
        $this->db->from("product_order_details pod");
        $this->db->join("product_order_history poh","poh.order_block_id=pod.order_block_id");
        if($params){
            if(isset($params['is_service']) && $params['is_service'] != ""){
                $this->db->where("poh.is_it_service",1);
            }
            if(isset($params['is_product']) && $params['is_product'] != ""){
                $this->db->where("poh.is_it_service",0);
            }
        }
        return $this->db->get()->row()->count;
    }

    public function getStoreTimeSlots($condition=[])
    {
        $this->db->select("s.*,sd.store_name");

        if(!empty($condition))
            $this->db->where($condition);

        $this->db->join("seller_details sd","sd.user_id=s.store_id","left");

        $this->db->order_by('s.day_id asc');

        return $this->db->get('store_time_slots s');

    }

    public function saveTimeslot($post)
    {
        $data = [
            'store_id'=>(int)$post['store_id'],
            'day_id'=>(int)$post['day_id'],
            'time_slot'=>(string)$post['time_slot'],
            'status'=>(int)$post['status'],
        ];

        if((int)$post['id'] > 0)
        {
            $this->db->where('slot_id', (int)$post['id']);
            if($this->db->update('store_time_slots', $data))
                return 1;
        }
        else
        {
            $data['created_date_time'] = gmdate("Y-m-d H:i:s");
            if($this->db->insert('store_time_slots', $data))
                return 1;
        }

        return 0;
    }

    function deleteTimeSlot($id)
    {
        $this->db->trans_start();
        $this -> db -> where('slot_id', $id);
        $this -> db -> delete('store_time_slots');

        $this->db->trans_complete();

        if ($this->db->trans_status() === false)
        {
            return 0;
        }
        else
        {
            return 1;
        }
    }
}
