<?php
defined('BASEPATH') or exit('No direct script access allowed');

use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\CodeigniterAdapter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class C_admin extends ACP_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->config('app');
        $this->load->model('M_admin');
        $this->load->model('M_vendor');
        $this->load->model('V_product'); 
        //$this->lang->load("message","arabic");
        // error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING );
        error_reporting(E_ERROR | E_PARSE);
        $this->userTimezone ="Asia/Dubai";
    }

    public function index()
    {
        //$languageCode   = ($this->input->post('language')>0?$this->input->post('language'):1);
        // $country = $this->M_admin->getCountries($languageCode);

        //print_r($country);

        $this->load->view("admin/login");
    }
    public function home_offer_banners(){
        $this->load->model("Common");
        $data['home_offer_banners_list']=$this->Common->get_all_by_need('home_banners');
        $data['bottom_home_offer_banners_list']=$this->Common->get_all_by_need('home_banners_bottom');
        $data['homer_offer_content']=$this->Common->get_all_by_need('home_offers');
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/home_offer_banner_list", $data);
        $this->load->view("admin/footer");
    }
    public function saveHomeBanners(){
        $this->load->model("Common");
        $this->load->library('upload');
        $data['status'] = "0";
        $config['upload_path']          = './uploads/home_offers';
        $config['allowed_types']        = 'pdf|jpg|jpeg';
         $config['encrypt_name']         = TRUE;
        $this->upload->initialize($config);
        //var_dump($_FILES);
        $ins = array(
            'url1'  =>  $this->input->post("url1"),
            'url2'  =>  $this->input->post("url2"),
        );
         if ( ! $this->upload->do_upload('banner_image_1'))
        {
            $data['status'] = 3;
            $data['errors'] = array(
                'banner_image_1' => "File upload failed due to " . $this->upload->display_errors(),
            );
            //echo json_encode($data);
            //exit();
         }else {
            $response = $this->upload->data();
            $banner_image_1=$response['file_name'];  
         }
         $config['upload_path']          = './uploads/home_offers';
        $config['allowed_types']        = 'pdf|jpg|jpeg';
         $config['encrypt_name']         = TRUE;
        $this->upload->initialize($config);
         if ( ! $this->upload->do_upload('banner_image_2'))
        {
            $data['status'] = 3;
            $data['errors'] = array(
                'banner_image_2' => "File upload failed due to " . $this->upload->display_errors(),
            );
            //echo json_encode($data);
            //exit();
         }else {
            $response = $this->upload->data();
            $banner_image_2=$response['file_name'];  
         }
         if($banner_image_2 != ""){
            $ins['banner_image_2']=$banner_image_2;
         }
         if($banner_image_1 != ""){
            $ins['banner_image_1']=$banner_image_1;
         }
         //var_dump($ins);
         if(!empty($ins)){
            $ret=$this->Common->update("home_banners",$ins,array('home_banner_id'=>1));
            if($ret){
                $data['status'] = 1;
                $data['message'] = "Updated successfully";
                
            }else{
                $data['status'] = 0;
                $data['message'] = "faild to update";
            }
         }

         echo json_encode($data);

    }

    public function saveBottomHomeBanners()
    {
        $this->load->model("Common");
        $this->load->library('upload');
        $data['status'] = "0";
        
        $config['upload_path']          = './uploads/home_offers';
        $config['allowed_types']        = 'pdf|jpg|jpeg';
        $config['encrypt_name']         = TRUE;
        $this->upload->initialize($config);

        $ins = array(
            'url_1'  =>  $this->input->post("bottom_url1"),
            'url_2'  =>  $this->input->post("bottom_url2"),
            'url_3'  =>  $this->input->post("bottom_url3"),
            'url_4'  =>  $this->input->post("bottom_url4"),
            'url_5'  =>  $this->input->post("bottom_url5"),
            'url_6'  =>  $this->input->post("bottom_url6"),
        );
         if ( ! $this->upload->do_upload('bottom_banner_image_1'))
        {
            $data['status'] = 3;
            $data['errors'] = array(
                'bottom_banner_image_1' => "File upload failed due to " . $this->upload->display_errors(),
            );
        }
        else{
           $response = $this->upload->data();
           $bottom_banner_image_1=$response['file_name'];  
        }
         
        $config['upload_path']          = './uploads/home_offers';
        $config['allowed_types']        = 'pdf|jpg|jpeg';
        $config['encrypt_name']         = TRUE;
        $this->upload->initialize($config);
         if ( ! $this->upload->do_upload('bottom_banner_image_2'))
        {
            $data['status'] = 3;
            $data['errors'] = array(
                'bottom_banner_image_2' => "File upload failed due to " . $this->upload->display_errors(),
            );
        }
        else {
           $response = $this->upload->data();
           $bottom_banner_image_2=$response['file_name'];  
        }

        $config['upload_path']          = './uploads/home_offers';
        $config['allowed_types']        = 'pdf|jpg|jpeg';
        $config['encrypt_name']         = TRUE;
        $this->upload->initialize($config);
        if ( ! $this->upload->do_upload('bottom_banner_image_3'))
        {
            $data['status'] = 3;
            $data['errors'] = array(
                'bottom_banner_image_3' => "File upload failed due to " . $this->upload->display_errors(),
            );
        }
        else {
           $response = $this->upload->data();
           $bottom_banner_image_3=$response['file_name'];  
        }

        $config['upload_path']          = './uploads/home_offers';
        $config['allowed_types']        = 'pdf|jpg|jpeg';
        $config['encrypt_name']         = TRUE;
        $this->upload->initialize($config);
        if ( ! $this->upload->do_upload('bottom_banner_image_4'))
        {
            $data['status'] = 3;
            $data['errors'] = array(
                'bottom_banner_image_4' => "File upload failed due to " . $this->upload->display_errors(),
            );
        }
        else {
           $response = $this->upload->data();
           $bottom_banner_image_4=$response['file_name'];  
        }

        $config['upload_path']          = './uploads/home_offers';
        $config['allowed_types']        = 'pdf|jpg|jpeg';
        $config['encrypt_name']         = TRUE;
        $this->upload->initialize($config);
        if ( ! $this->upload->do_upload('bottom_banner_image_5'))
        {
            $data['status'] = 3;
            $data['errors'] = array(
                'bottom_banner_image_5' => "File upload failed due to " . $this->upload->display_errors(),
            );
        }
        else {
           $response = $this->upload->data();
           $bottom_banner_image_5=$response['file_name'];  
        }

        $config['upload_path']          = './uploads/home_offers';
        $config['allowed_types']        = 'pdf|jpg|jpeg';
        $config['encrypt_name']         = TRUE;
        $this->upload->initialize($config);
        if ( ! $this->upload->do_upload('bottom_banner_image_6'))
        {
            $data['status'] = 3;
            $data['errors'] = array(
                'bottom_banner_image_6' => "File upload failed due to " . $this->upload->display_errors(),
            );
        }
        else {
           $response = $this->upload->data();
           $bottom_banner_image_6=$response['file_name'];  
        }
        

        if($bottom_banner_image_1 != ""){
           $ins['banner_image_1']=$bottom_banner_image_1;
        }
        if($bottom_banner_image_2 != ""){
           $ins['banner_image_2']=$bottom_banner_image_2;
        }
        if($bottom_banner_image_3 != ""){
           $ins['banner_image_3']=$bottom_banner_image_3;
        }
        if($bottom_banner_image_4 != ""){
           $ins['banner_image_4']=$bottom_banner_image_4;
        }
        if($bottom_banner_image_5 != ""){
           $ins['banner_image_5']=$bottom_banner_image_5;
        }
        if($bottom_banner_image_6 != ""){
           $ins['banner_image_6']=$bottom_banner_image_6;
        }

        if(!empty($ins)){
           $ret=$this->Common->update("home_banners_bottom",$ins,array('home_banner_bottom_id'=>1));
           if($ret){
               $data['status'] = 1;
               $data['message'] = "Updated successfully";
               
           }else{
               $data['status'] = 0;
               $data['message'] = "faild to update";
           }
        }

        echo json_encode($data);

    }
    
    public function saveHomeOffer(){
        $this->load->model("Common");
       
        $ins = array(
            'offer_title'  =>  $this->input->post("offer_title"),
            'offer_subtitle'  =>  $this->input->post("offer_subtitle"),
            'url' => $this->input->post('offer_url'),
        );
         
         //var_dump($ins);
         if(!empty($ins)){
            $ret=$this->Common->update("home_offers",$ins,array('home_offer_id'=>1));
            if($ret){
                $data['status'] = 1;
                $data['message'] = "Updated successfully";
                
            }else{
                $data['status'] = 0;
                $data['message'] = "faild to update";
            }
         }

         echo json_encode($data);

    }

    public function dashBoard()
    {
        $data = [
            'store_count' => $this->M_admin->getTableCount('seller_details'),
            'owner_count' => $this->M_admin->getTableCount('user_table', "user_type='O'"),
            'architect_count' => $this->M_admin->getTableCount('user_table', "user_type='A'"),
            'contractor_count' => $this->M_admin->getTableCount('user_table', "user_type='C'"),
            'driver_count' => $this->M_admin->getTableCount('driver_details'),
            'order_count' => $this->M_admin->get_orders_count(['is_product'=>1]),
            'service_count' => $this->M_admin->get_orders_count(['is_service'=>1]),
        ];
        $search_condition=['status' => ORDER_STATUS_DELIVERED];
        $overAllSalesCount = $this->M_product->getSalesHistoryCount($search_condition);
        
        $data['overAllSalesCount'] = $overAllSalesCount;
        $order_statuses = $this->config->item('order_delivery_statuses', 'app');
        $data['order_count_chart_data'] = [];
        $data['order_count_chart_label'] = [];
        foreach ($order_statuses as $tmp_status => $tmp_row) {
            $data['order_count_chart_data'][] = $this->M_product->getOrderDeleiveryCountAll($tmp_status);
            $data['order_count_chart_label'][] = "'" . $tmp_row[1] . "'";
        }
        $data['order_count_chart_data'] = '[' . implode(',', $data['order_count_chart_data']) . ']';
        $data['order_count_chart_label'] = '[' . implode(',', $data['order_count_chart_label']) . ']';

        $earnings_count_data = $this->M_admin->getTotalEarnings();
        $earnings_count_data = array_map('round', $earnings_count_data);
        $data['earnings_count_chart_data'] = '[' . implode(',', array_values($earnings_count_data)) . ']';

        // Sales Chart & Earnings Chart
        $month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
        $current_month = date('n');
        $start_year = date('Y');
        $current_month_days = date('t');
        $list_count = 0;
        $chart_keys = [];
        $chart_labels = [];
        $sales_chart_delivered = [];
        $sales_chart_cancelled = [];
        for ($i = $current_month; $i > 0; $i--) {
            $m = ($i < 10) ? "0{$i}" : $i;
            $chart_keys[] = "{$start_year}-{$m}";
            $chart_labels[] = "'" . $month_names[$i-1] . "'";

            $list_count++;
            if ($list_count > 5) break;
            if ($i == 1) {
                $start_year--;
                $current_month = 13;
                $i = 13;
            }
        }
        $search_condition = [
            'start_date' => $chart_keys[count($chart_keys)-1] . "-01",
            'end_date' => $chart_keys[0] . "-{$current_month_days}",
            'status' => ORDER_STATUS_DELIVERED,
        ];
        $delivered_data = $this->M_admin->getSalesGroupByMonth($search_condition);

        $search_condition['status'] = ORDER_STATUS_CANCEL;
        $cancelled_data = $this->M_admin->getSalesGroupByMonth($search_condition);

        $chart_labels = array_reverse($chart_labels);
        $chart_keys = array_reverse($chart_keys, TRUE);
        foreach ($chart_keys as $chart_key) {
            $tmp_delivered = $delivered_data[$chart_key] ?? 0;
            $tmp_cancelled = $cancelled_data[$chart_key] ?? 0;
            $sales_chart_delivered[] = $tmp_delivered;
            $sales_chart_cancelled[] = $tmp_cancelled;
        }

        $data['sales_chart_labels'] = '[' . implode(',', $chart_labels) . ']';
        $data['sales_chart_delivered'] = '[' . implode(',', $sales_chart_delivered) . ']';
        $data['sales_chart_cancelled'] = '[' . implode(',', $sales_chart_cancelled) . ']';

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/dashboard", $data);
        $this->load->view("admin/footer");
    }

    public function login()
    {
        // Clear all login sessions
        $this->clearLoginSessions();

        $data = array('admin_user_email' => $_POST['username'], 'admin_user_password' => MD5($_POST['password']), 'admin_user_status' => 1);

        $result = $this->M_admin->login($data);
        //print_r($result);

        if ($result == "") {
            echo 0;
        } else {
            if ($result->admin_user_email != "") {
                echo 1;

                //$this->session->sess_destroy();

                $this->session->unset_userdata('admin_email');
                $this->session->unset_userdata('admin_id');
                $this->session->unset_userdata('admin_name');
                $this->session->unset_userdata('user_type');
                $this->session->unset_userdata('admin_display_name');
                $this->session->unset_userdata('admin_designation');
                $this->session->unset_userdata('user_id');

                $this->session->set_userdata("admin_email", $result->admin_user_email);
                $this->session->set_userdata("admin_id", $result->admin_user_id);
                $this->session->set_userdata("admin_name", $result->admin_user_name);
                $this->session->set_userdata("user_type", "A");
                $this->session->set_userdata("admin_display_name", $result->admin_first_name . " " . $result->admin_last_name);
                $this->session->set_userdata("admin_designation", $result->designation_id);
            } else {
                echo 0;
            }
        }
    }

    public function logout()
    {
        $this->session->sess_destroy();
        $this->session->unset_userdata("admin_email");
        $this->session->unset_userdata("admin_id");
        redirect("admin");
    }

    public function countryList()
    {

        $data["countrylist"] = $this->M_admin->getCountriesByAjax();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/country_list", $data);
        $this->load->view("admin/footer");
    }

    public function listCountryAjax()
    {

        $searchKey = $_POST['searchKey'];
        $pageNo = $_POST['page'];

        $this->load->library('pagination');
        $additional = $_POST;

        $data = array();
        $limit_per_page = 3;

        $start_index = ($this->uri->segment(2) > 0 ? ($this->uri->segment(2) - 1) * $limit_per_page : 0);
        //$start_index                =   $start_index*
        $records = $this->M_admin->getCountriesByAjaxTotal($additional);
        $total_records = $records->count;

        if ($total_records > 0) {
            // get current page records
            $data["countrylist"] = $this->M_admin->getCountriesByAjax($limit_per_page, $start_index, $additional);
            $config['base_url'] = base_url() . '/country_list_ajax/';
            $config['total_rows'] = $total_records;
            $config['per_page'] = $limit_per_page;
            // $config["uri_segment"]      =   2;

            // custom paging configuration

            $config['use_page_numbers'] = true;
            $config['reuse_query_string'] = true;

            $config['full_tag_open'] = '<ul class="pagination">';
            $config['full_tag_close'] = '</ul>';

            //$config['first_link']         =   'First Page';
            $config['first_tag_open'] = '<li class="page-link">';
            $config['first_tag_close'] = '</li>';

            //$config['last_link']          =   'Last Page';
            $config['last_tag_open'] = '<li class="page-link">';
            $config['last_tag_close'] = '</li>';

            $config['next_link'] = '&gt;';
            $config['next_tag_open'] = '<li class="page-link">';
            $config['next_tag_close'] = '</li>';

            $config['prev_link'] = '&lt;';
            $config['prev_tag_open'] = '<li class="page-link">';
            $config['prev_tag_close'] = '</li>';

            $config['cur_tag_open'] = '<li class="active page-item"> <a class="page-link" href="javascript:void(0);">';
            $config['cur_tag_close'] = '</a></li>';

            $config['num_tag_open'] = '<li class="page-link">';
            $config['num_tag_close'] = '</li>';
            $config["num_links"] = 2;

            $this->pagination->initialize($config);

            // build paging links
            $data["links"] = $this->pagination->create_links();
        }

        $this->load->view('admin/country_list_ajax.php', $data);
    }

    public function addEditCountry()
    {

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_country");
        $this->load->view("admin/footer");
    }

    public function saveCountry()
    {

        $data = array();

        $this->form_validation->set_rules('txtEnglish', 'Country Name English', 'trim|required|max_length[100]');
        $this->form_validation->set_rules('txtArabic', 'Country Name Arabic', 'trim|required|max_length[100]');
        $this->form_validation->set_rules('txtDialCode', 'Dial Code', 'trim|required|numeric|max_length[5]');
        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txtEnglish' => form_error('txtEnglish'),
                'txtArabic' => form_error('txtArabic'),
                'txtDialCode' => form_error('txtDialCode'),
            );
            echo json_encode($data);
            exit();
        }

        $inputArray['country_name'] = $_POST['txtEnglish'];
        $inputArray['country_language_code'] = 1;
        $inputArray['country_dial_code'] = $_POST['txtDialCode'];
        $inputArray['country_status'] = $_POST['txtStatus'];
        $inputArray['country_created_date'] = gmdate("Y-m-d H:i:s");
        $inputArray2 = $inputArray;
        $inputArray2['country_name'] = ($_POST['txtArabic'] != "" ? $_POST['txtArabic'] : $_POST['txtEnglish']);
        $inputArray2['country_language_code'] = 2;

        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['country_id'] = $_POST['id'];
            $inputArray2['country_id'] = $_POST['id'];
            unset($inputArray['country_created_date']);
            unset($inputArray2['country_created_date']);
        }

        $inputArray = $this->security->xss_clean($inputArray);
        $inputArray2 = $this->security->xss_clean($inputArray2);

        $result = $this->M_admin->saveMasterTable($inputArray, $inputArray2, 'country_id', 'country_language_code', 'country');
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function deleteCountry()
    {
        $id = $_POST['id'];
        echo $this->M_admin->deleteCountry($id);
    }

    public function cityList()
    {

        $data["citylist"] = $this->M_admin->getCitiesByAjax();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/city_list", $data);
        $this->load->view("admin/footer");
    }

    public function listCityAjax()
    {

        $searchKey = $_POST['searchKey'];
        $pageNo = $_POST['page'];

        $this->load->library('pagination');
        $additional = $_POST;

        $data = array();
        $limit_per_page = 3;

        $start_index = ($this->uri->segment(2) > 0 ? ($this->uri->segment(2) - 1) * $limit_per_page : 0);
        //$start_index                =   $start_index*
        $records = $this->M_admin->getCitiesByAjaxTotal($additional);
        $total_records = $records->count;

        if ($total_records > 0) {
            // get current page records
            $data["citylist"] = $this->M_admin->getCitiesByAjax($limit_per_page, $start_index, $additional);
            $config['base_url'] = base_url() . '/country_list_ajax/';
            $config['total_rows'] = $total_records;
            $config['per_page'] = $limit_per_page;
            // $config["uri_segment"]      =   2;

            // custom paging configuration

            $config['use_page_numbers'] = true;
            $config['reuse_query_string'] = true;

            $config['full_tag_open'] = '<ul class="pagination">';
            $config['full_tag_close'] = '</ul>';

            //$config['first_link']         =   'First Page';
            $config['first_tag_open'] = '<li class="page-link">';
            $config['first_tag_close'] = '</li>';

            //$config['last_link']          =   'Last Page';
            $config['last_tag_open'] = '<li class="page-link">';
            $config['last_tag_close'] = '</li>';

            $config['next_link'] = '&gt;';
            $config['next_tag_open'] = '<li class="page-link">';
            $config['next_tag_close'] = '</li>';

            $config['prev_link'] = '&lt;';
            $config['prev_tag_open'] = '<li class="page-link">';
            $config['prev_tag_close'] = '</li>';

            $config['cur_tag_open'] = '<li class="active page-item"> <a class="page-link" href="javascript:void(0);">';
            $config['cur_tag_close'] = '</a></li>';

            $config['num_tag_open'] = '<li class="page-link">';
            $config['num_tag_close'] = '</li>';
            $config["num_links"] = 2;

            $this->pagination->initialize($config);

            // build paging links
            $data["links"] = $this->pagination->create_links();
        }

        $this->load->view('admin/city_list_ajax.php', $data);
    }

    public function testingDataTable()
    {
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view('admin/data_table.php');
        $this->load->view("admin/footer");
    }

    public function addEditCity()
    {
        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $data["country_list"] = $this->M_admin->getCountriesCondition($condition);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_city", $data);
        $this->load->view("admin/footer");
    }

    public function saveCity()
    {

        $data = array();

        $this->form_validation->set_rules('txtEnglish', 'City Name English', 'trim|required|max_length[100]');
        $this->form_validation->set_rules('txtArabic', 'City Name Arabic', 'trim|required|max_length[100]');
        $this->form_validation->set_rules('txtCountry', 'Country', 'trim|required');
        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txtEnglish' => form_error('txtEnglish'),
                'txtArabic' => form_error('txtArabic'),
                'txtCountry' => form_error('txtCountry'),
            );
            echo json_encode($data);
            exit();
        }

        $inputArray['city_name'] = $_POST['txtEnglish'];
        $inputArray['city_language_code'] = 1;
        $inputArray['city_country_id'] = $_POST['txtCountry'];
        $inputArray['city_status'] = $_POST['txtStatus'];
        $inputArray['city_created_date'] = gmdate("Y-m-d H:i:s");
        $inputArray2 = $inputArray;
        $inputArray2['city_name'] = ($_POST['txtArabic'] != "" ? $_POST['txtArabic'] : $_POST['txtEnglish']);
        $inputArray2['city_language_code'] = 2;

        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['city_id'] = $_POST['id'];
            $inputArray2['city_id'] = $_POST['id'];
            unset($inputArray['city_created_date']);
            unset($inputArray2['city_created_date']);
        }

        $inputArray = $this->security->xss_clean($inputArray);
        $inputArray2 = $this->security->xss_clean($inputArray2);

        $result = $this->M_admin->saveMasterTable($inputArray, $inputArray2, 'city_id', 'city_language_code', 'city');
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function deleteCity()
    {
        $id = $_POST['id'];
        echo $this->M_admin->deleteCity($id);
    }

    public function listPropertyTypes()
    {
        $data['property_types'] = $this->M_admin->getPropertyTypes(['status' => 1]);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ["segment" => "property_type_list"]);
        $this->load->view("admin/property_types", $data);
        $this->load->view("admin/footer");
    }

    public function addEditPropertyType( $encrypted_id=NULL )
    {
        $mode = '';
        $id   = '';
        $name = '';
        $name_arabic = '';

        if (! empty($encrypted_id) ) {
            $id = decryptor($encrypted_id);
            if ( $id > 0 ) {
                $mode = 'edit';
                $property_types = $this->M_admin->getPropertyTypes(['pk_id' => $id]);
                if ( empty($property_types) ) {
                    show_404();
                }
                $name = $property_types[0]->property_types;
                $name_arabic = $property_types[0]->arr_property_types;
            } else {
                show_404();
            }
        } else {
            $mode = 'add';
        }        

        $data = compact('mode', 'id', 'name', 'name_arabic');
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ["segment" => "property_type_list"]);
        $this->load->view("admin/add_edit_property_type", $data);
        $this->load->view("admin/footer");
    }

    public function savePropertyType()
    {
        $data = array();

        $this->form_validation->set_rules('name', 'Name English', 'trim|required');
        $this->form_validation->set_rules('name_arabic', 'Name Arabic', 'trim|required');
        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'name' => form_error('name'),
                'name_arabic' => form_error('name_arabic'),
            );
            echo json_encode($data);
            exit();
        }

        $pk_id = (int) $this->input->post('id', true);
        $property_types = $this->input->post('name', true);
        $arr_property_types = $this->input->post('name_arabic', true);

        $db_data = compact('pk_id', 'property_types', 'arr_property_types');
        $status = $this->M_admin->savePropertyType($db_data);
        $data['status'] = (int) $status;
        echo json_encode($data);
    }

    public function deletePropertyType()
    {
        $id = (int) $this->input->post('id', true);
        echo $this->M_admin->deletePropertyType($id);
    }

    public function listContractorTypes()
    {
        $data['contractor_types'] = $this->M_admin->getContractorTypes(['contractor_type_status' => 1]);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ["segment" => "contractor_type_list"]);
        $this->load->view("admin/contractor_types", $data);
        $this->load->view("admin/footer");
    }

    public function addEditContractorType( $encrypted_id=NULL )
    {
        $mode = '';
        $id   = '';
        $name = '';
        $name_arabic = '';

        if (! empty($encrypted_id) ) {
            $id = decryptor($encrypted_id);
            if ( $id > 0 ) {
                $mode = 'edit';
                $contractor = $this->M_admin->getContractorTypes(['contractor_type_id' => $id]);
                if ( empty($contractor) ) {
                    show_404();
                }
                $name = $contractor[0]->contractor_type_name;
                $name_arabic = $contractor[0]->contractor_type_name_arb;
            } else {
                show_404();
            }
        } else {
            $mode = 'add';
        }        

        $data = compact('mode', 'id', 'name', 'name_arabic');
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ["segment" => "contractor_type_list"]);
        $this->load->view("admin/add_edit_contractor_type", $data);
        $this->load->view("admin/footer");
    }

    public function saveContractorType()
    {
        $data = array();

        $this->form_validation->set_rules('name', 'Name English', 'trim|required');
        $this->form_validation->set_rules('name_arabic', 'Name Arabic', 'trim|required');
        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'name' => form_error('name'),
                'name_arabic' => form_error('name_arabic'),
            );
            echo json_encode($data);
            exit();
        }

        $contractor_type_id = (int) $this->input->post('id', true);
        $contractor_type_name = $this->input->post('name', true);
        $contractor_type_name_arb = $this->input->post('name_arabic', true);

        $db_data = compact('contractor_type_id', 'contractor_type_name', 'contractor_type_name_arb');
        $status = $this->M_admin->saveContractorType($db_data);
        $data['status'] = (int) $status;
        echo json_encode($data);
    }

    public function deleteContractorType()
    {
        $id = (int) $this->input->post('id', true);
        echo $this->M_admin->deleteContractorType($id);
    }

    public function privacy_policy_list()
    {

        $condition = array("user_type" => "D");
        $data["data_list"] = $this->M_admin->get_privacy_policies();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/privacy_policy_list", $data);
        $this->load->view("admin/footer");
    }

    public function add_edit_privacy_policy()
    {

        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);

        $data = array();

        $data["article_type"] = $this->M_admin->getArticleTypes();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_privacy_policy", $data);
        $this->load->view("admin/footer");
    }

    public function save_privacy_policy()
    {

        $this->form_validation->set_rules('txt_title_english', 'Title English', 'trim|required');
        $this->form_validation->set_rules('txt_title_arabic', 'Title English', 'trim|required');
        $this->form_validation->set_rules('txt_descp_english', 'Article English', 'trim|required|custom_minlength_check');
        $this->form_validation->set_rules('txt_descp_arabic', 'Article Arabic', 'trim|required|custom_minlength_check');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_title_english' => form_error('txt_title_english'),
                'txt_title_arabic' => form_error('txt_title_arabic'),
                'txt_descp_english' => form_error('txt_descp_english'),
                'txt_descp_arabic' => form_error('txt_descp_arabic'),
            );
            echo json_encode($data);
            exit();
        }

        $_POST = $this->security->xss_clean($_POST);

        $id = (int) $this->input->post("id", true);

        $i_data["pp_title"] = $_POST["txt_title_english"];
        $i_data["pp_description"] = $_POST["txt_descp_english"];
        $i_data["pp_title_arabic"] = $_POST["txt_title_arabic"];
        $i_data["pp_description_arabic"] = $_POST["txt_descp_arabic"];
        $i_data["status"] = $_POST["txtStatus"];
        $i_data["updated_at"] = gmdate("Y-m-d H:i:s");
        $policy['meta_title'] = $_POST['txt_meta_title'];
        $policy['meta_keyword'] = $_POST['txt_meta_keyword'];
        $policy['meta_description'] = $_POST['txt_meta_description'];

        if ($id > 0) {
            $result = $this->M_admin->update_privacy_policy($i_data, ["privacy_policy_id" => $id]);
            $this->M_admin->update_privacy_policy_meta_data($policy);
        } else {
            $i_data['meta_title'] = $_POST['txt_meta_title'];
            $i_data['meta_keyword'] = $_POST['txt_meta_keyword'];
            $i_data['meta_description'] = $_POST['txt_meta_description'];
            $result = $this->M_admin->create_privacy_policy($i_data);
            $result = ($result > 0) ? 1 : 0;
        }

        $data['status'] = $result;
        echo json_encode($data);
    }

    public function delete_privacy_policy()
    {
        $id = $_POST['id'];
        echo $this->M_admin->delete_privacy_policy($id);
    }



    public function terms_and_conditions_list()
    {
        $condition = array("user_type" => "D");
        $data["data_list"] = $this->M_admin->get_terms_and_conditions_list();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/terms_and_conditions_list", $data);
        $this->load->view("admin/footer");
    }

    public function add_edit_terms_and_conditions()
    {
        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);

        $data = array();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_terms_and_conditions", $data);
        $this->load->view("admin/footer");
    }

    public function save_terms_and_conditions()
    {
        $this->form_validation->set_rules('txt_title_english', 'Title English', 'trim|required');
        $this->form_validation->set_rules('txt_title_arabic', 'Title English', 'trim|required');
        $this->form_validation->set_rules('txt_descp_english', 'Article English', 'trim|required|custom_minlength_check');
        $this->form_validation->set_rules('txt_descp_arabic', 'Article Arabic', 'trim|required|custom_minlength_check');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_title_english' => form_error('txt_title_english'),
                'txt_title_arabic' => form_error('txt_title_arabic'),
                'txt_descp_english' => form_error('txt_descp_english'),
                'txt_descp_arabic' => form_error('txt_descp_arabic'),
            );
            echo json_encode($data);
            exit();
        }

        $_POST = $this->security->xss_clean($_POST);

        $id = (int) $this->input->post("id", true);

        $i_data["tc_title"] = $_POST["txt_title_english"];
        $i_data["tc_description"] = $_POST["txt_descp_english"];
        $i_data["tc_title_arabic"] = $_POST["txt_title_arabic"];
        $i_data["tc_description_arabic"] = $_POST["txt_descp_arabic"];
        $i_data["status"] = $_POST["txtStatus"];
        $i_data["updated_at"] = gmdate("Y-m-d H:i:s");

        if ($id > 0) {
            $result = $this->M_admin->update_terms_and_conditions($i_data, ["tc_id" => $id]);
        } else {
            $result = $this->M_admin->create_terms_and_conditions($i_data);
            $result = ($result > 0) ? 1 : 0;
        }

        $data['status'] = $result;
        echo json_encode($data);
    }

    public function delete_terms_and_conditions()
    {
        $id = $_POST['id'];
        echo $this->M_admin->delete_terms_and_conditions($id);
    }


    public function faq_list()
    {
        $condition = array("user_type" => "D");
        $data["data_list"] = $this->M_admin->get_faq_list();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/faq_list", $data);
        $this->load->view("admin/footer");
    }

    public function add_edit_faq()
    {
        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);

        $data = array();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_faq", $data);
        $this->load->view("admin/footer");
    }

    public function save_faq()
    {
        $this->form_validation->set_rules('txt_title_english', 'Title English', 'trim|required');
        $this->form_validation->set_rules('txt_title_arabic', 'Title English', 'trim|required');
        $this->form_validation->set_rules('txt_descp_english', 'Article English', 'trim|required|custom_minlength_check');
        $this->form_validation->set_rules('txt_descp_arabic', 'Article Arabic', 'trim|required|custom_minlength_check');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_title_english' => form_error('txt_title_english'),
                'txt_title_arabic' => form_error('txt_title_arabic'),
                'txt_descp_english' => form_error('txt_descp_english'),
                'txt_descp_arabic' => form_error('txt_descp_arabic'),
            );
            echo json_encode($data);
            exit();
        }

        $_POST = $this->security->xss_clean($_POST);

        $id = (int) $this->input->post("id", true);

        $i_data["faq_title"] = $_POST["txt_title_english"];
        $i_data["faq_description"] = $_POST["txt_descp_english"];
        $i_data["faq_title_arabic"] = $_POST["txt_title_arabic"];
        $i_data["faq_description_arabic"] = $_POST["txt_descp_arabic"];
        $i_data["status"] = $_POST["txtStatus"];
        $i_data["updated_at"] = gmdate("Y-m-d H:i:s");
        $meta['meta_title'] = $_POST['txt_meta_title'];
        $meta['meta_keyword'] = $_POST['txt_meta_keyword'];
        $meta['meta_description'] = $_POST['txt_meta_description'];

        if ($id > 0) {
            $result = $this->M_admin->update_faq($i_data, ["faq_id" => $id]);
            $this->M_admin->update_faq_meta_data($meta);
        } else {
            $i_data['meta_title'] = $_POST['txt_meta_title'];
            $i_data['meta_keyword'] = $_POST['txt_meta_keyword'];
            $i_data['meta_description'] = $_POST['txt_meta_description'];
            $result = $this->M_admin->create_faq($i_data);
            $result = ($result > 0) ? 1 : 0;
        }

        $data['status'] = $result;
        echo json_encode($data);
    }

    public function delete_faq()
    {
        $id = $_POST['id'];
        echo $this->M_admin->delete_faq($id);
    }

    public function socialCategoryList()
    {
        $condition = array();
        $data["category_list"] = $this->M_admin->getSocialCategoryList();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/social_category_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditSocialCategory()
    {
        $id = (int) $this->M_product->decryptId($this->uri->segment(2));

        $data['scat_eng'] = "";
        $data['scat_arabic'] = "";

        $data['id'] = 0;

        if ($id > 0) {
            $data['heading'] = "Edit Social ";

            $category_row = $this->M_admin->getSocialCategory($id);
            $arabic_row = $this->M_admin->getSocialCategoryLang($id, 2);

            if ($category_row) {
                $data['scat_eng'] = $category_row->scategory_name;
                $data['id'] = $id;
            }

            if ($arabic_row) {
                $data['scat_arabic'] = $arabic_row->scategory_lang_text;
            }
        } else {
            $data['heading'] = "Add New Social ";
        }

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_social_category", $data);
        $this->load->view("admin/footer");
    }

    public function saveSocialCategory()
    {
        $this->form_validation->set_rules('txtEnglish', 'Category Name English', 'trim|required|max_length[100]');
        $this->form_validation->set_rules('txtArabic', 'Category Name Arabic', 'trim|required|max_length[100]');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txtEnglish' => form_error('txtEnglish'),
                'txtArabic' => form_error('txtArabic'),
            );

            echo json_encode($data);
            exit();
        } else {
            $id = (int) $this->input->post("id", true);

            $category_row = $this->M_admin->getSocialCategory($id);

            $this->db->trans_start();

            if ($id <= 0) {
                $iData["scategory_name"] = $this->input->post("txtEnglish", true);
                $iData["scategory_created_date"] = gmdate("Y-m-d H:i:s");

                $scategory_id = $this->M_admin->createSocialCategory($iData);

                $fdata["scategory_lang_text"] = $this->input->post("txtArabic", true);
                $fdata["scategory_id"] = $scategory_id;
                $fdata["lang_code"] = 2;

                $this->M_admin->createSocialCategoryLangs($fdata);
            } else {
                $iData["scategory_name"] = $this->input->post("txtEnglish", true);

                $this->M_admin->updateSocialCategory($iData, $id);
                $this->M_admin->updateSocialCategoryLangs($id, 2, $this->input->post("txtArabic", true));
            }

            $this->db->trans_complete();

            if ($this->db->trans_status() === true) {
                $data['status'] = 1;

                $FBDatabase = get_firebase_refrence();

                if ($id > 0 && $category_row) {
                    $FBDatabase->getReference('SocialCategories/' . $category_row->scategory_fb_key)
                        ->update([
                            "engCategoryName" => $this->input->post("txtEnglish", true),
                            "arbCategoryName" => $this->input->post("txtArabic", true),
                        ]);
                } else {
                    $scategory_refrence = $FBDatabase->getReference('SocialCategories')
                        ->push([
                            "engCategoryName" => $this->input->post("txtEnglish", true),
                            "arbCategoryName" => $this->input->post("txtArabic", true),
                            "sCategoryID" => $scategory_id,
                        ]);

                    $scat_push_key = $scategory_refrence->getKey();
                    $this->M_admin->updateSocialCategory(array("scategory_fb_key" => $scat_push_key), $scategory_id);
                }
            } else {
                $data['status'] = 0;
            }

            echo json_encode($data);
        }
    }

    public function deleteSocialCategory()
    {

        $id = (int) $this->input->post("id", true);
        $category_row = $this->M_admin->getSocialCategory($id);

        $scount = $this->M_admin->getSocialCategoryPostContentCount($id);

        if ($scount <= 0) {
            echo $res = $this->M_admin->deleteSocialCategory($id);

            if ($res > 0) {
                $FBDatabase = get_firebase_refrence();
                $FBDatabase->getReference('SocialCategories/' . $category_row->scategory_fb_key)->remove();
            }
        } else {
            echo "0";
        }
    }

    public function changeSocialCategoryStatus()
    {
        $id = (int) $this->input->post("id", true);
        echo $result = $this->M_admin->updateSocialCategory(array("scategory_status" => (int) $this->input->post("status", true)), $id);
    }

    public function categoryList()
    {
        $condition = array();
        $data["category_list"] = $this->M_admin->getCategoryWithParent();
        $data["main_category_list"] = $this->M_admin->getParentCategories();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/category_list", $data);
        $this->load->view("admin/footer");
    }
    public function addEditCategory()
    {
        // Super Admin can addd/edit categories
        if ($this->session->userdata('admin_designation') != 1) {
            redirect(site_url('category_list'), 'refresh');
        }

        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);

        $parent_categories = $this->M_admin->getParentCategories($language);
        $parent_categories = array_column($parent_categories, 'category_name', 'category_id');
        asort($parent_categories);

        $categories_with_parent  = $this->M_admin->getCategoryWithParent();
        $sub_categories = [];
        foreach ($categories_with_parent as $row) {
            $sub_categories[$row->category_parent_id][$row->category_id] = $row->category_name;
        }

        $id = $this->M_product->decryptId($this->uri->segment(2));

        $attribute_map = [];//$this->M_admin->getAttributeCategoryMap($id);
        // $attribute_map = array_column($attribute_map, 'attribute_id');
        $data = array(
            'id' => $id,
            'category_list' => $parent_categories,
            'sub_category_list' => $sub_categories,
            'product_attribute_list' => [],//$this->M_product->getAttributes(['1' => '1']),
            'attribute_map' => $attribute_map,
            // 'category_attributes' => $this->M_admin->getCategoryAttributes()
        );

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_category", $data);
        $this->load->view("admin/footer");
    }

    public function is_unique_category_uid( $uid )
    {
        if (! empty($uid) ) {
            $condition = array();
            $id = $this->input->post('id', true);
            if (! empty($id) ) {
                $condition = ['category_id !=' => $id];
            }
            $category = $this->M_admin->getCategoryByUID($uid, $condition);
            if ( $category ) {
                $this->form_validation->set_message('is_unique_category_uid', 'The {field} field must contain a unique value. A category already exists with this UID.');
                return FALSE;
            }
        }
        return TRUE;
    }

    public function saveCategory()
    {
        $data = array();
        $this->load->library('upload');

        if ($_FILES["txtFile"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFile"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'category/';
            $config2['allowed_types'] = 'gif|jpg|png|jpeg|svg';
            // $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('txtFile')) {
                //die("file upload failed");
                $data['status'] = 0;
                $data['errors'] = array(
                    'txtFile' => "File upload failed due to " . $this->upload->display_errors(),
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['category_icon'] = $config2['file_name'];
            }
        }

        //app icon image
        if ($_FILES["txtFile2"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFile2"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'category/';
            $config2['allowed_types'] = 'gif|jpg|png|jpeg|svg';
            // $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('txtFile2')) {
                //die("file upload failed");
                $data['status'] = 0;
                $data['errors'] = array(
                    'txtFile2' => "File upload failed",
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['category_app_icon'] = $config2['file_name'];
            }
        }

        if ($_FILES["txtFileBanner"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFileBanner"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'category/';
            $config2['allowed_types'] = 'gif|jpg|png|pdf|svg';
            // $config2['max_size']             =  10000;
            //  $config2['max_width']            =  2;
            // $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('txtFileBanner')) {
                //die("file upload failed");
                $data['status'] = 0;
                $data['errors'] = array(
                    'txtFileBanner' => "File upload failed",
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['category_banner_image'] = $config2['file_name'];
            }
        }

        $this->form_validation->set_rules('txtEnglish', 'Category Name English', 'trim|required|max_length[100]');
        $this->form_validation->set_rules('txtArabic', 'Category Name Arabic', 'trim|required|max_length[100]');
        $this->form_validation->set_rules('txtUniqueId', 'Category UID', 'trim|required|max_length[30]|callback_is_unique_category_uid');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txtEnglish' => form_error('txtEnglish'),
                'txtArabic' => form_error('txtArabic'),
                'txtUniqueId' => form_error('txtUniqueId'),
            );
            echo json_encode($data);
            exit();
        }
        $allow_product_listing = $this->input->post('txtAllowProductListing');
        $measurement_required = $this->input->post('txtMeasurementRequired');

        $_POST = $this->security->xss_clean($_POST);

        $inputArray['category_uid'] = $_POST['txtUniqueId'];
        $inputArray['category_name'] = $_POST['txtEnglish'];
        $inputArray['category_language_code'] = 1;
        $inputArray['category_parent_id'] = $_POST['txtParent'];
        $inputArray['allow_product_listing'] = ($allow_product_listing == 1) ? 1 : 0;
        $inputArray['measurement_required']  = ($measurement_required == 1) ? 1 : 0;
        $inputArray['category_product_attributes'] = $_POST['txtProductAttribute'];

        $inputArray['category_status'] = $_POST['txtStatus'];
        $inputArray['category_hot'] = 0; //$_POST['txtHot'];
        $inputArray['category_created_date'] = gmdate("Y-m-d H:i:s");
        $inputArray['category_commission'] = 0; //$_POST['txt_commission'];

        $inputArray['meta_title']                =    $_POST['txt_meta_title'] ;
        $inputArray['meta_keyword']              =    $_POST['txt_meta_keyword'] ;
        $inputArray['meta_description']          =    $_POST['txt_meta_description'] ;
        $inputArray['category_app_action']       =    $_POST['txtAppAction'] ;

        $inputArray2['meta_title']                =    $_POST['txt_meta_title'] ;
        $inputArray2['meta_keyword']              =    $_POST['txt_meta_keyword'] ;
        $inputArray2['meta_description']          =    $_POST['txt_meta_description'] ;

        $inputArray2 = $inputArray;
        $inputArray2['category_name'] = ($_POST['txtArabic'] != "" ? $_POST['txtArabic'] : $_POST['txtEnglish']);
        $inputArray2['category_language_code'] = 2;

        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['category_id'] = $_POST['id'];
            $inputArray2['category_id'] = $_POST['id'];

            $inputArray['category_updated_date'] = gmdate("Y-m-d H:i:s");
            $inputArray2['category_updated_date'] = gmdate("Y-m-d H:i:s");
            unset($inputArray['category_created_date']);
            unset($inputArray2['category_created_date']);
        }

        $inputArray = $this->security->xss_clean($inputArray);
        $inputArray2 = $this->security->xss_clean($inputArray2);

        $result = $this->M_admin->saveMasterTable($inputArray, $inputArray2, 'category_id', 'category_language_code', 'category');

        $data['status'] = $result;
        echo json_encode($data);
    }

    public function deleteCategory()
    {
        $id = $_POST['id'];
        echo $this->M_admin->deleteCategory($id);
    }

    public function userList()
    {
        $conditions = "(user_type='U' OR user_type='C')";
        $data["user_list"] = $this->M_admin->getUsersList($conditions);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/user_list", $data);
        $this->load->view("admin/footer");
    }

    public function get_customer_list() {

        require_once APPPATH.'third_party/ozdemir-datatable/vendor/autoload.php';
        $datatable = new Datatables(new CodeigniterAdapter);

        $permission = $this->M_admin->getAdminPermissionsByMenu((int)  $this->session->userdata('admin_id'), 3);

        $search_condition = "";
        $search_condition="and user_type='U' OR user_type='C'";

        $search_from_date       = $this->input->post("f_from_date", true);
        $search_to_date         = $this->input->post("f_to_date", true);

        if(strlen($search_from_date) > 5 && strlen($search_to_date) > 5 ) {
            $search_condition .=" and user_created_date::date >= '". date("Y-m-d", strtotime($search_from_date)) ."' and  user_created_date::date <= '". date("Y-m-d", strtotime($search_to_date)) ."'";
        }
        else if(strlen($search_from_date) > 5  ) {
            $search_condition .=" and user_created_date::date = '". date("Y-m-d", strtotime($search_from_date)) ."'";
		}

        $this->M_admin->get_customer_list($datatable, $search_condition);

        $datatable->add("mobile_no", function ($data) {
            $mobile_no = $data['phone_number'];
            if (! empty($mobile_no) ) {
                if (! empty($data['dial_code']) ) {
                    $mobile_no .= "{$data['dial_code']}-{$mobile_no}";
                }
            }
            return (string)$data['phone_number'];
        });

        $datatable->edit("created_date", function ($data) {
            return date("d, F Y",  strtotime($data['created_date']));
        });

        // $datatable->edit("type", function ($data) {
        //     if($data['type']=="U"){
        //         return 'Customer';
        //     }
        //     else{
        //         return 'Company';
        //     }
        // });

        $datatable->edit("status", function($data) use ($permission) {

            $checkbox_disabled = "";


            if ($permission->perm_edit != 1)
                $checkbox_disabled = "disabled";
            else
                $checkbox_disabled = "";

                $checked_status = $data['status'] == 1 ? "checked" : "";

            return '<label class="switch">
                        <input type="checkbox"
                            '.$checked_status.'
                            for="'.$data['id'].'" class="swichCheck"
                            '.$checkbox_disabled.'>
                        <span class="slider round"></span>
                    </label>';
        });

        $datatable->add('action', function($data) use ($permission) {
            $edit_action = '';
            if ($permission->perm_edit == 1) {
                $edit_action = '<a class="dropdown-item edit" href="'.base_url() . 'update_user/' . $this->M_product->encryptId($data["id"]).'"><i class="fa fa-pencil" i></i> Edit</a>';
            }

            $delete_button = '';
            if ($permission->perm_delete == 1) {
                $delete_button = '<a class="dropdown-item removeThis" href="#" data-toggle="modal" data-target="#confirm-modal" for="'.$data['id'].'"><i class="fa fa-trash-o"></i> Delete</a>';
            }

            $view_button = '';
            $order_button = '';
            $measurement_button = '';
            if ($permission->perm_view == 1) {
                $view_button = '<a class="dropdown-item detailView" href="#" data-toggle="modal" data-target="#modal-media_details" for="'.$data['id'].'"><i class="fa fa-eye"></i> View</a>';
                $order_button = '<a class="dropdown-item" href="'.base_url() . 'user_orders/' . $this->M_product->encryptId($data["id"]).'">Orders</a>';
                $measurement_button = '<a class="dropdown-item" href="'.base_url() . 'user_measurements/' . $this->M_product->encryptId($data["id"]).'">Measurement Points</a>';
            }

            /*
            if ($permission->perm_view == 1) {
                $action .= '<a style="margin-left:12px;" class="view" href="'.base_url() . 'cash_point_user_report/' . $this->M_product->encryptId($data['id']).'">
                                <i class="fa fa-money" id="detailView" for="'.$data['id'].'"></i>
                            </a>';
            }
            */

            $action .= <<<ACTION
            <div class="btn-group">
                <button type="button" class="btn btn-secondary btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    Action
                </button>
                <div class="dropdown-menu">
                    {$order_button}
                    {$measurement_button}
                    <div class="dropdown-divider"></div>
                    {$view_button}
                    {$edit_action}
                    {$delete_button}
                </div>
            </div>
ACTION;

			return $action;

        });

        $this->output->set_output( $datatable->generate() );
    }

    /*public function update_invite_code()
    {
        $query = $this->db->from('user_table')
                          ->where_in('user_type', ['U', 'C'])
                          ->get();
        $users = $query->result();

        foreach ($users as $user) {
            $custom_id = $this->M_admin->getUserCustomId();
            if (! empty($custom_id) ) {
                $status = $this->M_admin->updateCustomId($user->user_id, $custom_id);
            }
        }
    }*/

    public function addEditUser()
    {
        $adminUserid = $this->session->userdata('admin_id');
        $menuId = 3;
        $permission = $this->M_admin->getAdminPermissionsByMenu($adminUserid, $menuId);

        if ($permission->perm_add != 1) {
            redirect(base_url() . "admin");
        }


        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $data["country_list"] = $this->M_admin->getCountriesCondition($condition);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_user", $data);
        $this->load->view("admin/footer");
    }

    public function does_phone_exists( $phone_number )
    {
        if (! empty($phone_number) ) {
            $id             = (int) $this->input->post('id', true);
            $dial_code      = trim($this->input->post("txt_dialcode", true));
            $phone_number   = trim($this->input->post("txt_phone", true));

            $condition      = ["dial_code" => $dial_code, "phone_number" => $phone_number, "phone_verified" => 1];
            if ( $id > 0 ) {
                $condition['user_id !='] = $id;
            }
            $user_phone_row = $this->M_admin->get_user($condition);
            if ( $user_phone_row ) {
                $this->form_validation->set_rules('does_phone_exists', 'Phone number already registered.');
                return FALSE;
            }
        }

        return TRUE;
    }

    public function saveUser()
    {
        $data = array();

        $id = $this->input->post('id', true);

        //$this->form_validation->set_rules('txt_company', 'Company', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('txt_first_name', 'First Name', 'trim|required|max_length[100]|xss_clean');

        $this->form_validation->set_rules('txt_email', 'Email Address', 'required|valid_email|max_length[100]');
        if (! isset($id) ) {
            $this->form_validation->set_rules('txt_password', 'Password', 'trim|required|min_length[8]|max_length[20]|valid_password');
            if (empty($_FILES['txt_image']['name'])) {
                $this->form_validation->set_rules('txt_image', 'Profile Picture', 'trim|required');
            }
        } else {
            $pw = $this->input->post('txt_password', true);
            if ( $pw == 'n0p@ssword' ) {
                $_POST['txt_password'] = '';
            }
            if ( !empty($pw) && ($pw != 'n0p@ssword') ) {
                $this->form_validation->set_rules('txt_password', 'Password', 'min_length[8]|max_length[20]|valid_password');
            }
        }
        $this->form_validation->set_rules('select_country', 'Country', 'trim|required');
        $this->form_validation->set_rules('select_city', 'City', 'trim|required');
        $this->form_validation->set_rules('txt_phone', 'Phone', 'trim|required|numeric|min_length[5]|max_length[10]|xss_clean|callback_does_phone_exists');
        $this->form_validation->set_rules('user_type', 'User Type', 'trim|required');

        $user_type = $this->input->post('user_type', true);
        if ( $user_type == 'A' || $user_type == 'C' ) {
            $this->form_validation->set_rules('txt_trade_license', 'Trade License', 'trim|required|max_length[100]');
        }

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_first_name'       => form_error('txt_first_name'),
                'txt_email'         => form_error('txt_email'),
                'txt_password'      => form_error('txt_password'),
                'select_country'    => form_error('select_country'),
                'select_city'       => form_error('select_city'),
                'user_type'         => form_error('user_type'),
                'txt_image'         => form_error('txt_image'),
                'txt_trade_license' => form_error('txt_trade_license'),
            );
            echo json_encode($data);
            exit();
        }

        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);

            $config1['upload_path']          =  $this->config->item('upload_path').$this->config->item('user_profile_image_upload_dir');
            $config1['allowed_types']        =  'gif|jpg|png|jpeg';
            $config1['max_size']             =  1000;
            $config1['max_width']            =  600;
            $config1['max_height']           =  600;
            $config1['file_name']            =  $randomNo.".".$file_ext;

            $this->load->library('upload', $config1);
            $this->upload->initialize($config1);

            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 {
                $_POST['image'] = $config1['file_name'];
            }
        }

        $_POST = $this->security->xss_clean($_POST);

        $_POST['txt_company'] = trim($_POST['txt_first_name'].' '.$_POST['txt_last_name']);
        
        if (count($_POST) > 0) {
            /**
             * There is no need to verify phone number, since it is added by Admin.
             * Otherwise the vendor will be blocked from being login using mobile app
             * because of OTP verification.
             */
            $_POST['phone_verified'] = 1;
            if ( $id > 0 ) {
                $result = $this->M_admin->updateCustomerUser($_POST);
            } else {
                $result = $this->M_admin->saveCustomerUser($_POST);
            }
        } else {
            $result = 0;
        }
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function saveUserOld()
    {
        $data = array();

        $this->form_validation->set_rules('txt_first_name', 'First name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_last_name', 'Last name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_email', 'Email Address', 'required|valid_email|max_length[100]');
        $this->form_validation->set_rules('select_country', 'Country', 'trim|required');
        $this->form_validation->set_rules('txt_password', 'Password', 'trim|required|min_length[8]|max_length[20]|valid_password');
        // $this->form_validation->set_rules('select_country2[]', 'Shipping Country', 'trim|required');
        $this->form_validation->set_rules('select_city[]', 'City', 'trim|required');
        $this->form_validation->set_rules('txt_Phone[]', 'Phone', 'trim|required|numeric|min_length[5]|max_length[10]|xss_clean');
        $this->form_validation->set_rules('txt_location[]', 'Location', 'trim|required|max_length[300]');
        $this->form_validation->set_rules('txt_street[]', 'Street Name', 'trim|required|max_length[100]|check_inavlid_char');
        $this->form_validation->set_rules('txt_building[]', 'Building Number', 'trim|required|max_length[100]|check_inavlid_char');
        $this->form_validation->set_rules('txt_land_mark[]', 'Land Mark', 'trim|required|max_length[300]|check_inavlid_char');
        $this->form_validation->set_rules('select_location_type[]', 'Location type', 'trim|required');
        // $this->form_validation->set_rules('txt_user_id', 'User Id', 'trim|required|max_length[50]|min_length[8]|xss_clean|alpha_numeric');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_first_name' => form_error('txt_first_name'),
                'txt_last_name' => form_error('txt_last_name'),
                'txt_email' => form_error('txt_email'),
                'select_country' => form_error('select_country'),
                'txt_password' => form_error('txt_password'),
                'select_country2[]' => form_error('select_country2[]'),
                'select_city[]' => form_error('select_city[]'),
                'txt_Phone[]' => form_error('txt_Phone[]'),
                'txt_location[]' => form_error('txt_location[]'),
                'txt_street[]' => form_error('txt_street[]'),
                'txt_building[]' => form_error('txt_building[]'),
                'txt_land_mark[]' => form_error('txt_land_mark[]'),
                'select_location_type[]' => form_error('select_location_type[]'),
                'txt_user_id' => form_error('txt_user_id'),
            );
            echo json_encode($data);
            exit();
        }

        $_POST = $this->security->xss_clean($_POST);
        if (count($_POST) > 0) {
            /**
             * There is no need to verify phone number, since it is added by Admin.
             * Otherwise the vendor will be blocked from being login using mobile app
             * because of OTP verification.
             */
            $_POST['phone_verified'] = 1;
            $result = $this->M_admin->saveUser($_POST);
        } else {
            $result = 0;
        }
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function deleteUserShippingAddress()
    {
        $status = 0;
        $id = $this->input->post('id', true);
        if ( $id > 0 ) {
            $status = $this->M_admin->deleteUserShippingAddressById($id);
        }

        header('Content-Type: application/json');
        echo json_encode(array('status'=>$status));
        exit;
    }

    public function loadShipingForm()
    {

        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('city_language_code' => $language, 'city_status' => 1, 'city_country_id' => $_POST['countryId']);
        $data["city_list"] = $this->M_admin->getCitiesCondition($condition);

        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $data["country_list"] = $this->M_admin->getCountriesCondition($condition);

        $data["form_count"] = $_POST['addressCount'];
        $this->load->view("admin/add_edit_shipping", $data);
    }

    public function loadCityDropDown()
    {
        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('city_language_code' => $language, 'city_status' => 1, 'city_country_id' => $_POST['countryId']);
        $cityList = $this->M_admin->getCitiesCondition($condition);

        if (isset($cityList) && count($cityList) > 0) { ?>
            <option value="" >Select</option>

            <?php
            foreach ($cityList as $rows) { ?>
                <option value="<?php echo $rows->city_id; ?>" ><?php echo $rows->city_name; ?></option>
                <?php
            }
        }
    }

    public function editUser()
    {

        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $data["country_list"] = $this->M_admin->getCountriesCondition($condition);

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/update_edit_user", $data);
        $this->load->view("admin/footer");
    }

   public function updateUser()
    {

        $data = array();

        $this->form_validation->set_rules('txt_first_name', 'First name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_last_name', 'Last name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_email', 'Email Address', 'required|valid_email|max_length[100]');

        $this->form_validation->set_rules('select_country', 'Country', 'trim|required');
        $this->form_validation->set_rules('select_country2[]', 'Shipping Country', 'trim|required');
        $this->form_validation->set_rules('select_city[]', 'City', 'trim|required');
        $this->form_validation->set_rules('txt_Phone[]', 'Phone', 'trim|required|numeric|min_length[5]|max_length[10]|xss_clean');
        $this->form_validation->set_rules('txt_location[]', 'Location', 'trim|required|max_length[300]');
        $this->form_validation->set_rules('txt_street[]', 'Street Name', 'trim|required|max_length[100]|check_inavlid_char');
        $this->form_validation->set_rules('txt_building[]', 'Building Number', 'trim|required|max_length[100]|check_inavlid_char');
        $this->form_validation->set_rules('txt_land_mark[]', 'Land Mark', 'trim|required|max_length[300]|check_inavlid_char');
        $this->form_validation->set_rules('select_location_type[]','Location type','trim|required');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $shipping_address = form_error('select_country2[]') . form_error('select_city[]') . form_error('txt_Phone[]') . form_error('txt_location[]') . form_error('txt_street[]') . form_error('txt_building[]') . form_error('txt_land_mark[]') . form_error('select_location_type[]');
            $data['errors'] = array(
                'txt_first_name' => form_error('txt_first_name'),
                'txt_last_name' => form_error('txt_last_name'),
                'txt_email' => form_error('txt_email'),
                'select_country' => form_error('select_country'),
                'shipping_address' => $shipping_address,
            );
            echo json_encode($data);
            exit();
        }

        $_POST = $this->security->xss_clean($_POST);
        if (count($_POST) > 0) {
            $result = $this->M_admin->updateUser($_POST);
        } else {
            $result = 0;
        }
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function deleteUser()
    {
        $id = $_POST['id'];
        echo $this->M_admin->deleteUser($id);
    }

    public function userDetails()
    {
        $id = $_POST['id'];
        // $param                      =   array("user_id"=>$id);
        $records1 = $this->M_admin->getUserFulDetails($id);
       // print_r($records1);
        $data['user_deatail'] = $records1;
        $this->load->view('admin/user_detail_view', $data);
    }

    public function approveUser()
    {
        echo $result = $this->M_admin->approveUser($_POST);
    }

    public function verifySeller()
    {
        $user_id = $this->input->post('id');
        $verified_status = $this->input->post('status');

        $seller = $this->M_admin->getVendorInfo($user_id);
        $verified_count = $seller->verified_count ?? 0; 

        $updateArr = array('user_id' => $user_id, 'verified_status' => $verified_status);
        if ( $verified_status ) {
            $verified_count++;
            $updateArr['verified_count'] = $verified_count;
        }
        $update = $this->M_admin->updateSeller($updateArr, $user_id);

        //if ( $update && ($verified_status == 1)  ) {
           if ( $update && ($verified_status == 1) && ($verified_count == 1) ) {
           // echo $verified_count;
            $user = $this->M_admin->getBasicUserDeatils($user_id);

            $this->load->model('website/home_model', 'model_home');
            $app_basic_row  = $this->model_home->get_app_basics();

            $subject = "Congrats! Your account has been verified";
            $to      = $user->user_email_id;

            $email_message = $this->load->view('email_templates/verify_seller', [
                "assets" => base_url()."email_assets/",
                "user_name" => $user->user_first_name . " " . $user->user_last_name,
                "telephone" => ($app_basic_row) ? $app_basic_row->phone_no : "",
                "twitter" => ($app_basic_row) ? $app_basic_row->twitter_link : "",
                "facebook" => ($app_basic_row) ? $app_basic_row->fb_link : "",
                "instagram" => ($app_basic_row) ? $app_basic_row->insta_link : "",
                "email" => ($app_basic_row) ? $app_basic_row->email_id : "",
                "playstore" => ($app_basic_row) ? $app_basic_row->android_app_link:"",
                "appstore" => ($app_basic_row) ? $app_basic_row->ios_app_link:"",
            ], TRUE);

            $from = SITE_NOREPLY_EMAIL;

            $this->load->library("Mail_function");
            //$this->mail_function->SendEmail($email_message, $subject, $to);
        }
        echo $update;
    }

    public function userOrderList( $user_id )
    {
        if (! empty($user_id) ) {
            $user_id = $this->M_product->decryptId($user_id);

            if ( $user_id > 0 ) {
                $data['orderDetails'] = $this->M_product->getOrderListDetails($user_id);
                $this->load->view("admin/header");
                $this->load->view("admin/sidebar", ['segment' => 'user_list']);
                $this->load->view("admin/user_order_list", $data);
                $this->load->view("admin/footer");
            } else {
                show_404();
            }
        } else {
            show_404();
        }
    }

    public function userOrderSummary()
    {
        $order_id =  $this->M_product->decryptId($this->uri->segment(2));
        if ( $order_id > 0 ) {
            $orderData      = $this->M_admin->getCustomerOrderDetail($order_id);
            $orderDetails   = [];
            if ( $orderData ) {
                $orderIssues = $this->M_admin->getOrderIssuesReported($orderData->order_id);
                $reportedIssues = [];
                foreach ($orderIssues as $tmpIssue) {
                    $reportedIssues[$tmpIssue->store_id][] = $tmpIssue;
                }
                foreach ($orderData->products as $row) {
                    if ( array_key_exists($row->store_id, $orderDetails) == FALSE ) {
                        $orderDetails[$row->store_id] = [
                            'store_id' => $row->store_id,
                            'store_name' => $row->store_name,
                            'products' => [],
                            'delivery_statuses' => $this->M_admin->getDeliveryStatusTimeline($orderData->order_id, $row->product_variant_id),
                            'reported_issues' => $reportedIssues[$row->seller_id] ?? [],
                            'driver_name' => '',
                            'driver_earning' => 0,
                            'status_changed_date' => $row->status_changed_date ?? '',
                            'status_changed_user_type' => $row->status_changed_user_type ?? '',
                        ];
                        if (! empty($row->driver_id) ) {
                            $driver = $this->db->select('u.user_first_name,u.user_last_name,s.mobile_no,s.vehicle_reg_no')
                                                        ->from('user_table u')
                                                        ->join('driver_details s', 'u.user_id =s.user_id', 'inner')
                                                        ->where('u.user_id', $row->driver_id)
                                                        ->get()
                                                        ->row();
                            $orderDetails['driver_name'] = $driver->user_first_name. " ". $driver->user_last_name;
                            $orderDetails['driver_mobile'] = $driver->mobile_no;
                            $orderDetails['vehicle_no'] = $driver->vehicle_reg_no;
                            $driver_earnings = $this->M_admin->getDriverEarnings($row->driver_id, $orderData->order_id, $row->seller_id);
                            if (! empty($driver_earnings) ) {
                                $orderDetails[$row->store_id]['driver_earning'] = array_sum(array_column($driver_earnings, 'earning'));
                            }
                        }
                    }
                    $orderDetails[$row->store_id]['products'][] = $row;
                }
                foreach ($orderData->services as $row) {
                    if ( array_key_exists($row->store_id, $orderDetails) == FALSE ) {
                        $orderDetails[$row->store_id] = [
                            'store_id' => $row->store_id,
                            'store_name' => $row->store_name,
                            'products' => [],
                            'delivery_statuses' => $this->M_admin->getDeliveryStatusTimeline($orderData->order_id, $row->product_variant_id),
                            'reported_issues' => $reportedIssues[$row->seller_id] ?? [],
                            'driver_name' => '',
                            'driver_earning' => 0,
                            'status_changed_date' => $row->status_changed_date ?? '',
                            'status_changed_user_type' => $row->status_changed_user_type ?? '',
                        ];
                    }
                    $orderDetails[$row->store_id]['services'][] = $row;
                }
                $orderData->shipping_address = $this->M_admin->getCustomerShippingAddressById($orderData->shipping_address_id);
            }
            $data['orderData'] = $orderData;
            $data['orderDetails'] = $orderDetails;
            //echo '<pre>';print_r($orderDetails);die;
            $this->load->view("admin/header");
            $this->load->view("admin/sidebar", ['segment' => 'order_status']);
            $this->load->view("admin/user_order_summary", $data);
            $this->load->view("admin/footer");
        } else {
            show_404();
        }
    }

    public function userMeasurementList($enc_user = NULL)
    {
        $user_id = $this->M_product->decryptId($enc_user);
        $data = array();
        if( $user_id == NULL){
            redirect("user_list");
        }
        else{
            $data["measurement_list"] = $this->_get_measurement_points($user_id );
            $data["user_id"] = $user_id;
            //echo '<pre>';print_r($data["measurement_list"]);exit;
            $this->load->view("admin/header");
            $this->load->view("admin/sidebar", ['segment' => 'user_list']);
            $this->load->view("admin/user_measurement_list", $data);
            $this->load->view("admin/footer");

        }


    }

    public function featuredSeller()
    {
        $user_id = $this->input->post('id');
        $verified_status = $this->input->post('status');

        $updateArr = array('user_id' => $user_id, 'featured' => $verified_status, 'featured_date' => date('Y-m-d H:i:s'));
        $update = $this->M_admin->updateSeller($updateArr, $user_id);
        if ($update && $verified_status == 1) {
            //              $user = $this->M_admin->getBasicUserDeatils($user_id);

            //              $subject  =  "Welcome to Teyaar - Simply Sell and Buy! ";
            //              $to       =   $user->user_email_id;
            //             // $to      =  "syamca2s@gmail.com";
            //               $from    =  "info@teyaar.com";
            //               $message ='<div style="background: #373242;max-width: 663px;
            //     margin: 0 auto;">
            //     <div style="background:url(http://a2itproducts.com/fassl/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>Congratulations ! your account has been verified</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);
        }
        echo $update;
    }

    public function storeList()
    {

        $condition = array("user_type" => "V");
        $data["user_list"] = $this->M_admin->getShopList();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/store_list", $data);
        $this->load->view("admin/footer");
    }


    public function addEditStore()
    {

        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $data["country_list"] = $this->M_admin->getCountriesCondition($condition);

        $condition2 = array('mall_language_code' => $language, 'mall_status' => 1);
        $data["mall_list"] = $this->M_admin->getMallsCondition($condition2);

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_store", $data);
        $this->load->view("admin/footer");
    }



    public function saveStore()
    {

        $data = array();


        $this->form_validation->set_rules('txt_Store', 'Store name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_email', 'Email Address', 'trim|required|valid_email|max_length[100]');
        $this->form_validation->set_rules('select_country', 'Country', 'trim|required');
        $this->form_validation->set_rules('txt_location', 'Location', 'trim|required|max_length[150]');
        $this->form_validation->set_rules('txt_password', 'Password', 'trim|required|min_length[8]|max_length[20]|valid_password');
        $this->form_validation->set_rules('select_city', 'City', 'trim|required');
        $this->form_validation->set_rules('txt_Phone', 'Phone', 'trim|required|numeric|min_length[5]|max_length[10]|xss_clean');

        if (empty($_FILES['txt_logo']['name'])) {
            $this->form_validation->set_rules('txt_logo', 'Upload Logo', 'trim|required');
        }
        // $this->form_validation->set_rules('txt_user_id', 'User Id', 'trim|required|max_length[50]|min_length[8]|xss_clean|alpha_numeric');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_Store' => form_error('txt_Store'),
                'txt_email' => form_error('txt_email'),
                'select_country' => form_error('select_country'),
                'txt_password' => form_error('txt_password'),
                'select_city' => form_error('select_city'),
                'txt_Phone' => form_error('txt_Phone'),
                'txt_location' => form_error('txt_location'),
                'txt_logo' => form_error('txt_logo'),
            );
            echo json_encode($data);
            exit();
        }
        $_POST = $this->security->xss_clean($_POST);

        if (count($_POST) > 0)
            $result = $this->M_admin->saveStore($_POST);

        else
            $result = 0;


        $data['status'] = $result;
        echo json_encode($data);
    }

    public function editStore()
    {

        $language   = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition  = array('country_language_code' => $language, 'country_status' => 1);

        $data["country_list"] = $this->M_admin->getCountriesCondition($condition);

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/update_edit_store", $data);
        $this->load->view("admin/footer");
    }

    public function updateStore()
    {
        $data = array();

        $this->form_validation->set_rules('txt_Store', 'Store name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_email', 'Email Address', 'trim|required|valid_email|max_length[100]');
        $this->form_validation->set_rules('select_country', 'Country', 'trim|required');
        $this->form_validation->set_rules('txt_location', 'Location', 'trim|required|max_length[150]');
        $this->form_validation->set_rules('txt_password', 'Password', 'trim|required|min_length[8]|max_length[20]|valid_password');
        $this->form_validation->set_rules('select_city', 'City', 'trim|required');
        $this->form_validation->set_rules('txt_Phone', 'Phone', 'trim|required|numeric|min_length[5]|max_length[10]|xss_clean');

        if (empty($_FILES['txt_doc']['name'])) {
            // $this->form_validation->set_rules('txt_doc','Upload Document','trim|required');
        }

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                                'txt_Store' => form_error('txt_Store'),
                                'txt_email' => form_error('txt_email'),
                                'select_country' => form_error('select_country'),
                                'txt_password' => form_error('txt_password'),
                                'select_city' => form_error('select_city'),
                                'txt_Phone' => form_error('txt_Phone'),
                                'txt_location' => form_error('txt_location'),
                                'txt_logo' => form_error('txt_logo'),
                            );
            echo json_encode($data);
            exit();
        }

        $_POST = $this->security->xss_clean($_POST);

        if (count($_POST) > 0)
            $result = $this->M_admin->updateStore($_POST);
        else
            $result = 0;

        $data['status'] = $result;
        echo json_encode($data);
    }

    public function storeDetails()
    {

        // error_reporting(E_ALL & ~E_WARNING);

        $id = $_POST['id'];
        $records1 = $this->M_admin->getVenderFulDetails($id);
        $data['user_deatail'] = $records1;
        $this->load->view('admin/store_detail_view.php', $data);
    }


    public function venderList()
    {
        $data["user_list"] = $this->M_admin->getVenderCondition();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/vender_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditVender()
    {

        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $data["country_list"] = $this->M_admin->getCountriesCondition($condition);

        $condition2 = array('mall_language_code' => $language, 'mall_status' => 1);
        $data["mall_list"] = $this->M_admin->getMallsCondition($condition2);
        $data["bank_list"] = $this->M_admin->getBankList();

        $data['default_seller_commission'] = $this->config->item('default_seller_commission', 'app');
        $data['minimum_seller_commission'] = $this->config->item('minimum_seller_commission', 'app');
        $data['maximum_seller_commission'] = $this->config->item('maximum_seller_commission', 'app');
        $data['driver_earnings_percentage'] = $this->config->item('driver_earnings_percentage', 'app');

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_vender", $data);
        $this->load->view("admin/footer");
    }

    public function saveVender()
    {

        $data = array();


        $this->form_validation->set_rules('txt_first_name', 'First name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_last_name', 'Last name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_email', 'Email Address', 'trim|required|valid_email|max_length[100]');
        $this->form_validation->set_rules('txt_about_desc', 'Description', 'trim|required');
        $this->form_validation->set_rules('txt_about_desc_arabic', 'Description (Arabic)', 'trim|required');
        $this->form_validation->set_rules('radio_gender', 'Gender', 'trim|required');
        $this->form_validation->set_rules('select_country', 'Country', 'trim|required');
        $this->form_validation->set_rules('txt_password', 'Password', 'trim|required|min_length[8]|max_length[20]|valid_password');
        $this->form_validation->set_rules('select_city[]', 'City', 'trim|required');
        $this->form_validation->set_rules('txt_Phone[]', 'Phone', 'trim|required|numeric|min_length[5]|max_length[10]|xss_clean');
        //   $this->form_validation->set_rules('txt_Land_Phone[]', 'Land Phone', 'trim|numeric|max_length[12]');
        $this->form_validation->set_rules('txt_location[]', 'Location', 'trim|required|max_length[150]');
        $this->form_validation->set_rules('txt_street[]', 'Street Name', 'trim|required|max_length[150]|check_inavlid_char');
        $this->form_validation->set_rules('txt_building[]', 'Building Number', 'trim|required|max_length[50]|check_inavlid_char');
        $this->form_validation->set_rules('txt_Store[]', 'Store name', 'trim|required|max_length[100]|check_inavlid_char');
        $this->form_validation->set_rules('txt_doc_no[]', 'Document number', 'trim|required|max_length[50]|check_inavlid_char');
        $this->form_validation->set_rules('select_doc_type[]', 'Document type', 'trim|required');
        if (empty($_FILES['txt_doc']['name'])) {
            $this->form_validation->set_rules('txt_doc', 'Upload Document', 'trim|required');
        }
        $this->form_validation->set_rules('delivery_time_min', 'Delivery Time (Min)', 'trim|required|numeric|xss_clean');
        $this->form_validation->set_rules('delivery_time_max', 'Delivery Time (Max)', 'trim|required|numeric|xss_clean');

        $this->form_validation->set_rules('seller_commission', 'Khiat Commission', 'trim|required|callback_is_valid_seller_commission');

        $this->form_validation->set_rules('seller_bank_id', 'Bank', 'trim|required');
        $this->form_validation->set_rules('bank_account_number', 'Bank Account No.', 'trim|required|numeric|max_length[50]');
        $this->form_validation->set_rules('bank_ifsc_code', 'IFSC Code', 'trim|required|max_length[50]');
        $this->form_validation->set_rules('bank_swift_code', 'Swift Code', 'trim|required|max_length[50]');

        // $this->form_validation->set_rules('txt_user_id', 'User Id', 'trim|required|max_length[50]|min_length[8]|xss_clean|alpha_numeric');
        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_first_name' => form_error('txt_first_name'),
                'txt_last_name' => form_error('txt_last_name'),
                'txt_email' => form_error('txt_email'),
                'txt_about_desc' => form_error('txt_about_desc'),
                'txt_about_desc_arabic' => form_error('txt_about_desc_arabic'),
                //'txt_user_id' => form_error('txt_user_id'),
                'radio_gender' => form_error('radio_gender'),
                'select_country' => form_error('select_country'),
                'txt_password' => form_error('txt_password'),
                'select_city[]' => form_error('select_city[]'),
                'txt_Phone[]' => form_error('txt_Phone[]'),
                'txt_Land_Phone[]' => form_error('txt_Land_Phone[]'),
                'txt_location[]' => form_error('txt_location[]'),
                'txt_street[]' => form_error('txt_street[]'),
                'txt_building[]' => form_error('txt_building[]'),
                'txt_Store[]' => form_error('txt_Store[]'),
                'txt_doc_no[]' => form_error('txt_doc_no[]'),
                'select_doc_type[]' => form_error('select_doc_type[]'),
                'txt_doc' => form_error('txt_doc'),
                'seller_commission' => form_error('seller_commission'),
                'delivery_time_min' => form_error('delivery_time_min'),
                'delivery_time_max' => form_error('delivery_time_max'),
                'seller_bank_id' => form_error('seller_bank_id'),
                'bank_account_number' => form_error('bank_account_number'),
                'bank_ifsc_code' => form_error('bank_ifsc_code'),
                'bank_swift_code' => form_error('bank_swift_code'),
            );
            echo json_encode($data);
            exit();
        }
        $_POST = $this->security->xss_clean($_POST);

        if (count($_POST) > 0) {
            /**
             * There is no need to verify phone number, since it is added by Admin.
             * Otherwise the vendor will be blocked from being login using mobile app
             * because of OTP verification.
             */
            $_POST['phone_verified'] = 1;
            $_POST['seller_commission'] = 100 - $_POST['seller_commission'];
            $result = $this->M_admin->saveVender($_POST);
        } else {
            $result = 0;
        }

        $data['status'] = $result;
        echo json_encode($data);
    }

    public function is_valid_seller_commission( $value )
    {
        $value = (int) $value;
        if ( $value <= 0 ) {
            return TRUE;
        }
        $minimum_seller_commission = $this->config->item('minimum_seller_commission', 'app');
        $maximum_seller_commission = $this->config->item('maximum_seller_commission', 'app');
        if ( $value >= $minimum_seller_commission && $value <= $maximum_seller_commission) {
            return TRUE;
        }
        $this->form_validation->set_message('is_valid_seller_commission', "{field} must be between {$minimum_seller_commission} and {$maximum_seller_commission}.");
        return FALSE;
    }

    public function editVender()
    {
        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $data["country_list"] = $this->M_admin->getCountriesCondition($condition);

        $condition2 = array('mall_language_code' => $language, 'mall_status' => 1);
        $data["mall_list"] = $this->M_admin->getMallsCondition($condition2);
        $data["bank_list"] = $this->M_admin->getBankList();

        $data['default_seller_commission'] = $this->config->item('default_seller_commission', 'app');
        $data['minimum_seller_commission'] = $this->config->item('minimum_seller_commission', 'app');
        $data['maximum_seller_commission'] = $this->config->item('maximum_seller_commission', 'app');
        $data['driver_earnings_percentage'] = $this->config->item('driver_earnings_percentage', 'app');

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/update_edit_vender", $data);
        $this->load->view("admin/footer");
    }

    public function updateVender()
    {
        $data = array();

        $this->form_validation->set_rules('txt_first_name', 'First name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_last_name', 'Last name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_email', 'Email Address', 'trim|required|valid_email|max_length[100]');
        $this->form_validation->set_rules('txt_about_desc', 'Description', 'trim|required');
        $this->form_validation->set_rules('txt_about_desc_arabic', 'Description (Arabic)', 'trim|required');
        $this->form_validation->set_rules('radio_gender', 'Gender', 'trim|required');
        $this->form_validation->set_rules('select_country', 'Country', 'trim|required');
        $this->form_validation->set_rules('select_city[]', 'City', 'trim|required');
        $this->form_validation->set_rules('txt_Phone[]', 'Phone', 'trim|required|numeric|min_length[5]|max_length[10]|xss_clean');
        $this->form_validation->set_rules('txt_Land_Phone[]', 'Land Phone', 'trim|numeric|max_length[12]');
        $this->form_validation->set_rules('txt_location[]', 'Location', 'trim|required|max_length[150]');
        $this->form_validation->set_rules('txt_street[]', 'Street Name', 'trim|required|max_length[150]|check_inavlid_char');
        $this->form_validation->set_rules('txt_building[]', 'Building Number', 'trim|required|max_length[50]|check_inavlid_char');
        $this->form_validation->set_rules('txt_Store[]', 'Store name', 'trim|required|max_length[100]|check_inavlid_char');
        $this->form_validation->set_rules('txt_doc_no[]', 'Document number', 'trim|required|max_length[50]|check_inavlid_char');
        $this->form_validation->set_rules('select_doc_type[]', 'Document type', 'trim|required');
        $this->form_validation->set_rules('delivery_time_min', 'Delivery Time (Min)', 'trim|required|numeric|xss_clean');
        $this->form_validation->set_rules('delivery_time_max', 'Delivery Time (Max)', 'trim|required|numeric|xss_clean');

        $this->form_validation->set_rules('seller_commission', 'Khiat Commission', 'trim|required|callback_is_valid_seller_commission');

        $this->form_validation->set_rules('seller_bank_id', 'Bank', 'trim|required');
        $this->form_validation->set_rules('bank_account_number', 'Bank Account No.', 'trim|required|numeric|max_length[50]');
        $this->form_validation->set_rules('bank_ifsc_code', 'IFSC Code', 'trim|required|max_length[50]');
        $this->form_validation->set_rules('bank_swift_code', 'Swift Code', 'trim|required|max_length[50]');

        if (empty($_FILES['txt_doc']['name'])) {
            // $this->form_validation->set_rules('txt_doc','Upload Document','trim|required');
        }

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_first_name' => form_error('txt_first_name'),
                'txt_last_name' => form_error('txt_last_name'),
                'txt_email' => form_error('txt_email'),
                'txt_about_desc' => form_error('txt_about_desc'),
                'txt_about_desc_arabic' => form_error('txt_about_desc_arabic'),
                'radio_gender' => form_error('radio_gender'),
                'select_country' => form_error('select_country'),
                'select_city[]' => form_error('select_city[]'),
                'txt_Phone[]' => form_error('txt_Phone[]'),
                'txt_Land_Phone[]' => form_error('txt_Land_Phone[]'),
                'txt_location[]' => form_error('txt_location[]'),
                'txt_street[]' => form_error('txt_street[]'),
                'txt_building[]' => form_error('txt_building[]'),
                'txt_Store[]' => form_error('txt_Store[]'),
                'txt_doc_no[]' => form_error('txt_doc_no[]'),
                'select_doc_type[]' => form_error('select_doc_type[]'),
                'txt_doc' => form_error('txt_doc'),
                'seller_commission' => form_error('seller_commission'),
                'delivery_time_min' => form_error('delivery_time_min'),
                'delivery_time_max' => form_error('delivery_time_max'),
                'seller_bank_id' => form_error('seller_bank_id'),
                'bank_account_number' => form_error('bank_account_number'),
                'bank_ifsc_code' => form_error('bank_ifsc_code'),
                'bank_swift_code' => form_error('bank_swift_code'),
            );
            echo json_encode($data);
            exit();
        }
        $_POST = $this->security->xss_clean($_POST);
        if (count($_POST) > 0) {
            $_POST['seller_commission'] = 100 - $_POST['seller_commission'];
            $result = $this->M_admin->updateVender($_POST);
        } else {
            $result = 0;
        }
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function venderDetails()
    {

        // error_reporting(E_ALL & ~E_WARNING);

        $id = $_POST['id'];
        $records1 = $this->M_admin->getVendorByUserId($id);
        $data['user_deatail'] = $records1;
        $this->load->view('admin/vender_detail_view', $data);
    }
    /**
     * Freelancer
     */
    public function freelancerList()
    {
        $data["user_list"] = $this->M_admin->getFreelancerCondition();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/freelancer_list", $data);
        $this->load->view("admin/footer");
    }
    /**
     * Owners
     */
    public function ownerList()
    {
        $data["user_list"] = $this->M_admin->getOwnerConditionIncludingOrderCount();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/owner_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditOwner( $encrypted_id=NULL )
    {
        $id = null;

        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $country_list = $this->M_admin->getCountriesCondition($condition);

        $company_name   = '';
        $user_email_id  = '';
        $password       = '';
        $select_country = '';
        $select_city    = '';
        $dial_code      = '';
        $phone_number   = '';
        $user_image     = '';
        $user_location  = '';
        $user_latitude  = '';
        $user_longitude = '';
        $txt_first_name = '';
        $txt_last_name  = '';

        if ( $encrypted_id ) {
            $action = "edit";
            $id = $this->M_product->decryptId($encrypted_id);
            if ($id > 0) {
                $user = $this->M_admin->get_user(['user_id' => $id, 'user_type' => 'O']);
                if ( $user ) {
                    $company_name   = $user->company_name;
                    $user_email_id  = $user->user_email_id;
                    $password       = 'nopassword';
                    $select_country = $user->user_country_id;
                    $select_city    = $user->user_city_id;
                    $dial_code      = $user->dial_code;
                    $phone_number   = $user->phone_number;
                    $user_image     = $user->image;
                    $user_location  = $user->user_location;
                    $user_latitude  = $user->user_latitude;
                    $user_longitude = $user->user_longitude;
                    $txt_first_name = $user->user_first_name;
                    $txt_last_name  = $user->user_last_name;
                } else {
                    show_404();
                }
            }
        } else {
            $action = "add";
        }

        if ( !empty($select_country) ) {
            $condition = array('city_language_code' => $language, 'city_status' => 1, 'city_country_id' => $select_country);
            $city_list = $this->M_admin->getCitiesCondition($condition);
            if ( !empty($city_list) && empty($select_city) ) {
                $select_city = $city_list[0]->city_id;
            }
        } else {
            $city_list = array();
        }

        if ( empty($user_latitude) ) {
            $user_latitude = 25.204819;
        }
        if ( empty($user_longitude) ) {
            $user_longitude = 55.270931;
        }

        $data = compact('action', 'id', 'country_list', 'city_list', 'company_name', 'user_email_id', 'password', 'select_country', 'select_city', 'dial_code', 'phone_number', 'user_image', 'user_location', 'user_latitude', 'user_longitude', 'txt_first_name', 'txt_last_name');

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", array('segment' => 'owner_list'));
        $this->load->view("admin/add_edit_owner", $data);
        $this->load->view("admin/footer");
    }

    /**
     * Architects
     */
    public function architectList()
    {
        $data["user_list"] = $this->M_admin->getArchitectCondition();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/architect_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditArchitect( $encrypted_id=NULL )
    {
        $id = null;

        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $country_list = $this->M_admin->getCountriesCondition($condition);

        $company_name   = '';
        $user_email_id  = '';
        $password       = '';
        $select_country = '';
        $select_city    = '';
        $dial_code      = '';
        $trade_license  = '';
        $phone_number   = '';
        $user_image     = '';
        $user_location  = '';
        $user_latitude  = '';
        $user_longitude = '';

        if ( $encrypted_id ) {
            $action = "edit";
            $id = $this->M_product->decryptId($encrypted_id);
            if ($id > 0) {
                $user = $this->M_admin->get_user(['user_id' => $id, 'user_type' => 'A']);
                if ( $user ) {
                    $company_name   = $user->company_name;
                    $user_email_id  = $user->user_email_id;
                    $password       = 'nopassword';
                    $select_country = $user->user_country_id;
                    $select_city    = $user->user_city_id;
                    $dial_code      = $user->dial_code;
                    $trade_license  = $user->trade_license_no;
                    $phone_number   = $user->phone_number;
                    $user_image     = $user->image;
                    $user_location  = $user->user_location;
                    $user_latitude  = $user->user_latitude;
                    $user_longitude = $user->user_longitude;
                } else {
                    show_404();
                }
            }
        } else {
            $action = "add";
        }

        if ( !empty($select_country) ) {
            $condition = array('city_language_code' => $language, 'city_status' => 1, 'city_country_id' => $select_country);
            $city_list = $this->M_admin->getCitiesCondition($condition);
            if ( !empty($city_list) && empty($select_city) ) {
                $select_city = $city_list[0]->city_id;
            }
        } else {
            $city_list = array();
        }

        if ( empty($user_latitude) ) {
            $user_latitude = 25.204819;
        }
        if ( empty($user_longitude) ) {
            $user_longitude = 55.270931;
        }

        $data = compact('action', 'id', 'country_list', 'city_list', 'company_name', 'user_email_id', 'password', 'select_country', 'select_city', 'dial_code', 'trade_license', 'phone_number', 'user_image', 'user_location', 'user_latitude', 'user_longitude');

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", array('segment' => 'architect_list'));
        $this->load->view("admin/add_edit_architect", $data);
        $this->load->view("admin/footer");
    }

    /**
     * Contractors
     */
    public function contractorList()
    {
        $data["user_list"] = $this->M_admin->getContractorCondition();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/contractor_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditContractor( $encrypted_id=NULL )
    {
        $id = null;

        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $country_list = $this->M_admin->getCountriesCondition($condition);

        $company_name   = '';
        $user_email_id  = '';
        $password       = '';
        $select_country = '';
        $select_city    = '';
        $dial_code      = '';
        $trade_license  = '';
        $phone_number   = '';
        $user_image     = '';
        $user_location  = '';
        $user_latitude  = '';
        $user_longitude = '';

        if ( $encrypted_id ) {
            $action = "edit";
            $id = $this->M_product->decryptId($encrypted_id);
            if ($id > 0) {
                $user = $this->M_admin->get_user(['user_id' => $id, 'user_type' => 'C']);
                if ( $user ) {
                    $company_name   = $user->company_name;
                    $user_email_id  = $user->user_email_id;
                    $select_country = $user->user_country_id;
                    $select_city    = $user->user_city_id;
                    $dial_code      = $user->dial_code;
                    $trade_license  = $user->trade_license_no;
                    $phone_number   = $user->phone_number;
                    $user_image     = $user->image;
                    $user_location  = $user->user_location;
                    $user_latitude  = $user->user_latitude;
                    $user_longitude = $user->user_longitude;
                } else {
                    show_404();
                }
            }
        } else {
            $action = "add";
        }

        if ( !empty($select_country) ) {
            $condition = array('city_language_code' => $language, 'city_status' => 1, 'city_country_id' => $select_country);
            $city_list = $this->M_admin->getCitiesCondition($condition);
            if ( !empty($city_list) && empty($select_city) ) {
                $select_city = $city_list[0]->city_id;
            }
        } else {
            $city_list = array();
        }

        if ( empty($user_latitude) ) {
            $user_latitude = 25.204819;
        }
        if ( empty($user_longitude) ) {
            $user_longitude = 55.270931;
        }

        $data = compact('action', 'id', 'country_list', 'city_list', 'company_name', 'user_email_id', 'password', 'select_country', 'select_city', 'dial_code', 'trade_license', 'phone_number', 'user_image', 'user_location', 'user_latitude', 'user_longitude');

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", array('segment' => 'contractor_list'));
        $this->load->view("admin/add_edit_contractor", $data);
        $this->load->view("admin/footer");
    }

    public function driverList($encrypted_id="")
    {
        $condition =[];
        if($encrypted_id)
        {
            $vendor_id = $this->M_product->decryptId($encrypted_id);
            $condition = array("s.vendor_id" => $vendor_id);
        }
        $data["user_list"] = $this->M_admin->getDriverCondition($condition);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/driver_list", $data);
        $this->load->view("admin/footer");
    }

    public function driverEarnings( $encrypted_id )
    {
        $user_id = $this->M_product->decryptId($encrypted_id);

        $start_date = $this->input->get('sdate', true);
        $end_date = $this->input->get('edate', true);
        $condition = compact('start_date', 'end_date');

        $data['earnings'] = $this->M_admin->getDriverEarnings($user_id, NULL, NULL, $condition);

        $total_earnings = 0;
        $total_paid = 0;
        $total_sales = 0;
        foreach ($data['earnings'] as $row) {
            $total_sales += $row->total_sale;
            $total_earnings += $row->earning;
            if ( $row->is_paid ) {
                $total_paid += $row->earning;
            }
        }

        $data['total_sales']    = $total_sales;
        $data['total_earnings'] = $total_earnings;
        $data['total_paid']     = $total_paid;
        $data['total_pending']  = $total_earnings - $total_paid;
        $data['encrypted_id']   = $encrypted_id;
        $data['start_date']     = $start_date;
        $data['end_date']       = $end_date;

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ['segment' => 'driver_list']);
        $this->load->view("admin/driver_earnings", $data);
        $this->load->view("admin/footer");
    }

    public function payDriverEarning()
    {
        if ( $this->input->is_ajax_request() ) {
            $earning_id = $this->input->post('earning_id', true);
            $status = $this->M_admin->payDriverEarning($earning_id);
            echo $status;
        }
    }

    /*public function addDriver($encrypted_id = null)
    {
        $id = null;

        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $country_list = $this->M_admin->getCountriesCondition($condition);

        if ( $encrypted_id ) {
            $action = "edit";
            $id = $this->M_product->decryptId($encrypted_id);
            if ($id > 0) {
                $driver_record = $this->M_admin->getDriverCondition(array('u.user_id' => $id));
                if ( count($driver_record) > 0 ) {
                    $driver_record = $driver_record[0];
                    $txt_first_name = $driver_record->user_first_name;
                    $txt_last_name = $driver_record->user_last_name;
                    $select_country = $driver_record->user_country_id;
                    $select_city = $driver_record->city;
                    $txt_email = $driver_record->user_email_id;
                    $txt_user_id = $driver_record->user_custom_id;
                    $radio_gender = $driver_record->user_gender;
                    $user_image = $driver_record->image;
                    $mobile_no_list = explode('-', $driver_record->mobile_no);
                    $txt_dialcode = ( count($mobile_no_list) > 1 ) ? $mobile_no_list[0] : null;
                    $txt_Phone = ( count($mobile_no_list) > 1 ) ? $mobile_no_list[1] : $mobile_no_list[0];
                    $txt_location = $driver_record->location;
                    $txt_street = $driver_record->street_name;
                    $txt_building = $driver_record->building_no;
                    $latitude = $driver_record->latitude;
                    $longitude = $driver_record->longitude;
                    $txt_veh_no = $driver_record->vehicle_no;
                    $txt_Land_Phone = $driver_record->land_phone;
                    $txt_License = $driver_record->document_number;
                    $vehicle_type = $driver_record->vehicle_type_id;
                    $vehicle_reg_no = $driver_record->vehicle_reg_no;
                    $license_file_name = $driver_record->doument_name;
                    $mulkiya_file_name = $driver_record->mulkiya;
                    $emirates_id = $driver_record->emirates_id_number;
                    $emirates_id_file_name = $driver_record->emirates_id_file;
                    $earning_percentage = $driver_record->driver_earning_percentage;
                    $driver_bank_id = $driver_record->driver_bank_id;
                    $bank_account_number = $driver_record->bank_account_number;
                    $bank_ifsc_code = $driver_record->bank_ifsc_code ?? "";
                    $bank_swift_code = $driver_record->bank_swift_code ?? "";
                } else {
                    show_404();
                }
            }
        } else {
            $action = "add";
            $txt_first_name = null;
            $txt_last_name = null;
            $select_country = !empty($country_list) ? $country_list[0]->country_id : null;
            $select_city = null;
            $txt_email = null;
            $txt_user_id = null;
            $radio_gender = 1;
            $user_image = null;
            $txt_dialcode = null;
            $txt_Phone = null;
            $txt_location = null;
            $txt_street = null;
            $txt_building = null;
            $latitude = null;
            $longitude = null;
            $txt_veh_no = null;
            $txt_Land_Phone = null;
            $txt_License = null;
            $vehicle_type = null;
            $vehicle_reg_no = null;
            $license_file_name = null;
            $mulkiya_file_name = null;
            $emirates_id = null;
            $emirates_id_file_name = null;
            $earning_percentage = null;
            $driver_bank_id = null;
            $bank_account_number = null;
            $bank_ifsc_code = null;
            $bank_swift_code = null;
        }

        if ( !empty($select_country) ) {
            $condition = array('city_language_code' => $language, 'city_status' => 1, 'city_country_id' => $select_country);
            $city_list = $this->M_admin->getCitiesCondition($condition);
            if ( !empty($city_list) ) {
                $select_city = $city_list[0]->city_id;
            }
        } else {
            $city_list = array();
        }
        $vehicle_type_list = $this->M_admin->getVehicleTypeCondition(array('language_type' => $language));
        $bank_list = $this->M_admin->getBankList();

        $data = compact('action', 'id', 'country_list', 'city_list', 'vehicle_type_list', 'bank_list', 'txt_first_name', 'txt_last_name', 'select_country', 'select_city', 'txt_email', 'txt_user_id', 'radio_gender', 'user_image', 'txt_dialcode', 'txt_Phone', 'txt_location', 'txt_street', 'txt_building', 'latitude', 'longitude', 'txt_veh_no', 'txt_Land_Phone', 'txt_License', 'vehicle_type', 'vehicle_reg_no', 'license_file_name', 'mulkiya_file_name', 'emirates_id', 'emirates_id_file_name', 'earning_percentage', 'driver_bank_id', 'bank_account_number', 'bank_ifsc_code', 'bank_swift_code');

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", array('segment' => 'driver_list'));
        $this->load->view("admin/add_edit_driver", $data);
        $this->load->view("admin/footer");
    }*/

    public function addEditDriver($encrypted_id = null,$enc_vendor_id = null)
    {
        $id = null;

        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $country_list = $this->M_admin->getCountriesCondition($condition);

        if ( $encrypted_id ) {
            $action = "edit";
            $id = $this->M_product->decryptId($encrypted_id);
            if ($id > 0) {
                $driver_record = $this->M_admin->getDriverCondition(array('u.user_id' => $id));
                if ( count($driver_record) > 0 ) {
                    $driver_record = $driver_record[0];
                    $txt_first_name = $driver_record->user_first_name;
                    $txt_last_name = $driver_record->user_last_name;
                    $select_country = $driver_record->user_country_id;
                    $select_city = $driver_record->city;
                    $txt_email = $driver_record->user_email_id;
                    $txt_user_id = $driver_record->user_custom_id;
                    $radio_gender = $driver_record->user_gender;
                    $user_image = $driver_record->image;
                    $mobile_no_list = explode('-', $driver_record->mobile_no);
                    $txt_dialcode = ( count($mobile_no_list) > 1 ) ? $mobile_no_list[0] : null;
                    $txt_Phone = ( count($mobile_no_list) > 1 ) ? $mobile_no_list[1] : $mobile_no_list[0];
                    $txt_location = $driver_record->location;
                    $txt_street = $driver_record->street_name;
                    $txt_building = $driver_record->building_no;
                    $latitude = $driver_record->latitude;
                    $longitude = $driver_record->longitude;
                    $txt_veh_no = $driver_record->vehicle_no;
                    $txt_Land_Phone = $driver_record->land_phone;
                    $txt_License = $driver_record->document_number;
                    $vehicle_type = $driver_record->vehicle_type_id;
                    $vehicle_reg_no = $driver_record->vehicle_reg_no;
                    $license_file_name = $driver_record->doument_name;
                    $mulkiya_file_name = $driver_record->mulkiya;
                    $emirates_id = $driver_record->emirates_id_number;
                    $emirates_id_file_name = $driver_record->emirates_id_file;
                    $earning_percentage = $driver_record->driver_earning_percentage;
                    $driver_bank_id = $driver_record->driver_bank_id;
                    $bank_account_number = $driver_record->bank_account_number;
                    $bank_ifsc_code = $driver_record->bank_ifsc_code ?? "";
                    $bank_swift_code = $driver_record->bank_swift_code ?? "";
                    $vender_id = $driver_record->vendor_id;
                } else {
                    show_404();
                }
            }
        } else {
            $action = "add";
            $txt_first_name = null;
            $txt_last_name = null;
            $select_country = "";//!empty($country_list) ? $country_list[0]->country_id : null;
            $select_city = null;
            $txt_email = null;
            $txt_user_id = null;
            $radio_gender = 1;
            $user_image = null;
            $txt_dialcode = null;
            $txt_Phone = null;
            $txt_location = null;
            $txt_street = null;
            $txt_building = null;
            $latitude = null;
            $longitude = null;
            $txt_veh_no = null;
            $txt_Land_Phone = null;
            $txt_License = null;
            $vehicle_type = null;
            $vehicle_reg_no = null;
            $license_file_name = null;
            $mulkiya_file_name = null;
            $emirates_id = null;
            $emirates_id_file_name = null;
            $earning_percentage = null;
            $driver_bank_id = null;
            $bank_account_number = null;
            $bank_ifsc_code = null;
            $bank_swift_code = null;
            $vender_id = $this->M_product->decryptId($enc_vendor_id);
        }

        if ( !empty($select_country) ) {
            $condition = array('city_language_code' => $language, 'city_status' => 1, 'city_country_id' => $select_country);
            $city_list = $this->M_admin->getCitiesCondition($condition);
            /*if ( !empty($city_list) ) {
                $select_city = $city_list[0]->city_id;
            }*/
        } else {
            $city_list = array();
        }
        $vehicle_type_list = $this->M_admin->getVehicleTypeCondition(array('language_type' => $language));
        $bank_list = $this->M_admin->getBankList();

        $data = compact('action', 'id', 'country_list', 'city_list', 'vehicle_type_list', 'bank_list', 'txt_first_name', 'txt_last_name', 'select_country', 'select_city', 'txt_email', 'txt_user_id', 'radio_gender', 'user_image', 'txt_dialcode', 'txt_Phone', 'txt_location', 'txt_street', 'txt_building', 'latitude', 'longitude', 'txt_veh_no', 'txt_Land_Phone', 'txt_License', 'vehicle_type', 'vehicle_reg_no', 'license_file_name', 'mulkiya_file_name', 'emirates_id', 'emirates_id_file_name', 'earning_percentage', 'driver_bank_id', 'bank_account_number', 'bank_ifsc_code', 'bank_swift_code','vender_id');

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", array('segment' => 'driver_list'));
        $this->load->view("admin/add_edit_driver", $data);
        $this->load->view("admin/footer");
    }

    public function saveDriver()
    {
        //echo '<pre>';print_r($_POST);die;
        $data = array();

        $id = $this->input->post('id', true);

        $this->form_validation->set_rules('txt_first_name', 'First name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_last_name', 'Last name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_email', 'Email Address', 'required|valid_email|max_length[100]');
        // $this->form_validation->set_rules('radio_gender', 'Gender', 'trim|required');
        $this->form_validation->set_rules('select_country', 'Country', 'trim|required');
        if (! isset($id) ) {
            $this->form_validation->set_rules('txt_password', 'Password', 'trim|required|min_length[8]|max_length[20]|valid_password');
            //$this->form_validation->set_rules('txt_user_id', 'User id', 'trim|required|max_length[50]|min_length[8]|xss_clean|alpha_numeric');
        } else {
            $pw = $this->input->post('txt_password', true);
            if ( $pw == 'nopassword' ) {
                $_POST['txt_password'] = '';
            }
            if ( !empty($pw) && ($pw != 'nopassword') ) {
                $this->form_validation->set_rules('txt_password', 'Password', 'min_length[8]|max_length[20]|valid_password');
            }
        }
        $this->form_validation->set_rules('select_city[]', 'City', 'trim|required');
        $this->form_validation->set_rules('txt_Phone[]', 'Phone', 'trim|required|numeric|min_length[5]|max_length[10]|xss_clean');
        // $this->form_validation->set_rules('txt_Land_Phone[]', 'Land Phone', 'trim|numeric|max_length[15]');
        // $this->form_validation->set_rules('txt_location[]', 'Location', 'trim|required|max_length[150]');
        $this->form_validation->set_rules('txt_street[]', 'Street Name', 'trim|required|max_length[100]|check_inavlid_char');
        // $this->form_validation->set_rules('txt_building[]', 'Building Number', 'trim|required|max_length[50]|check_inavlid_char');
        // $this->form_validation->set_rules('txt_License[]', 'License No', 'trim|required|max_length[50]|check_inavlid_char');
        $this->form_validation->set_rules('txt_veh_no[]', 'Vehicle No', 'trim|required|max_length[50]|check_inavlid_char');

        if (! isset($id) ) {
            if (empty($_FILES['txt_doc']['name'])) {
                $this->form_validation->set_rules('txt_doc', 'Upload Document', 'trim|required');
            }
            if (empty($_FILES['txt_doc2']['name'])) {
                $this->form_validation->set_rules('txt_doc2', 'Upload Document', 'trim|required');
            }
        }

        $this->form_validation->set_rules('driver_bank_id', 'Bank', 'trim|required');
        $this->form_validation->set_rules('driver_bank_account_number', 'Bank Account No.', 'trim|required|numeric|max_length[50]|xss_clean');
        $this->form_validation->set_rules('driver_bank_ifsc_code', 'IFSC Code', 'trim|required|max_length[50]');
        $this->form_validation->set_rules('driver_bank_swift_code', 'Swift Code', 'trim|required|max_length[50]');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_first_name' => form_error('txt_first_name'),
                'txt_last_name' => form_error('txt_last_name'),
                'txt_email' => form_error('txt_email'),
               // 'txt_user_id' => form_error('txt_user_id'),
                'radio_gender' => form_error('radio_gender'),
                'select_country' => form_error('select_country'),
                'txt_password' => form_error('txt_password'),
                'select_city[]' => form_error('select_city[]'),
                'txt_Phone[]' => form_error('txt_Phone[]'),
                //'txt_Land_Phone[]' => form_error('txt_Land_Phone[]'),
                'txt_location[]' => form_error('txt_location[]'),
                'txt_street[]' => form_error('txt_street[]'),
                'txt_building[]' => form_error('txt_building[]'),
                'txt_License[]' => form_error('txt_License[]'),
                'txt_veh_no[]' => form_error('txt_veh_no[]'),
                'txt_emirates_id[]' => form_error('txt_emirates_id[]'),
                // 'select_doc_type[]' => form_error('select_doc_type[]'),
                // 'txt_doc' => form_error('txt_doc'),
                'txt_doc2' => form_error('txt_doc2'),
                'txt_doc3' => form_error('txt_doc3'),
                'driver_bank_id' => form_error('driver_bank_id'),
                'driver_bank_account_number' => form_error('driver_bank_account_number'),
                'driver_bank_ifsc_code' => form_error('driver_bank_ifsc_code'),
                'driver_bank_swift_code' => form_error('driver_bank_swift_code'),
            );
            echo json_encode($data);
            exit();
        }
        $_POST = $this->security->xss_clean($_POST);

        if ( count($_POST) > 0 ) {
            $result = 1;
            /**
             * There is no need to verify phone number, since it is added by Admin.
             * Otherwise the driver will be blocked from being login using mobile app
             * because of OTP verification.
             */
            $_POST['phone_verified'] = 1;
            if ( $id > 0 ) {
                $result = $this->M_admin->updateDriver($_POST);
            } else {
                $result = $this->M_admin->saveDriver($_POST);
            }
        } else {
            $result = 0;
        }
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function editDriver()
    {
        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $data["country_list"] = $this->M_admin->getCountriesCondition($condition);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/update_edit_driver", $data);
        $this->load->view("admin/footer");
    }

    public function updateDriver()
    {
        $data = array();

        $this->form_validation->set_rules('txt_first_name', 'First name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_last_name', 'Last name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        //$this->form_validation->set_rules('txt_email', 'Email Address', 'trim|required|valid_email');
        $this->form_validation->set_rules('radio_gender', 'Gender', 'trim|required');
        $this->form_validation->set_rules('select_country', 'Country', 'trim|required');
        $this->form_validation->set_rules('select_city[]', 'City', 'trim|required');
        $this->form_validation->set_rules('txt_Phone[]', 'Phone', 'trim|required|numeric|min_length[5]|max_length[10]|xss_clean');
        $this->form_validation->set_rules('txt_Land_Phone[]', 'Land Phone', 'trim|numeric|max_length[15]');
        $this->form_validation->set_rules('txt_location[]', 'Location', 'trim|required|max_length[150]');
        $this->form_validation->set_rules('txt_street[]', 'Street Name', 'trim|required|max_length[100]|check_inavlid_char');
        $this->form_validation->set_rules('txt_building[]', 'Building Number', 'trim|required|max_length[50]|check_inavlid_char');
        $this->form_validation->set_rules('txt_License[]', 'License No', 'trim|required|max_length[50]|check_inavlid_char');
        $this->form_validation->set_rules('txt_veh_no[]', 'Vehicle No', 'trim|required|max_length[50]|check_inavlid_char');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_first_name' => form_error('txt_first_name'),
                'txt_last_name' => form_error('txt_last_name'),
                'txt_email' => form_error('txt_email'),
                'radio_gender' => form_error('radio_gender'),
                'select_country' => form_error('select_country'),
                'select_city[]' => form_error('select_city[]'),
                'txt_Phone[]' => form_error('txt_Phone[]'),
                'txt_Land_Phone[]' => form_error('txt_Land_Phone[]'),
                'txt_location[]' => form_error('txt_location[]'),
                'txt_street[]' => form_error('txt_street[]'),
                'txt_building[]' => form_error('txt_building[]'),
                'txt_License[]' => form_error('txt_License[]'),
                'txt_veh_no[]' => form_error('txt_veh_no[]'),
                'txt_Land_Phone[]' => form_error('txt_Land_Phone[]'),
            );
            echo json_encode($data);
            exit();
        }

        $_POST = $this->security->xss_clean($_POST);
        if (count($_POST) > 0) {
            $result = $this->M_admin->updateDriver($_POST);
        } else {
            $result = 0;
        }
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function deleteDriver()
    {
        $id = $_POST['id'];
        echo $this->M_admin->deleteDriver($id);
    }

    public function approveDriver()
    {
        $user_id = (int) $this->input->post('id', true);
        $verified_status = (int) $this->input->post('status', true);

        $driver = $this->M_admin->getDriverInfo($user_id);
        $verified_count = $driver->verified_count ?? 0;
        if ( $verified_status == 1 ) {
            $verified_count++;
            $_POST['verified_count'] = $verified_count;
        }

        $_POST = $this->security->xss_clean($_POST);
        $update = $this->M_admin->approveDriver($_POST);

        if ( $update && ($verified_status == 1) && ($verified_count == 1) ) {
            $user = $this->M_admin->getBasicUserDeatils($user_id);

            $this->load->model('website/home_model', 'model_home');
            $app_basic_row  = $this->model_home->get_app_basics();

            $subject = "Congrats! Your account has been verified";
            $to      = $user->user_email_id;

            $email_message = $this->load->view('email_templates/verify_driver', [
                "assets" => base_url()."email_assets/",
                "user_name" => $user->user_first_name . " " . $user->user_last_name,
                "telephone" => ($app_basic_row) ? $app_basic_row->phone_no : "",
                "twitter" => ($app_basic_row) ? $app_basic_row->twitter_link : "",
                "facebook" => ($app_basic_row) ? $app_basic_row->fb_link : "",
                "instagram" => ($app_basic_row) ? $app_basic_row->insta_link : "",
                "email" => ($app_basic_row) ? $app_basic_row->email_id : "",
                "playstore" => ($app_basic_row) ? $app_basic_row->android_app_link:"",
                "appstore" => ($app_basic_row) ? $app_basic_row->ios_app_link:"",
            ], TRUE);

            $from = SITE_NOREPLY_EMAIL;

            $this->load->library("Mail_function");
            $this->mail_function->SendEmail($email_message, $subject, $to);
        }
        echo $update;
    }

    public function driverDetails()
    {
        // error_reporting(E_ALL & ~E_WARNING);

        $id = $_POST['id'];
        // $param                      =   array("user_id"=>$id);
        $records1 = $this->M_admin->getDriverFulDetails($id);
        $data['user_deatail'] = $records1;
        // exit;
        $this->load->view('admin/driver_detail_view', $data);
    }

    public function custom_minlength_check($field_value = "")
    {
        $field_value = strip_tags($field_value);
        if (strlen($field_value) < 10) {
            $this->form_validation->set_message('custom_minlength_check', "Please enter atleast 10 characters");
            return false;
        } else {
            return true;
        }
    }

    public function articleList()
    {
        $condition = array("user_type" => "D");
        $data["article_list"] = $this->M_admin->getArticles();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/article_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditArticle()
    {
        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);

        $data = array();

        $data["article_type"] = $this->M_admin->getArticleTypes();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_article", $data);
        $this->load->view("admin/footer");
    }

    public function saveArticle()
    {
        $this->form_validation->set_rules('txt_article_type', 'Article type', 'trim|required');
        $this->form_validation->set_rules('txt_article', 'Article English', 'trim|required|custom_minlength_check');
        $this->form_validation->set_rules('txt_article_arb', 'Article Arabic', 'trim|required|custom_minlength_check');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_article_type' => form_error('txt_article_type'),
                'txt_article' => form_error('txt_article'),
                'txt_article_arb' => form_error('txt_article_arb'),
            );
            echo json_encode($data);
            exit();
        }

        $_POST = $this->security->xss_clean($_POST);

        if (count($_POST) > 0) {
            $result = $this->M_admin->saveArticle($_POST);
        } else {
            $result = 0;
        }

        $data['status'] = $result;
        echo json_encode($data);
    }

    public function deleteArticle()
    {
        $id = $_POST['id'];
        echo $this->M_admin->deleteArticle($id);
    }

    public function brandList()
    {
        $data["brand_list"] = $this->M_admin->getgetBrandList();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/brand_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditBrand()
    {
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_brand");
        $this->load->view("admin/footer");
    }

    public function saveBrand()
    {

        $data = array();

        if ($_FILES["txtFile"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFile"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'brand/';
            $config2['allowed_types'] = 'gif|jpg|png|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('txtFile')) {
                //die("file upload failed");
                $data['status'] = 3;
                $data['errors'] = array(
                    'txtFile' => strip_tags($this->upload->display_errors()),
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['brand_logo'] = $config2['file_name'];
            }
        }

        $this->form_validation->set_rules('txtEnglish', 'Brand Name English', 'trim|required|max_length[100]|xss_clean|alpha_numeric');
        $this->form_validation->set_rules('txtArabic', 'Brand Name Arabic', 'trim|required|max_length[100]');
        if (empty($_FILES['txtFile']['name'])) {
            $this->form_validation->set_rules('txtFile', 'Image', 'required');
        }

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txtEnglish' => form_error('txtEnglish'),
                'txtArabic' => form_error('txtArabic'),
                'txtFile' => form_error('txtFile'),
            );
            echo json_encode($data);
            exit();
        }

        $inputArray['brand_name'] = ucfirst($_POST['txtEnglish']);
        $inputArray['brand_language_code'] = 1;
        $inputArray['brand_status'] = $_POST['txtStatus'];
        $inputArray['brand_created_date'] = gmdate("Y-m-d H:i:s");

        $inputArray2 = $inputArray;
        $inputArray2['brand_name'] = ($_POST['txtArabic'] != "" ? $_POST['txtArabic'] : ucfirst($_POST['txtEnglish']));
        $inputArray2['brand_language_code'] = 2;

        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['brand_id'] = $_POST['id'];
            $inputArray2['brand_id'] = $_POST['id'];
            unset($inputArray['brand_created_date']);
            unset($inputArray2['brand_created_date']);
        }

        $inputArray = $this->security->xss_clean($inputArray);
        $inputArray2 = $this->security->xss_clean($inputArray2);

        $result = $this->M_admin->saveMasterTable($inputArray, $inputArray2, 'brand_id', 'brand_language_code', 'brand');

        $data['status'] = $result;
        echo json_encode($data);
    }

    public function deleteBrand()
    {
        $id = $_POST['id'];

        echo $this->M_admin->deleteBrand($id);
    }

    public function userReport()
    {
        $condition = array("user_type" => "O");
        $data["user_list"] = $this->M_admin->getUsersCondition($condition);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/user_report", $data);
        $this->load->view("admin/footer");
    }

    public function vendorReport()
    {
        $condition = array("user_type" => "V");
        $data["user_list"] = $this->M_admin->getVenderCondition();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/vendor_report", $data);
        $this->load->view("admin/footer");
    }


    public function salesReport()
    {
        $condition = array("user_type" => "V");
        $data["user_list"] = $this->M_admin->getVenderCondition();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/sales_report", $data);
        $this->load->view("admin/footer");
    }

    public function cashPointReport()
    {
        $data["user_list"] = $this->M_admin->getCashPointReports();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/cash_point_report", $data);
        $this->load->view("admin/footer");
    }

    public function cashPointUserReport($user_id = "")
    {
        $user_id = (int) $this->M_product->decryptId($this->uri->segment(2));

        $user_row = $this->M_admin->get_user(["user_id" => $user_id]);

        if (!$user_row) {
            redirect(base_url()."cashPointReport");
        }




        $data["cashpoint_list"] = $this->M_admin->getUserCashPointDetails($user_id);
        $data["user_data"]      = $user_row;

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/cash_point_user_report", $data);
        $this->load->view("admin/footer");
    }

    public function orderReport()
    {
        $data = array();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/order_history_vendor", $data);
        $this->load->view("admin/footer");
    }

    public function orderIssueReport( $encrypted_id ) {
        // $issues = [
        //     '',
        //     'Missing or wrong products',
        //     'Inacurate product description',
        //     'Late Order',
        //     'Payment Issues'
        // ];
        // foreach ($issues as $t) {
        //     $this->db->insert('order_issue_master', [
        //         'reason' => $t,
        //     ]);
        // }
        /*
        $orders = [57, 56, 56, 55, 54, 54, 53, 52, 51, 51];
        $date = gmdate("Y-m-d H:i:s");
        foreach ($orders as $oid) {
            $this->db->insert('order_reported_issue', [
                'order_id' => $oid,
                'created_date' => $date,
                'issue_text' => $issues[random_int(1, 4)]
            ]);
        }
        exit;
        */
        $order_id = $this->M_product->decryptId($encrypted_id);
        $data['issues_list'] = $this->M_admin->getOrderIssuesReported($order_id);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ['segment' => 'order_report']);
        $this->load->view("admin/order_reported_issues", $data);
        $this->load->view("admin/footer");
    }

    public function productReviews( $encrypted_id )
    {
        // $review = [
        //     '',
        //     'Poor',
        //     'Satisfied',
        //     'Good',
        //     'Excellent',
        //     'Outstanding'
        // ];
        // $date = gmdate("Y-m-d H:i:s");
        // for ($i = 0; $i < 10; $i++) {
        //     $r = random_int(1, 5);
        //     $this->db->insert('temp_reviews', [
        //         'type' => 1,
        //         'created_date' => $date,
        //         'rating' => $r,
        //         'review' => $review[$r]
        //     ]);
        // }
        // exit;
        $product_id = $this->M_product->decryptId($encrypted_id);
        $p_info=$this->M_admin->getProdcutInfo($product_id);
        $data['heading'] = $p_info->product_name;
        $data['review_list'] = $this->M_admin->getReviews($product_id);
     //echo '<pre>';print_r($data['review_list']);exit;
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ['segment' => 'product_list']);
        $this->load->view("admin/view_reviews", $data);
        $this->load->view("admin/footer");
    }

    public function vendorReviews( $encrypted_id )
    {
        $vendor = $this->M_product->decryptId($encrypted_id);
        $v_info=$this->M_admin->getVendorInfo($vendor);
        $data['heading'] = $v_info->store_name;
        $data['review_list'] = $this->M_admin->getVendorReviews($vendor);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ['segment' => 'vender_list']);
        $this->load->view("admin/view_reviews", $data);
        $this->load->view("admin/footer");
    }

    public function vendorEarnings( $encrypted_id )
    {
        $vendor_id = $this->M_product->decryptId($encrypted_id);
        $v_info = $this->M_admin->getVendorInfo($vendor_id);
        $data['heading'] = $v_info->store_name;

        $total_sales = 0;
        $total_earnings = 0;
        $total_paid = 0;

        $start_date = $this->input->get('sdate', true);
        $end_date = $this->input->get('edate', true);
        $condition = compact('start_date', 'end_date');

        $earnings = $this->M_product->getVendorEarnings($vendor_id, NULL, $condition);

        foreach ($earnings as $row) {
            $total_sales += $row->total_sale;
            $total_earnings += $row->earning;
            if ( $row->vendor_commission_paid ) {
                $total_paid += $row->earning;
            }
        }

        $data['earnings']       = $earnings;
        $data['total_sales']    = $total_sales;
        $data['total_earnings'] = $total_earnings;
        $data['total_paid']     = $total_paid;
        $data['vendor_id']      = $vendor_id;
        $data['encrypted_id']   = $encrypted_id;
        $data['start_date']     = $start_date;
        $data['end_date']       = $end_date;

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ['segment' => 'vender_list']);
        $this->load->view("admin/vendor_earnings", $data);

        $this->data['assets']['footer'] = ['admin/scripts/vendor_earnings_script'];
        $this->load->view("admin/footer", $this->data);
    }

    public function vendorEarningsDownload( $encrypted_id )
    {
        $vendor_id = $this->M_product->decryptId($encrypted_id);
        $v_info = $this->M_admin->getVendorInfo($vendor_id);
        if ( empty($v_info) ) {
            show_404();
            exit;
        }

        $start_date = $this->input->get('sdate', true);
        $end_date = $this->input->get('edate', true);
        $condition = compact('start_date', 'end_date');

        $earnings = $this->M_product->getVendorEarnings($vendor_id, NULL, $condition);

        $fileName = $v_info->store_name . '_Earnings';
        $fileName = $fileName . '.xls';

        // headers for download
        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        function filterData(&$str)
        {
            $str = preg_replace("/\t/", "\\t", $str);
            $str = preg_replace("/\r?\n/", "\\n", $str);
            if (strstr($str, '"')) {
                $str = '"' . str_replace('"', '""', $str) . '"';
            }
        }

        $flag = false;
        $i = 1;

        foreach ($earnings as $row) {
            if (!$flag) {
                // display column names as first row
                echo implode("\t", array('#', 'Order No', 'Order Date', 'Total Sales', 'Earnings', SITE_NAME .' Commission', 'Earned Date', 'Status', 'Requested On', 'Paid On')) . "\n";
                $flag = true;
            }
            // filter data
            array_walk($row, 'filterData');

            $earnedDate = get_date_in_timezone("Asia/Dubai", $row->earned_date, "F j, Y, g:i a");
            $requestedDate = "";
            if (! empty($row->vendor_commission_request_withdrawal_date) ) {
                $requestedDate = get_date_in_timezone("Asia/Dubai", $row->vendor_commission_request_withdrawal_date, "F j, Y, g:i a");
            }
            $paidDate = "";
            if (! empty($row->vendor_commission_paid_date) ) {
                $paidDate = get_date_in_timezone("Asia/Dubai", $row->vendor_commission_paid_date, "F j, Y, g:i a");
            }
            $orderDate = get_date_in_timezone('Asia/Dubai', $row->order_placed_date, 'j M Y');

            $status = 'Pending';
            if ( $row->vendor_commission_paid ) {
                $status = 'Paid';
            } elseif ($row->vendor_commission_request_withdrawal) {
                $status = 'Requested to Withdraw';
            }

            echo implode("\t", array($i, $row->order_no, $orderDate, number_format($row->total_sale, 2), number_format($row->earning, 2, '.', ','), number_format($row->khiat_commission, 2, '.', ','), $earnedDate, $status, $requestedDate, $paidDate)) . "\n";

            $i++;
        }

        exit;
    }

    public function payVendorEarning()
    {
        $order_id = (int) $this->input->post('order_id', true);
        $vendor_id = (int) $this->input->post('vendor_id', true);
        $status = "0";
        $message = "";

        $earning = $this->M_product->getVendorEarnings($vendor_id, $order_id);
        if ( $earning ) {
            $earning = $earning[0];

            if ( $earning->vendor_commission_paid ) {
                $message = "Already paid";
            } elseif (! $earning->vendor_commission_request_withdrawal ) {
                $message = "Vendor not requestd for withdrawal";
            } else {
                $status = $this->M_product->payVendorEarnings($vendor_id, $order_id);
            }
        }

        $data['status']     = $status;
        $data['message']    = $message;

        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }

    function updateServiceTypePriority()
    {
        $priority   =   $this->input->post('priority');
        $category_id   =   $this->input->post('category_id');
        $priority_column ='sort_order';


        $update =  $this->M_admin->updateServiceTypePriority($priority, $priority_column, $category_id);


        if ($update) {
            $status=1;
            $message="Priority updated.";
        } else {
            $status=0;
            $message="Priority not updated !";
        }
        echo json_encode(array('status'=>$status,'message'=>$message));
    }




    public function venderPaymentReport()
    {
        $condition = array("user_type" => "U");
        $data["user_list"] = $this->M_admin->venderPaymentReport($condition);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/vender_payment_report", $data);
        $this->load->view("admin/footer");
    }
    public function taxReport()
    {
        $condition = array("user_type" => "U");
        $data["user_list"] = $this->M_admin->getUsersCondition($condition);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/tax_report", $data);
        $this->load->view("admin/footer");
    }
    public function commissionReport()
    {
        $start_date = $this->input->get('sdate', true);
        $end_date = $this->input->get('edate', true);
        $condition = compact('start_date', 'end_date');

        $data["commission_list"] = $this->M_admin->commissionReport($condition);

        $khiat_commission = 0;
        $vendor_commission = 0;
        if (! empty($data["commission_list"]) ) {
            $khiat_commission = array_sum(array_column($data["commission_list"], 'sum'));
            $vendor_commission = array_sum(array_column($data["commission_list"], 'vendor_commission'));
        }
        $data["khiat_commission"]  = $khiat_commission;
        $data["vendor_commission"] = $vendor_commission;
        $data["start_date"] = $start_date;
        $data["end_date"] = $end_date;

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/commission_report", $data);
        $this->load->view("admin/footer");
    }

    public function commissionReportDownload()
    {
        $start_date = $this->input->get('sdate', true);
        $end_date = $this->input->get('edate', true);
        $condition = compact('start_date', 'end_date');

        $data["commission_list"] = $this->M_admin->commissionReport($condition);

        $option = $this->uri->segment(4);

        if ($option == 1) {
            $this->load->library('Fpdf_gen');
            $this->fpdf = new FPDF();
            $this->fpdf->addPage('L');
            $this->fpdf->SetFont('Arial', 'B', 14);
            $this->fpdf->SetFillColor(193, 229, 252);

            $width_cell     = array(20, 40, 80, 80, 20, 40);
            $total_width    = array_sum($width_cell);

            $report_title = SITE_NAME.' Commission Report As On - ' . date('Y-m-d');
            if ( !empty($start_date) || !empty($end_date) ) {
                if ( !empty($start_date) && !empty($end_date) ) {
                    $report_title = SITE_NAME." Commission Report From {$start_date} To {$end_date}";
                } elseif ( !empty($start_date) ) {
                    $report_title = SITE_NAME." Commission Report From {$start_date}";
                } else {
                    $report_title = SITE_NAME." Commission Report Upto {$end_date}";
                }
            }

            $this->fpdf->Cell($total_width, 10, $report_title, 1, 1, C, true);

            $this->fpdf->SetFont('Arial', 'B', 12);

            $this->fpdf->SetFillColor(193, 229, 252); // Background color of header
            // Header starts ///
            $this->fpdf->Cell($width_cell[0], 10, 'Sl No', 1, 0, C, true);
            $this->fpdf->Cell($width_cell[1], 10, 'Order No', 1, 0, C, true);
            $this->fpdf->Cell($width_cell[2], 10, 'Store', 1, 0, C, true);
            $this->fpdf->Cell($width_cell[3], 10, 'Product Name', 1, 0, C, true);
            $this->fpdf->Cell($width_cell[4], 10, 'Qty', 1, 0, C, true);
            $this->fpdf->Cell($width_cell[5], 10, SITE_NAME.' Commission', 1, 0, C, true);

            $this->fpdf->SetFont('Arial', '', 10);

            if (count($data["commission_list"]) > 0) {
                $this->fpdf->SetFont('Arial', '', 10);
                $i = 1;
                $total = 0;
                $total2 = 0;
                foreach ($data["commission_list"] as $rows) {
                    $this->fpdf->Cell($width_cell[0], 10, $i, 1, 0, C, false); // First header column
                    $this->fpdf->Cell($width_cell[1], 10, $rows['order_no'], 1, 0, C, false);
                    $this->fpdf->Cell($width_cell[2], 10, $rows['store_name'], 1, 0, C, false); // Second header column
                    $this->fpdf->Cell($width_cell[3], 10, substr($rows['product_name'], 0, 25), 1, 0, C, false); // Third header column
                    $this->fpdf->Cell($width_cell[4], 10, $rows['purchase_qty'], 1, 0, C, false); // First header column
                    $this->fpdf->Cell($width_cell[5], 10, $rows['sum'], 1, 0, C, false); // Second header column

                    $total = $total + $rows['sum'];
                    // $total2 = $total2 + $rows['sum2'];
                    $i++;
                }

                $this->fpdf->Cell(240, 10, 'Total', 1, 0, C, false);
                $this->fpdf->Cell(40, 10, $total, 1, 0, C, false);
                // $this->fpdf->Cell(50, 10, $total2, 1, 0, C, false);
            }

            echo $this->fpdf->Output(SITE_NAME.'_commission_report_on_' . date('Y_m_d') . '.pdf', 'D');
        } else {
            $fileName = SITE_NAME.'_commission_report_on_' . date('Y_m_d');
            if ( !empty($start_date) || !empty($end_date) ) {
                if ( !empty($start_date) && !empty($end_date) ) {
                    $fileName = SITE_NAME."_commission_report_from_{$start_date}_to_{$end_date}";
                } elseif ( !empty($start_date) ) {
                    $fileName = SITE_NAME."_commission_report_from_{$start_date}";
                } else {
                    $fileName = SITE_NAME."_commission_report_upto_{$end_date}";
                }
            }

            $fileName = $fileName . '.xls';

            // headers for download
            header("Content-Disposition: attachment; filename=\"$fileName\"");
            header("Content-Type: application/vnd.ms-excel");

            function filterData(&$str)
            {
                $str = preg_replace("/\t/", "\\t", $str);
                $str = preg_replace("/\r?\n/", "\\n", $str);
                if (strstr($str, '"')) {
                    $str = '"' . str_replace('"', '""', $str) . '"';
                }
            }

            // file name for download
            // $fileName = "vendor_payment_report_on" . date('Ymd') . ".xls";

            // headers for download
            header("Content-Disposition: attachment; filename=\"$fileName\"");
            header("Content-Type: application/vnd.ms-excel");

            $flag = false;
            $i = 1;

            $order_delivery_statuses = $this->config->item('order_delivery_statuses', 'app');
            foreach ($data["commission_list"] as $row) {
                if (!$flag) {
                    // display column names as first row
                    echo implode("\t", array('Sl', 'Order No', 'Date', 'Order Status', 'Store', 'Product', 'Customer', 'Qty', 'Sale Price', 'Sale Price w/o VAT', SITE_NAME. ' Commission', 'Vendor Commission', 'VAT', 'Grand Total')) . "\n";
                    $flag = true;
                }
                // filter data
                array_walk($row, 'filterData');

                $order_date = get_date_in_timezone('Asia/Dubai', $row['order_placed_date'], 'j M Y');

                $name = $row['store_name'];
                echo implode("\t", array($i, $row['order_no'], $order_date, $order_delivery_statuses[$row['deliver_status']][1], $name, $row['product_name'], $row['cusfname'].' '.$rows['cuslname'], $row['purchase_qty'], $row['sub_total'], ($row['sub_total'] - $row['product_total_tax']), $row['sum'], $row['vendor_commission'], $row['product_total_tax'], $row['grand_total'])) . "\n";

                $i++;
            }

            exit;
        }
    }

    //Banner Images
    public function bannerList()
    {
        $data["brand_list"] = $this->M_admin->getBannerList();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/banner_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditBanner()
    {
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_banner");
        $this->load->view("admin/footer");
    }

    public function saveBanner()
    {

        if ($_FILES["txtFile"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFile"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'banner/';
            $config2['allowed_types'] = 'gif|jpg|png|pdf|doc';
            $config2['max_size'] = 2000;
            $config2['max_width'] = 2000;
            $config2['max_height'] = 1200;
            $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('txtFile')) {
                // die("file upload failed");
                $data['status'] = 0;
                $data['errors'] = array(
                    'txtFile' => "File upload failed",
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['bi_image'] = $config2['file_name'];
            }
        }

        $inputArray['bi_name'] = ucfirst($_POST['txtEnglish']);
        $inputArray['bi_target'] = $_POST['txtTarget'];
        $inputArray['bi_url'] = $_POST['txtURL'];
        $inputArray['bi_language_code'] = 1;
        $inputArray['bi_status'] = $_POST['txtStatus'];
        $inputArray['bi_created_date'] = gmdate("Y-m-d H:i:s");
        $inputArray2 = $inputArray;
        $inputArray2['bi_name'] = ($_POST['txtArabic'] != "" ? $_POST['txtArabic'] : $_POST['txtEnglish']);
        $inputArray2['bi_language_code'] = 2;

        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['bi_id'] = $_POST['id'];
            $inputArray2['bi_id'] = $_POST['id'];
            unset($inputArray['bicreated_date']);
            //    unset($inputArray2['bicreated_date']);
        }

        //  print_r($inputArray);
        $inputArray = $this->security->xss_clean($inputArray);
        $inputArray2 = $this->security->xss_clean($inputArray2);

        $result = $this->M_admin->saveMasterTable($inputArray, $inputArray2, 'bi_id', 'bi_language_code', 'banner_images');

        $data['status'] = $result;
        echo json_encode($data);
    }

    public function deleteBanner()
    {
        $id = $_POST['id'];

        echo $this->M_admin->deleteBanner($id);
    }

    //App Home banner

    public function appHomeBannerList()
    {
        $data["brand_list"] = $this->M_admin->getAppHomeBannerList();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/apphomebanner_list", $data);
        $this->load->view("admin/footer");
    }

    //App Home banner edit
    public function addEditAppHomeBanner()
    {
        //get all products with attribute id
        $data['product_list'] = $this->M_admin->getAllProductList();
        $data['category_list'] = $this->M_admin->getAllCategoryList();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_apphomebanner", $data);
        $this->load->view("admin/footer");
    }

    public function saveAppHomeBanner()
    {

        if ($_FILES["txtFile"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFile"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'banner/';
            $config2['allowed_types'] = 'gif|jpg|png|pdf|doc';
            $config2['max_size'] = 2000;
            $config2['max_width'] = 2000;
            $config2['max_height'] = 1200;
            $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('txtFile')) {
                // die("file upload failed");
                $data['status'] = 0;
                $data['errors'] = array(
                    'txtFile' => "File upload failed",
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['ahop_image'] = $config2['file_name'];
            }
        }

        $inputArray['ahop_name'] = ucfirst($_POST['txtEnglish']);
        $inputArray['ahop_target'] = $_POST['txtTarget'];
        $inputArray['ahop_url'] = $_POST['txtURL'];
        $inputArray['ahop_language_code'] = 1;
        $inputArray['ahop_status'] = $_POST['txtStatus'];
        $inputArray['ahop_created_date'] = gmdate("Y-m-d H:i:s");
        $inputArray['ahop_type'] = $_POST['txtTarget'];
        if ($_POST['txtTarget'] == 1) {
            $inputArray['ahop_type_id'] = $_POST['txtProduct'];
        } else {
            $inputArray['ahop_type_id'] = $_POST['txtCategory'];
        }
        $inputArray2 = $inputArray;
        $inputArray2['ahop_name'] = ($_POST['txtArabic'] != "" ? $_POST['txtArabic'] : $_POST['txtEnglish']);
        $inputArray2['ahop_language_code'] = 2;

        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['ahop_id'] = $_POST['id'];
            $inputArray2['ahop_id'] = $_POST['id'];
            unset($inputArray['bicreated_date']);
            //    unset($inputArray2['bicreated_date']);
        }

        //  print_r($inputArray);
        $inputArray = $this->security->xss_clean($inputArray);
        $inputArray2 = $this->security->xss_clean($inputArray2);

        $result = $this->M_admin->saveMasterTable($inputArray, $inputArray2, 'ahop_id', 'ahop_language_code', 'app_homer_offer_popup');

        $data['status'] = $result;
        echo json_encode($data);
    }

    //Slider Images
    public function sliderList()
    {
        $data["brand_list"] = $this->M_admin->getSliderList();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/slider_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditSlider()
    {
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_slider");
        $this->load->view("admin/footer");
    }

    public function saveSlider()
    {

        $data = array();

        $this->form_validation->set_rules('txtEnglish', 'Slider Name English', 'trim|required');
        $this->form_validation->set_rules('txtArabic', 'Slider Name Arabic', 'trim|required');
        //$this->form_validation->set_rules('txtURL', 'Slider url', 'trim|required');

        if ($_POST['id'] <= 0 && empty($_FILES['txtFile']['name'])) {
            $this->form_validation->set_rules('txtFile', 'Slider image', 'required');
        }

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txtEnglish' => form_error('txtEnglish'),
                'txtArabic' => form_error('txtArabic'),
                'txtURL' => form_error('txtURL'),
                'txtFile' => form_error('txtFile'),
            );
            echo json_encode($data);
            exit();
        }

        if ($_FILES["txtFile"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFile"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'banner/';
            $config2['allowed_types'] = 'gif|jpg|png|pdf|doc';
            // $config2['max_size'] = 2000;
            //$config2['max_width'] = 2000;
            //$config2['max_height'] = 1200;
            $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('txtFile')) {
                //die("file upload failed");
                $data['status'] = 0;
                $data['errors'] = array(
                    'txtFile' => strip_tags($this->upload->display_errors()),
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['si_image'] = $config2['file_name'];
            }
        }

        $inputArray['si_name'] = ucfirst($_POST['txtEnglish']);
        $inputArray['si_target'] = $_POST['txtTarget'];
        $inputArray['si_url'] = $_POST['txtURL'];
        $inputArray['si_language_code'] = 1;
        $inputArray['si_status'] = $_POST['txtStatus'];
        $inputArray['si_created_date'] = gmdate("Y-m-d H:i:s");
        $inputArray2 = $inputArray;
        $inputArray2['si_name'] = ($_POST['txtArabic'] != "" ? $_POST['txtArabic'] : $_POST['txtEnglish']);
        $inputArray2['si_language_code'] = 2;

        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['si_id'] = $_POST['id'];
            $inputArray2['si_id'] = $_POST['id'];
            unset($inputArray['si_created_date']);
            //    unset($inputArray2['bicreated_date']);
        }

        //  print_r($inputArray);

        $inputArray = $this->security->xss_clean($inputArray);
        $inputArray2 = $this->security->xss_clean($inputArray2);

        $result = $this->M_admin->saveMasterTable($inputArray, $inputArray2, 'si_id', 'si_language_code', 'slider_images');

        $data['status'] = $result;
        echo json_encode($data);
    }

    public function deleteSlider()
    {
        $id = $_POST['id'];
        echo $this->M_admin->deleteSlider($id);
    }

    //Dragon Slider Images

    public function dragonSliderList()
    {
        $data["brand_list"] = $this->M_admin->getDragonSliderList();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/dragon_slider_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditDragonSlider()
    {
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_dragon_slider");
        $this->load->view("admin/footer");
    }

    public function addEditDragonSliderApp()
    {
        $data['product_list'] = $this->M_admin->getAllProductList();
        $data['category_list'] = $this->M_admin->getAllCategoryList();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_dragon_slider_app", $data);
        $this->load->view("admin/footer");
    }

    public function saveDragonSlider()
    {

        $data = array();

        $this->form_validation->set_rules('txtEnglish', 'Slider Name English', 'trim|required');
        //$this->form_validation->set_rules('txtArabic', 'Slider Name Arabic', 'trim|required');
        $this->form_validation->set_rules('txtURL', 'Url', 'trim|required');

        if ($_POST['id'] <= 0 && empty($_FILES['txtFile']['name'])) {
            $this->form_validation->set_rules('txtFile', 'Slider image', 'required');
        }

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txtEnglish' => form_error('txtEnglish'),
                'txtArabic' => form_error('txtArabic'),
                'txtURL' => form_error('txtURL'),
                'txtFile' => form_error('txtFile'),

            );
            echo json_encode($data);
            exit();
        }

        if ($_FILES["txtFile"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFile"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'banner/';
            $config2['allowed_types'] = 'gif|jpg|png|pdf|doc';
            $config2['max_size'] = 2000;
            $config2['max_width'] = 2000;
            $config2['max_height'] = 1200;
            $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('txtFile')) {
                //die("file upload failed");
                $data['status'] = 0;
                $data['errors'] = array(
                    'txtFile' => "File upload failed",
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['dsi_image'] = $config2['file_name'];
            }
        }

        $inputArray['dsi_name'] = ucfirst($_POST['txtEnglish']);
        $inputArray['dsi_target'] = $_POST['txtTarget'];
        $inputArray['dsi_url'] = $_POST['txtURL'];
        $inputArray['dsi_language_code'] = 1;
        $inputArray['dsi_status'] = $_POST['txtStatus'];
        $inputArray['dsi_created_date'] = gmdate("Y-m-d H:i:s");
        $inputArray2 = $inputArray;
        $inputArray2['dsi_name'] = ($_POST['txtArabic'] != "" ? $_POST['txtArabic'] : $_POST['txtEnglish']);
        $inputArray2['dsi_language_code'] = 2;

        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['dsi_id'] = $_POST['id'];
            $inputArray2['dsi_id'] = $_POST['id'];
            unset($inputArray['dsi_created_date']);
            //    unset($inputArray2['bicreated_date']);
        }

        //  print_r($inputArray);

        $inputArray = $this->security->xss_clean($inputArray);
        $inputArray2 = $this->security->xss_clean($inputArray2);

        $result = $this->M_admin->saveMasterTable($inputArray, $inputArray2, 'dsi_id', 'dsi_language_code', 'dragon_slider_images');
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function saveDragonSliderApp()
    {

        $data = array();

        $this->form_validation->set_rules('txtEnglish', 'Slider Name English', 'trim|required');
        $this->form_validation->set_rules('txtArabic', 'Slider Name Arabic', 'trim|required');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txtEnglish' => form_error('txtEnglish'),
                'txtArabic' => form_error('txtArabic'),

            );
            echo json_encode($data);
            exit();
        }

        if ($_FILES["txtFile"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFile"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'banner/';
            $config2['allowed_types'] = 'gif|jpg|png|pdf|doc';
            $config2['max_size'] = 2000;
            $config2['max_width'] = 2000;
            $config2['max_height'] = 1200;
            $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('txtFile')) {
                //die("file upload failed");
                $data['status'] = 0;
                $data['errors'] = array(
                    'txtFile' => "File upload failed",
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['dsi_image'] = $config2['file_name'];
            }
        }

        $inputArray['dsi_name'] = ucfirst($_POST['txtEnglish']);
        $inputArray['dsi_target'] = $_POST['txtTarget'];
        $inputArray['dsi_url'] = $_POST['txtURL'];
        $inputArray['dsi_language_code'] = 1;
        $inputArray['dsi_status'] = $_POST['txtStatus'];
        $inputArray['dsi_created_date'] = gmdate("Y-m-d H:i:s");
        $inputArray2 = $inputArray;
        $inputArray2['dsi_name'] = ($_POST['txtArabic'] != "" ? $_POST['txtArabic'] : $_POST['txtEnglish']);
        $inputArray2['dsi_language_code'] = 2;

        if ($_POST['txtTarget'] == 1) {
            $inputArray['dsi_type_id'] = $_POST['txtProduct'];
        } else {
            $inputArray['dsi_type_id'] = $_POST['txtCategory'];
        }

        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['dsi_id'] = $_POST['id'];
            $inputArray2['dsi_id'] = $_POST['id'];
            unset($inputArray['dsi_created_date']);
            //    unset($inputArray2['bicreated_date']);
        }

        //  print_r($inputArray);


        $inputArray = $this->security->xss_clean($inputArray);
        $inputArray2 = $this->security->xss_clean($inputArray2);

        $result = $this->M_admin->saveMasterTable($inputArray, $inputArray2, 'dsi_id', 'dsi_language_code', 'dragon_slider_images_app');
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function deleteDragonSlider()
    {
        $id = $_POST['id'];
        echo $this->M_admin->deleteDragonSlider($id);
    }

    public function deleteDragonSliderApp()
    {
        $id = $_POST['id'];
        echo $this->M_admin->deleteDragonSliderApp($id);
    }

    public function listAppBannerList()
    {
        $data["brand_list"] = $this->M_admin->getBannerListApp();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/banner_list_app", $data);
        $this->load->view("admin/footer");
    }

    public function listAppOfferBannerList()
    {
        $data["brand_list"] = $this->M_admin->getAppOfferBannerList();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/dragon_offer_banner_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditDragonOfferBanner()
    {
        $data['product_list'] = $this->M_admin->getAllProductList();
        $data['category_list'] = $this->M_admin->getAllCategoryList();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_dragon_offer_banner_app", $data);
        $this->load->view("admin/footer");
    }

    public function addEditAppBanner()
    {
        $data['product_list'] = $this->M_admin->getAllProductList();
        $data['category_list'] = $this->M_admin->getAllCategoryList();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_banner_app", $data);
        $this->load->view("admin/footer");
    }

    public function saveBannerApp()
    {

        $data = array();

        $this->form_validation->set_rules('txtEnglish', 'Country Name English', 'trim|required');
        $this->form_validation->set_rules('txtArabic', 'Country Name Arabic', 'trim|required');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txtEnglish' => form_error('txtEnglish'),
                'txtArabic' => form_error('txtArabic'),

            );
            echo json_encode($data);
            exit();
        }

        if ($_FILES["txtFile"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFile"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'banner/';
            $config2['allowed_types'] = 'gif|jpg|png|pdf|doc';
            $config2['max_size'] = 2000;
            $config2['max_width'] = 2000;
            $config2['max_height'] = 1200;
            $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('txtFile')) {
                //die("file upload failed");
                $data['status'] = 0;
                $data['errors'] = array(
                    'txtFile' => "File upload failed",
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['bi_image'] = $config2['file_name'];
            }
        }

        $inputArray['bi_name'] = ucfirst($_POST['txtEnglish']);
        $inputArray['bi_target'] = $_POST['txtTarget'];
        $inputArray['bi_url'] = $_POST['txtURL'];
        $inputArray['bi_language_code'] = 1;
        $inputArray['bi_status'] = $_POST['txtStatus'];
        $inputArray['bi_created_date'] = gmdate("Y-m-d H:i:s");
        $inputArray2 = $inputArray;
        $inputArray2['bi_name'] = ($_POST['txtArabic'] != "" ? $_POST['txtArabic'] : $_POST['txtEnglish']);
        $inputArray2['bi_language_code'] = 2;

        if ($_POST['txtTarget'] == 1) {
            $inputArray['bi_type_id'] = $_POST['txtProduct'];
        } else {
            $inputArray['bi_type_id'] = $_POST['txtCategory'];
        }

        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['bi_id'] = $_POST['id'];
            $inputArray2['bi_id'] = $_POST['id'];
            unset($inputArray['bicreated_date']);
            //    unset($inputArray2['bicreated_date']);
        }

        //  print_r($inputArray);
        /**
         * changes by jitin on 27 sep 18 for xss filtering
         */
        $inputArray = $this->security->xss_clean($inputArray);
        $inputArray2 = $this->security->xss_clean($inputArray2);

        $result = $this->M_admin->saveMasterTable($inputArray, $inputArray2, 'bi_id', 'bi_language_code', 'banner_images_app');
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function saveDragonOfferbannerApp()
    {

        $data = array();

        if (empty($_FILES['txtFile']['name']) && $_POST['id'] <= 0) {
            $this->form_validation->set_rules('txtFile', 'Banner image', 'trim|required');
        }

        if (form_error('txtFile') != "") {
            $data['status'] = 0;
            $data['errors'] = array(
                'txtFile' => form_error('txtFile'),
            );
            echo json_encode($data);
            exit();
        }

        if ($_FILES["txtFile"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFile"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'banner/';
            $config2['allowed_types'] = 'gif|jpg|png|pdf|doc';
            $config2['max_size'] = 2000;
            $config2['max_width'] = 2000;
            $config2['max_height'] = 1200;
            $config2['file_name'] = 'off_' . $randomNo . "." . $file_ext2;

            //$this->load->library('upload', $config2);
            $this->load->library('upload', $config2);
            // $this->upload->initialize($config2);

            if (!$this->upload->do_upload('txtFile')) {
                //die("file upload failed");
                //echo $this->upload->display_errors();
                $data['status'] = 0;
                $data['errors'] = array(
                    'txtFile' => "File upload failed",
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['drag_offer_image'] = $config2['file_name'];
            }
        }

        $inputArray['drag_offer_url'] = $_POST['txtURL'];
        $inputArray['drag_offer_status'] = $_POST['txtStatus'];
        $inputArray['drag_offer_created_date'] = gmdate("Y-m-d H:i:s");

        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['drag_offer_ban_id'] = $_POST['id'];
            $inputArray2['bi_id'] = $_POST['id'];
            unset($inputArray['bicreated_date']);
            //    unset($inputArray2['bicreated_date']);
        }

        $inputArray = $this->security->xss_clean($inputArray);

        $result = $this->M_admin->saveMasterTable2($inputArray, 'drag_offer_ban_id', 'dragon_offer_banner');
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function listAppSlider()
    {
        $data["brand_list"] = $this->M_admin->getSliderListApp();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/slider_list_app", $data);
        $this->load->view("admin/footer");
    }

    public function addEditAppSlider()
    {
        $data['product_list'] = $this->M_admin->getAllProductList();
        $data['category_list'] = $this->M_admin->getAllCategoryList();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_slider_app", $data);
        $this->load->view("admin/footer");
    }
    public function saveAppSlider()
    {

        $data = array();

        //print_r($_POST);exit;
        $this->form_validation->set_rules('txtEnglish', 'Slider Name English', 'trim|required');
        //  $this->form_validation->set_rules('txtArabic', 'Slider Name Arabic', 'trim|required');

        if (empty($_FILES['txtFile']['name']) && $_POST['id'] <= 0) {
            $this->form_validation->set_rules('txtFile', 'Slider image', 'trim|required');
        }

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txtEnglish' => form_error('txtEnglish'),
                'txtArabic' => form_error('txtArabic'),
                'txtFile' => form_error('txtFile'),

            );
            echo json_encode($data);
            exit();
        }

        if ($_FILES["txtFile"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFile"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'banner/';
            $config2['allowed_types'] = 'gif|jpg|png';
            $config2['max_size'] = 3000;
            $config2['max_width'] = 3000;
            $config2['max_height'] = 3000;
            $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('txtFile')) {
                //die("file upload failed");
                $data['status'] = 3;
                $data['errors'] = array(
                    'txtFile' => strip_tags($this->upload->display_errors()),
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['si_image'] = $config2['file_name'];
            }
        }

        $inputArray['si_name'] = ucfirst($_POST['txtEnglish']);
        $inputArray['si_target'] = $_POST['txtTarget'];
        $inputArray['si_url'] = $_POST['txtURL'];
        $inputArray['si_language_code'] = 1;
        $inputArray['si_status'] = $_POST['txtStatus'];
        $inputArray['si_created_date'] = gmdate("Y-m-d H:i:s");

        // if ($_POST['txtTarget'] == 1) {
        //     $inputArray['si_type_id'] = $_POST['txtProduct'];
        // } else {
        //     $inputArray['si_type_id'] = $_POST['txtCategory'];
        // }

        $inputArray['si_type_id'] = $_POST['txtCategory'];
        $inputArray2 = $inputArray;
        $inputArray2['si_name'] = ($_POST['txtArabic'] != "" ? $_POST['txtArabic'] : $_POST['txtEnglish']);
        $inputArray2['si_language_code'] = 2;

        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['si_id'] = $_POST['id'];
            $inputArray2['si_id'] = $_POST['id'];
            unset($inputArray['si_created_date']);
            //    unset($inputArray2['bicreated_date']);
        }

        //  print_r($inputArray);

        $inputArray = $this->security->xss_clean($inputArray);
        $inputArray2 = $this->security->xss_clean($inputArray2);

        $result = $this->M_admin->saveMasterTable($inputArray, $inputArray2, 'si_id', 'si_language_code', 'slider_images_app');

        $data['status'] = $result;
        echo json_encode($data);
    }


    /*Offer slider */
    public function listofferSlider()
    {
        $data["brand_list"] = $this->M_admin->getOfferSliderListApp();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/offer_list_app", $data);
        $this->load->view("admin/footer");
    }

    public function addEditOfferSlider()
    {
        $data['product_list'] = $this->M_admin->getAllProductList();
        $data['category_list'] = $this->M_admin->getAllCategoryList();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_offer_slider_app", $data);
        $this->load->view("admin/footer");
    }
    public function saveOfferSlider()
    {

        $data = array();

        //print_r($_POST);exit;
        $this->form_validation->set_rules('txtEnglish', 'Slider Name English', 'trim|required');
        //  $this->form_validation->set_rules('txtArabic', 'Slider Name Arabic', 'trim|required');

        if (empty($_FILES['txtFile']['name']) && $_POST['id'] <= 0) {
            $this->form_validation->set_rules('txtFile', 'Slider image', 'trim|required');
        }

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txtEnglish' => form_error('txtEnglish'),
                'txtArabic' => form_error('txtArabic'),
                'txtFile' => form_error('txtFile'),

            );
            echo json_encode($data);
            exit();
        }

        if ($_FILES["txtFile"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFile"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'banner/';
            $config2['allowed_types'] = 'gif|jpg|png';
            $config2['max_size'] = 3000;
            $config2['max_width'] = 3000;
            $config2['max_height'] = 3000;
            $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('txtFile')) {
                //die("file upload failed");
                $data['status'] = 3;
                $data['errors'] = array(
                    'txtFile' => strip_tags($this->upload->display_errors()),
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['si_image'] = $config2['file_name'];
            }
        }

        $inputArray['si_name'] = ucfirst($_POST['txtEnglish']);
        $inputArray['si_target'] = $_POST['txtTarget'];
        $inputArray['si_url'] = $_POST['txtURL'];
        $inputArray['si_language_code'] = 1;
        $inputArray['si_status'] = $_POST['txtStatus'];
        $inputArray['si_created_date'] = gmdate("Y-m-d H:i:s");

        // if ($_POST['txtTarget'] == 1) {
        //     $inputArray['si_type_id'] = $_POST['txtProduct'];
        // } else {
        //     $inputArray['si_type_id'] = $_POST['txtCategory'];
        // }

        $inputArray['si_type_id'] = $_POST['txtCategory'];
        $inputArray2 = $inputArray;
        $inputArray2['si_name'] = ($_POST['txtArabic'] != "" ? $_POST['txtArabic'] : $_POST['txtEnglish']);
        $inputArray2['si_language_code'] = 2;

        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['si_id'] = $_POST['id'];
            $inputArray2['si_id'] = $_POST['id'];
            unset($inputArray['si_created_date']);
            //    unset($inputArray2['bicreated_date']);
        }

        //  print_r($inputArray);

        $inputArray = $this->security->xss_clean($inputArray);
        $inputArray2 = $this->security->xss_clean($inputArray2);

        $result = $this->M_admin->saveMasterTable($inputArray, $inputArray2, 'si_id', 'si_language_code', 'offer_banners_app');

        $data['status'] = $result;
        echo json_encode($data);
    }
    public function deleteOfferSlider()
    {
        $id = $_POST['id'];

        echo $this->M_admin->deleteOfferSlider($id);
    }
    //End
    public function CashPointDetails()
    {
        $id = $_POST['id'];

        $result = $this->M_admin->CashPointDetails($id);
        if (count($result) > 0) {
            $table = '<table class="table-responsive" border="1">';
            $table .= '<tr><td>Sl No</td><td>Product Name</td><td>Qty</td><td>Cash Points</td>';
            $i = 1;
            foreach ($result as $rows) {
                $table .= '<tr><td>' . $i . '</td><td>' . $rows['product_name'] . '</td><td>' . $rows['purchase_qty'] . '</td><td>' . $rows['sum'] . '</td>';
                $i++;
            }

            echo $table .= "</table>";
        }
    }

    public function venderPaymentDetails()
    {
        $id = $_POST['id'];

        $result = $this->M_admin->venderPaymentDetails($id);
        if (count($result) > 0) {
            $table = '<table class="table-responsive" border="1">';
            $table .= '<tr><td>Sl No</td><td>Product Name</td><td>Qty</td><td>Payment</td>';
            $i = 1;
            foreach ($result as $rows) {
                $table .= '<tr><td>' . $i . '</td><td>' . $rows['product_name'] . '</td><td>' . $rows['purchase_qty'] . '</td><td>' . $rows['sum'] . '</td>';
                $i++;
            }

            echo $table .= "</table>";
        }
    }

    public function pdfTesting()
    {
        $this->load->library('Fpdf_gen');

        $this->fpdf->SetFont('Arial', 'B', 16);
        $this->fpdf->Cell(40, 10, 'Hello World!');

        echo $this->fpdf->Output('hello_world.pdf', 'D');
    }

    public function CashPointDetailsDownload()
    {
        error_reporting(E_ALL);

        $option = $this->uri->segment(4);
        $user_list = $this->M_admin->getCashPointReports();

        require_once APPPATH.'third_party/php-excel/autoload.php';

        $spreadsheet    = new Spreadsheet();
        $sheet          = $spreadsheet->getActiveSheet();


        $sheet->setCellValue('A1', "Customer Name");
        $sheet->setCellValue('B1', "Earned Cash Points");
        $sheet->setCellValue('C1', "Earned Cash Points (AED)");
        $sheet->setCellValue('D1', "Used Cash Points");
        $sheet->setCellValue('E1', "Used Cash Points (AED)");
        $sheet->setCellValue('F1', "Balance Cash Points");
        $sheet->setCellValue('G1', "Balance Cash Points (AED)");


        $sheet->getColumnDimension('A')->setWidth(20);
        $sheet->getColumnDimension('B')->setWidth(20);
        $sheet->getColumnDimension('C')->setWidth(22);
        $sheet->getColumnDimension('D')->setWidth(20);
        $sheet->getColumnDimension('E')->setWidth(22);
        $sheet->getColumnDimension('F')->setWidth(20);
        $sheet->getColumnDimension('G')->setWidth(22);


        $row_index = 2;

        $total_points = 0;
        $total_points_aed = 0;

        foreach ($user_list as $key => $rows) {
            $balance_points = $rows->user_points- $rows->used_points;
            $balance_points_aed = $balance_points * $this->config->item("single_point_bc_value");

            $sheet->setCellValue('A'.($row_index ), $rows->user_first_name . " " . $rows->user_last_name);
            $sheet->setCellValue('B'.($row_index ), $rows->user_points);
            $sheet->setCellValue('C'.($row_index ), $rows->user_points * $this->config->item("single_point_bc_value"));
            $sheet->setCellValue('D'.($row_index ), $rows->used_points);
            $sheet->setCellValue('E'.($row_index ), $rows->used_points * $this->config->item("single_point_bc_value"));
            $sheet->setCellValue('F'.($row_index ), $balance_points);
            $sheet->setCellValue('G'.($row_index ), $balance_points_aed);

            $total_points       += $balance_points ;
            $total_points_aed   += $balance_points_aed ;

            $row_index++;
        }

        $sheet->setCellValue('E'.($row_index ), "Total");
        $sheet->setCellValue('F'.($row_index ), $total_points);
        $sheet->setCellValue('G'.($row_index ), $total_points_aed);

        $sheet->getStyle('E'.($row_index).':G'.($row_index))->getFont()->setBold(true);

        $spreadsheet->getProperties()->setCreator('monsterremit')
                                    ->setLastModifiedBy('monsterremit')
                                    ->setTitle('Sender Details')
                                    ->setSubject('Sender List')
                                    ->setDescription('')
                                    ->setKeywords('')
                                    ->setCategory('');


        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="Cash Points List -'.date('Y').'.xlsx"');
        header('Cache-Control: max-age=0');

        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public');


        $writer = new Xlsx($spreadsheet);
        $writer->setPreCalculateFormulas(false);
        $writer->save('php://output');

        // if ($option == 1) {

        //     $this->load->library('Fpdf_gen');

        //     $this->fpdf->SetFont('Arial', 'B', 14);
        //     $this->fpdf->SetFillColor(193, 229, 252);
        //     $this->fpdf->Cell(180, 10, 'Cash Point Report As On - ' . date('Y-m-d'), 1, 1, C, true);
        //     $this->fpdf->SetFont('Arial', 'B', 12);

        //     $width_cell = array(30, 80, 70);
        //     $this->fpdf->SetFillColor(193, 229, 252); // Background color of header
        //     // Header starts ///
        //     $this->fpdf->Cell($width_cell[0], 10, 'ID', 1, 0, C, true); // First header column
        //     $this->fpdf->Cell($width_cell[1], 10, 'Customer Name', 1, 0, C, true); // Second header column
        //     $this->fpdf->Cell($width_cell[2], 10, 'Total Cash points', 1, 1, C, true); // Third header column

        //     $this->fpdf->SetFont('Arial', '', 10);

        //     if (count($data["user_list"]) > 0) {
        //         $this->fpdf->SetFont('Arial', '', 10);
        //         $i = 1;
        //         $total = 0;
        //         foreach ($data["user_list"] as $rows) {
        //             $this->fpdf->Cell($width_cell[0], 10, $rows['user_id'], 1, 0, C, false); // First header column
        //             $this->fpdf->Cell($width_cell[1], 10, $rows['user_first_name'] . " " . $rows['user_last_name'], 1, 0, C, false); // Second header column
        //             $this->fpdf->Cell($width_cell[2], 10, $rows['sum'], 1, 1, C, false); // Third header column

        //             $total = $total + $rows['sum'];
        //             $i++;
        //         }

        //         $this->fpdf->Cell(110, 10, 'Total', 1, 0, C, false);
        //         $this->fpdf->Cell(70, 10, $total, 1, 1, C, false);
        //     }

        //     echo $this->fpdf->Output('cash_point_report_on' . date('Y_m_d') . '.pdf', 'D');

        // }
        // else {

        //     $fileName = 'cash_point_report_on' . date('Y_m_d') . '.xls';
        //     // headers for download
        //     header("Content-Disposition: attachment; filename=\"$fileName\"");
        //     header("Content-Type: application/vnd.ms-excel");

        //     function filterData(&$str)
        //     {
        //         $str = preg_replace("/\t/", "\\t", $str);
        //         $str = preg_replace("/\r?\n/", "\\n", $str);
        //         if (strstr($str, '"')) {
        //             $str = '"' . str_replace('"', '""', $str) . '"';
        //         }

        //     }

        //     // file name for download
        //     // $fileName = "codexworld_export_data" . date('Ymd') . ".xls";

        //     // headers for download
        //     header("Content-Disposition: attachment; filename=\"$fileName\"");
        //     header("Content-Type: application/vnd.ms-excel");

        //     $flag = false;

        //     $total = 0;
        //     foreach ($data["user_list"] as $row) {
        //         if (!$flag) {
        //             // display column names as first row
        //             echo implode("\t", array('Id', 'Name', 'Total Cash Points')) . "\n";
        //             $flag = true;
        //         }
        //         // filter data
        //         array_walk($row, 'filterData');

        //         $name = $row['user_first_name'] . " " . $row['user_last_name'];
        //         echo implode("\t", array($row['user_id'], $name, $row['sum'])) . "\n";
        //         $total = $total + $row['sum'];
        //     }
        //     echo implode("\t", array('Total', '', $total)) . "\n";
        //     exit;

        // }
    }

    public function vendorPaymentDetailsDownload()
    {

        $option = $this->uri->segment(4);
        $data["user_list"] = $this->M_admin->venderPaymentReport();

        if ($option == 1) {
            $this->load->library('Fpdf_gen');

            $this->fpdf->SetFont('Arial', 'B', 14);
            $this->fpdf->SetFillColor(193, 229, 252);
            $this->fpdf->Cell(180, 10, 'Vendor Payment Report As On - ' . date('Y-m-d'), 1, 1, C, true);

            $this->fpdf->SetFont('Arial', 'B', 12);

            $width_cell = array(30, 80, 70);
            $this->fpdf->SetFillColor(193, 229, 252); // Background color of header
            // Header starts ///
            $this->fpdf->Cell($width_cell[0], 10, 'ID', 1, 0, C, true); // First header column
            $this->fpdf->Cell($width_cell[1], 10, 'Customer Name', 1, 0, C, true); // Second header column
            $this->fpdf->Cell($width_cell[2], 10, 'Total Payments', 1, 1, C, true); // Third header column

            $this->fpdf->SetFont('Arial', '', 10);

            if (count($data["user_list"]) > 0) {
                $this->fpdf->SetFont('Arial', '', 10);
                $i = 1;
                $total = 0;
                foreach ($data["user_list"] as $rows) {
                    $this->fpdf->Cell($width_cell[0], 10, $rows['user_id'], 1, 0, C, false); // First header column
                    $this->fpdf->Cell($width_cell[1], 10, $rows['user_first_name'] . " " . $rows['user_last_name'], 1, 0, C, false); // Second header column
                    $this->fpdf->Cell($width_cell[2], 10, $rows['sum'], 1, 1, C, false); // Third header column

                    $total = $total + $rows['sum'];
                    $i++;
                }

                $this->fpdf->Cell(110, 10, 'Total', 1, 0, C, false);
                $this->fpdf->Cell(70, 10, $total, 1, 1, C, false);
            }

            echo $this->fpdf->Output('vendor_payment_report_on' . date('Y_m_d') . '.pdf', 'D');
        } else {
            $fileName = 'vendor_payment_report_on' . date('Y_m_d') . '.xls';
            // headers for download
            header("Content-Disposition: attachment; filename=\"$fileName\"");
            header("Content-Type: application/vnd.ms-excel");

            function filterData(&$str)
            {
                $str = preg_replace("/\t/", "\\t", $str);
                $str = preg_replace("/\r?\n/", "\\n", $str);
                if (strstr($str, '"')) {
                    $str = '"' . str_replace('"', '""', $str) . '"';
                }
            }

            // file name for download
            // $fileName = "vendor_payment_report_on" . date('Ymd') . ".xls";

            // headers for download
            header("Content-Disposition: attachment; filename=\"$fileName\"");
            header("Content-Type: application/vnd.ms-excel");

            $flag = false;
            foreach ($data["user_list"] as $row) {
                if (!$flag) {
                    // display column names as first row
                    echo implode("\t", array('Id', 'Name', 'Total Payments')) . "\n";
                    $flag = true;
                }
                // filter data
                array_walk($row, 'filterData');

                $name = $row['user_first_name'] . " " . $row['user_last_name'];
                echo implode("\t", array($row['user_id'], $name, $row['sum'])) . "\n";
            }

            exit;
        }
    }

    public function userReportDownLoad()
    {
        $type = $this->uri->segment(5);
        $this->load->library('Fpdf_gen');
        $this->fpdf->SetFont('Arial', 'B', 14);
        $this->fpdf->SetFillColor(193, 229, 252);

        if ($type == 1) {
            $condition = array("user_type" => "O");
            $pdfFileName = 'customer_report_on' . date('Y_m_d') . '.pdf';
            $fileName = 'customer_report_on' . date('Y_m_d') . '.xls';
            $data["user_list"] = $this->M_admin->getUsersCondition($condition);
            $this->fpdf->Cell(180, 10, 'Customer Report', 1, 1, C, true);
        } elseif ($type == 2) {
            $condition = array("user_type" => "V");
            $pdfFileName = 'vendor_report_on' . date('Y_m_d') . '.pdf';
            $fileName = 'vendor_report_on' . date('Y_m_d') . '.xls';
            $data["user_list"] = $this->M_admin->getUsersCondition($condition);
            $this->fpdf->Cell(180, 10, 'Vendor Report', 1, 1, C, true);
        } elseif ($type == 3) {
            $condition = array("user_type" => "D");
            $pdfFileName = 'driver_report_on' . date('Y_m_d') . '.pdf';
            $fileName = 'driver_report_on' . date('Y_m_d') . '.xls';
            $data["user_list"] = $this->M_admin->getDriverCondition();
            $this->fpdf->Cell(190, 10, 'Driver Report', 1, 1, C, true);
        } else {
            $condition = array("user_type" => "U");
            $pdfFileName = 'customer_report_on' . date('Y_m_d') . '.pdf';
            $fileName = 'customer_report_on' . date('Y_m_d') . '.xls';
            $data["user_list"] = $this->M_admin->getUsersCondition($condition);
            $this->fpdf->Cell(180, 10, 'Customer Report', 1, 1, C, true);
        }

        $option = $this->uri->segment(4);

        if ($option == 1) {
            $this->fpdf->SetFont('Arial', 'B', 12);

            if ($type == 3) {
                $width_cell = array(20, 30, 35, 20, 20);
            } else {
                $width_cell = array(20, 40, 40, 30);
            }

            $this->fpdf->SetFillColor(193, 229, 252); // Background color of header
            // Header starts ///
            $this->fpdf->Cell($width_cell[0], 10, 'Sl No', 1, 0, C, true); // First header column
            $this->fpdf->Cell($width_cell[1], 10, 'Name', 1, 0, C, true); // Second header column
            $this->fpdf->Cell($width_cell[2], 10, 'Email', 1, 0, C, true); // Third header column
            $this->fpdf->Cell($width_cell[0], 10, 'Phone', 1, 0, C, true);
            $this->fpdf->Cell($width_cell[1], 10, 'Country', 1, 0, C, true);
            if ($type == 3) {
                $this->fpdf->Cell($width_cell[2], 10, 'Vehicle No', 1, 0, C, true);
            }
            $this->fpdf->Cell($width_cell[0], 10, 'Status', 1, 1, C, true);
            $this->fpdf->SetFont('Arial', '', 10);

            if (count($data["user_list"]) > 0) {
                $this->fpdf->SetFont('Arial', '', 7.5);
                $i = 1;
                foreach ($data["user_list"] as $rows) {
                    $user_country= $this->M_admin->getCountries($language=1, $rows->user_country_id);
                    $this->fpdf->Cell($width_cell[0], 10, $i, 1, 0, C, false); // First header column
                    $this->fpdf->Cell($width_cell[1], 10, $rows->user_first_name != "" ?$rows->user_first_name . ' ' . $rows->user_last_name :"NA", 1, 0, C, false); // Second header column
                    $this->fpdf->Cell($width_cell[2], 10, $rows->user_email_id, 1, 0, C, false); // Third header column
                    $this->fpdf->Cell($width_cell[0], 10, $rows->phone_number != "" ? $rows->dial_code." ".$rows->phone_number : 'NA', 1, 0, C, false);
                    $this->fpdf->Cell($width_cell[1], 10,  $user_country->country_name != "" ? $user_country->country_name : 'NA', 1, 0, C, false);
                    if ($type == 3) {
                        $this->fpdf->Cell($width_cell[2], 10, $rows->vehicle_no, 1, 0, C, false);
                    }
                    $this->fpdf->Cell($width_cell[0], 10, $rows->user_status == 1 ? "Active" : "Inactive", 1, 1, C, false);
                    $i++;
                }
            }

            echo $this->fpdf->Output($pdfFileName, 'D');
        } else {
            //$fileName = 'user_report_on'.date('Y_m_d').'.xls';
            // headers for download
            header("Content-Disposition: attachment; filename=\"$fileName\"");
            header("Content-Type: application/vnd.ms-excel");

            function filterData(&$str)
            {
                $str = preg_replace("/\t/", "\\t", $str);
                $str = preg_replace("/\r?\n/", "\\n", $str);
                if (strstr($str, '"')) {
                    $str = '"' . str_replace('"', '""', $str) . '"';
                }
            }

            // file name for download
            // $fileName = "vendor_payment_report_on" . date('Ymd') . ".xls";

            // headers for download
            header("Content-Disposition: attachment; filename=\"$fileName\"");
            header("Content-Type: application/vnd.ms-excel");

            $flag = false;
            $i = 1;
            foreach ($data["user_list"] as $row) {
                $user_country= $this->M_admin->getCountries($language=1, $row->user_country_id);

                if (!$flag) {
                    // display column names as first row
                    echo implode("\t", array('Sl no', 'Name', 'Email ', 'Phone','Country', 'Status')) . "\n";
                    $flag = true;
                }
                // filter data
                array_walk($row, 'filterData');

                $name = $row->user_first_name . ' ' . $row->user_last_name;
                echo implode("\t", array($i, $row->user_first_name != "" ?$row->user_first_name . ' ' . $row->user_last_name :"NA", $row->user_email_id, $row->phone_number != "" ? $row->dial_code." ".$row->phone_number : 'NA',$user_country->country_name != "" ? $user_country->country_name : 'NA', $row->user_status == 1 ? "Active" : "Inactive")) . "\n";
                $i++;
            }

            exit;
        }
    }

    public function khiatCommissionReportDownload()
    {
        $condition = array("user_type" => "U");
        $data["user_list"] = $this->M_admin->teyaarCommissionReport($condition);

        $option = $this->uri->segment(4);

        if ($option == 1) {
            $this->load->library('Fpdf_gen');
            $this->fpdf = new FPDF();
            $this->fpdf->addPage('L');
            $this->fpdf->SetFont('Arial', 'B', 14);
            $this->fpdf->SetFillColor(193, 229, 252);

            $width_cell     = array(20, 40, 80, 80, 20, 40);
            $total_width    = array_sum($width_cell);
            $this->fpdf->Cell($total_width, 10, SITE_NAME.' Commission Report As On - ' . date('Y-m-d'), 1, 1, C, true);

            $this->fpdf->SetFont('Arial', 'B', 12);

            $this->fpdf->SetFillColor(193, 229, 252); // Background color of header
            // Header starts ///
            $this->fpdf->Cell($width_cell[0], 10, 'Sl No', 1, 0, C, true);
            $this->fpdf->Cell($width_cell[1], 10, 'Order No', 1, 0, C, true);
            $this->fpdf->Cell($width_cell[2], 10, 'Store', 1, 0, C, true);
            $this->fpdf->Cell($width_cell[3], 10, 'Product Name', 1, 0, C, true);
            $this->fpdf->Cell($width_cell[4], 10, 'Qty', 1, 0, C, true);
            $this->fpdf->Cell($width_cell[5], 10, SITE_NAME.' Commission', 1, 0, C, true);

            $this->fpdf->SetFont('Arial', '', 10);

            if (count($data["user_list"]) > 0) {
                $this->fpdf->SetFont('Arial', '', 10);
                $i = 1;
                $total = 0;
                $total2 = 0;
                foreach ($data["user_list"] as $rows) {
                    $this->fpdf->Cell($width_cell[0], 10, $i, 1, 0, C, false); // First header column
                    $this->fpdf->Cell($width_cell[1], 10, $rows['order_no'], 1, 0, C, false);
                    $this->fpdf->Cell($width_cell[2], 10, $rows['user_first_name'] . " " . $rows['user_last_name'], 1, 0, C, false); // Second header column
                    $this->fpdf->Cell($width_cell[3], 10, substr($rows['product_name'], 0, 25), 1, 0, C, false); // Third header column
                    $this->fpdf->Cell($width_cell[4], 10, $rows['purchase_qty'], 1, 0, C, false); // First header column
                    $this->fpdf->Cell($width_cell[5], 10, $rows['sum'], 1, 0, C, false); // Second header column

                    $total = $total + $rows['sum'];
                    // $total2 = $total2 + $rows['sum2'];
                    $i++;
                }

                $this->fpdf->Cell(240, 10, 'Total', 1, 0, C, false);
                $this->fpdf->Cell(40, 10, $total, 1, 0, C, false);
                // $this->fpdf->Cell(50, 10, $total2, 1, 0, C, false);
            }

            echo $this->fpdf->Output(SITE_NAME.'_commission_report_on_' . date('Y_m_d') . '.pdf', 'D');
        } else {
            $fileName = SITE_NAME.'_commission_report_on_' . date('Y_m_d') . '.xls';
            // headers for download
            header("Content-Disposition: attachment; filename=\"$fileName\"");
            header("Content-Type: application/vnd.ms-excel");

            function filterData(&$str)
            {
                $str = preg_replace("/\t/", "\\t", $str);
                $str = preg_replace("/\r?\n/", "\\n", $str);
                if (strstr($str, '"')) {
                    $str = '"' . str_replace('"', '""', $str) . '"';
                }
            }

            // file name for download
            // $fileName = "vendor_payment_report_on" . date('Ymd') . ".xls";

            // headers for download
            header("Content-Disposition: attachment; filename=\"$fileName\"");
            header("Content-Type: application/vnd.ms-excel");

            $flag = false;
            $i = 1;
            foreach ($data["user_list"] as $row) {
                if (!$flag) {
                    // display column names as first row
                    echo implode("\t", array('Sl', 'Order No', 'Store', 'Product name', 'Qty', SITE_NAME. ' Commission')) . "\n";
                    $flag = true;
                }
                // filter data
                array_walk($row, 'filterData');

                $name = $row['user_first_name'] . " " . $row['user_last_name'];
                echo implode("\t", array($i, $row['order_no'], $name, $row['product_name'], $row['purchase_qty'], $row['sum'])) . "\n";

                $i++;
            }

            exit;
        }
    }

    public function deleteAppSlider()
    {
        $id = $_POST['id'];

        echo $this->M_admin->deleteAppSlider($id);
    }

    public function dragonSliderListApp()
    {
        $data["brand_list"] = $this->M_admin->getDragonSliderListApp();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/dragon_slider_list_app", $data);
        $this->load->view("admin/footer");
    }

    public function deleteDragonOfferBannerApp()
    {
        $id = $_POST['id'];

        echo $this->M_admin->deleteDragonOfferBannerApp($id);
    }

    public function listDragonAppProfileImage()
    {
        $data["brand_list"] = $this->M_admin->getDragonProfileListApp();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/dragon_profile_app_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditDragonProfileImage()
    {
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_dragon_profile_image");
        $this->load->view("admin/footer");
    }

    public function saveDragonProfileImageApp()
    {

        $data = array();

        if (empty($_FILES['txtFile']['name'])) {
            $this->form_validation->set_rules('txtFile', 'Profile image', 'trim|required');
            if ($this->form_validation->run() == false) {
                $data['status'] = 0;
                $data['errors'] = array(
                    'txtFile' => form_error('txtFile'),
                );
                echo json_encode($data);
                exit();
            }
        }

        if ($_FILES["txtFile"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFile"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'banner/';
            $config2['allowed_types'] = 'gif|jpg|png|pdf|doc';
            $config2['max_size'] = 2000;
            $config2['max_width'] = 2000;
            $config2['max_height'] = 1200;
            $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('txtFile')) {
                //die("file upload failed");
                $data['status'] = 0;
                $data['errors'] = array(
                    'txtFile' => "File upload failed",
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['image_name'] = $config2['file_name'];
            }
            $inputArray['created_date	'] = gmdate("Y-m-d H:i:s");
            $inputArray['status'] = 1;

            /**
             * changes by jitin on 27 sep 18 for xss filtering
             */
            $inputArray = $this->security->xss_clean($inputArray);

            $result = $this->M_admin->saveDragonProfile($inputArray);

            $data['status'] = $result;
            echo json_encode($data);
        }
    }

    public function loadAdminBasicForm()
    {
        $data["admin_basics"] = $this->M_admin->getAdminBasics();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_admin_deatils", $data);
        $this->load->view("admin/footer");
    }

    public function saveAdminDetails()
    {

        $data = array();

        $this->form_validation->set_rules('txt_email', 'Email address', 'trim|required|max_length[100]');
        $this->form_validation->set_rules('txt_address', 'Contact Address', 'trim|required|max_length[1000]');
        $this->form_validation->set_rules('txt_dial', 'Dial Code', 'trim|required|max_length[4]|numeric');
        $this->form_validation->set_rules('txt_phone', 'Phone', 'trim|required|max_length[10]|numeric');

        $this->form_validation->set_rules('txt_facebook', 'face book url', 'trim|required');
        $this->form_validation->set_rules('txt_twitter', 'Twitter url', 'trim|required');
        // $this->form_validation->set_rules('txt_google', 'Google plus url', 'trim|required');
        $this->form_validation->set_rules('txt_insta', 'Instagram url', 'trim|required');
        $this->form_validation->set_rules('txt_youtube', 'Youtube url', 'trim|required');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_email' => form_error('txt_email'),
                'txt_address' => form_error('txt_address'),
                'txt_dial' => form_error('txt_dial'),
                'txt_phone' => form_error('txt_phone'),
                'txt_facebook' => form_error('txt_facebook'),
                'txt_twitter' => form_error('txt_twitter'),
                'txt_google' => form_error('txt_google'),
                'txt_insta' => form_error('txt_insta'),
                'txt_youtube' => form_error('txt_youtube'),
            );
            echo json_encode($data);
            exit();
        }

        $_POST = $this->security->xss_clean($_POST);

        $result = $this->M_admin->saveAdminDetails($_POST);
        //print_r($_POST);
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function withdarwalReport()
    {
        $data = array();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/withdrawal_report", $data);
        $this->load->view("admin/footer");
    }

    public function celebrityList()
    {
        $condition = array("user_type" => "C");
        $data["user_list"] = $this->M_admin->getUsersCondition($condition);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/celebrity_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditCelebrity()
    {
        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $data["country_list"] = $this->M_admin->getCountriesCondition($condition);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_celebrity", $data);
        $this->load->view("admin/footer");
    }

    public function saveCelebrityUser()
    {
        $data = array();

        $this->form_validation->set_rules('txt_first_name', 'First name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_last_name', 'Last name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_email', 'Email Address', 'trim|required|valid_email|max_length[100]');
        $this->form_validation->set_rules('radio_gender', 'Gender', 'trim|required');
        $this->form_validation->set_rules('select_country', 'Country', 'trim|required');
        $this->form_validation->set_rules('txt_password', 'Password', 'trim|required|min_length[8]|max_length[20]|valid_password');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_first_name' => form_error('txt_first_name'),
                'txt_last_name' => form_error('txt_last_name'),
                'txt_email' => form_error('txt_email'),
                'radio_gender' => form_error('radio_gender'),
                'select_country' => form_error('select_country'),
                'txt_password' => form_error('txt_password'),

            );
            echo json_encode($data);
            exit();
        }
        //  print_r($_POST);
        $_POST = $this->security->xss_clean($_POST);
        if (count($_POST) > 0) {
            $result = $this->M_admin->saveCelebrityUser($_POST);
        } else {
            $result = 0;
        }
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function editCelebrity()
    {

        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $data["country_list"] = $this->M_admin->getCountriesCondition($condition);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/update_edit_celebrity", $data);
        $this->load->view("admin/footer");
    }

    public function updateCelebrity()
    {

        $data = array();

        $this->form_validation->set_rules('txt_first_name', 'First name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_last_name', 'Last name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_email', 'Email Address', 'trim|required|valid_email');
        $this->form_validation->set_rules('radio_gender', 'Gender', 'trim|required');
        $this->form_validation->set_rules('select_country', 'Country', 'trim|required');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_first_name' => form_error('txt_first_name'),
                'txt_last_name' => form_error('txt_last_name'),
                'txt_email' => form_error('txt_email'),
                'radio_gender' => form_error('radio_gender'),
                'select_country' => form_error('select_country'),

            );
            echo json_encode($data);
            exit();
        }

        $_POST = $this->security->xss_clean($_POST);
        if (count($_POST) > 0) {
            $result = $this->M_admin->updateCelebrity($_POST);
        } else {
            $result = 0;
        }
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function thankuCommissionReport()
    {

        $condition = array("user_type" => "U");
        $data["thank_list"] = $this->M_admin->thankuReport($condition);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/thanku_report", $data);
        $this->load->view("admin/footer");
    }

    public function thankuCommissionReportPdf()
    {
        $data["user_list"] = $this->M_admin->thankuReport($condition);

        $option = $this->uri->segment(4);

        if ($option == 1) {
            $this->load->library('Fpdf_gen');
            $this->fpdf = new FPDF();
            $this->fpdf->addPage('L');
            $this->fpdf->SetFont('Arial', 'B', 12);
            $this->fpdf->SetFillColor(193, 229, 252);
            $this->fpdf->Cell(270, 10, SITE_NAME.' Thank You commission report As On - ' . date('Y-m-d'), 1, 1, C, true);

            $this->fpdf->SetFont('Arial', 'B', 12);

            $width_cell = array(10, 10, 60, 60, 60, 20, 50);
            $this->fpdf->SetFillColor(193, 229, 252); // Background color of header
            // Header starts ///
            $this->fpdf->Cell($width_cell[0], 10, 'Sl No', 1, 0, C, true); // First header column
            $this->fpdf->Cell($width_cell[1], 10, 'Order id', 1, 0, C, true); // Second header column
            $this->fpdf->Cell($width_cell[2], 10, 'Product Name', 1, 0, C, true); // Third header column
            $this->fpdf->Cell($width_cell[3], 10, 'Celebrity Name', 1, 0, C, true); // Third header column
            $this->fpdf->Cell($width_cell[4], 10, 'Customer Name', 1, 0, C, true); // Third header column
            //$this->fpdf->Cell($width_cell[5],10,'Qty',1,0,C,true); // Third header column
            //$this->fpdf->Cell($width_cell[6],10,'Sale price',1,0,C,true); // Third header column
            //$this->fpdf->Cell($width_cell[7],10,'Commission %',1,0,C,true); // Third header column
            $this->fpdf->Cell($width_cell[5], 10, 'Commi:', 1, 0, C, true); // Third header column
            $this->fpdf->Cell($width_cell[6], 10, 'Date', 1, 1, C, true); // Third header column
            $this->fpdf->SetFont('Arial', '', 10);

            if (count($data["user_list"]) > 0) {
                $this->fpdf->SetFont('Arial', '', 10);
                $i = 1;
                $total = 0;
                $total2 = 0;
                foreach ($data["user_list"] as $rows) {
                    $this->fpdf->Cell($width_cell[0], 10, $i, 1, 0, C, false); // First header column
                    $this->fpdf->Cell($width_cell[1], 10, $rows['order_block_id'], 1, 0, C, false); // Second header column
                    $this->fpdf->Cell($width_cell[2], 10, $rows['product_name'], 1, 0, C, false);
                    $this->fpdf->Cell($width_cell[3], 10, $rows['celfirsname'] . " " . $rows['cellasname'], 1, 0, C, false); // Third header column
                    $this->fpdf->Cell($width_cell[4], 10, $rows['cusfirsname'] . " " . $rows['cuslasname'], 1, 0, C, false); // First header column
                    // $this->fpdf->Cell($width_cell[4],10,$rows['purchase_qty'],1,0,C,false); // Second header column
                    // $this->fpdf->Cell($width_cell[5],10,$rows['sale_price_ondate'],1,0,C,false); // Third header column
                    //$this->fpdf->Cell($width_cell[5],10,$rows['thank_u_perc_ondate'],1,0,C,false); // Third header column
                    $this->fpdf->Cell($width_cell[5], 10, $rows['thank_u_subtotal'], 1, 0, C, false); // Third header column
                    $this->fpdf->Cell($width_cell[6], 10, $rows['thank_date'], 1, 1, C, false); // Third header column

                    $total = $total + $rows['thank_u_subtotal'];
                    //$total2 = $total2+$rows['sum2'];
                    $i++;
                }

                $this->fpdf->Cell(220, 10, 'Total', 1, 0, C, false);
                $this->fpdf->Cell(50, 10, $total, 1, 0, C, false);
                //$this->fpdf->Cell(50,10,$total2,1,0,C,false);
            }

            echo $this->fpdf->Output(SITE_NAME.'_thank_report_on' . date('Y_m_d') . '.pdf', 'D');
        } else {
            $fileName = SITE_NAME.'_thank_report_on' . date('Y_m_d') . '.xls';
            // headers for download
            header("Content-Disposition: attachment; filename=\"$fileName\"");
            header("Content-Type: application/vnd.ms-excel");

            function filterData(&$str)
            {
                $str = preg_replace("/\t/", "\\t", $str);
                $str = preg_replace("/\r?\n/", "\\n", $str);
                if (strstr($str, '"')) {
                    $str = '"' . str_replace('"', '""', $str) . '"';
                }
            }

            // file name for download
            // $fileName = "vendor_payment_report_on" . date('Ymd') . ".xls";

            // headers for download
            header("Content-Disposition: attachment; filename=\"$fileName\"");
            header("Content-Type: application/vnd.ms-excel");

            $flag = false;
            $i = 1;
            foreach ($data["user_list"] as $rows) {
                if (!$flag) {
                    // display column names as first row
                    echo implode("\t", array('Sl', 'Order id', 'Product name', 'Celebrity Name', 'Customer Name', 'commission')) . "\n";
                    $flag = true;
                }
                // filter data
                array_walk($row, 'filterData');

                $name = $row['user_first_name'] . " " . $row['user_last_name'];
                echo implode("\t", array($i, $rows['order_block_id'], $rows['product_name'], $rows['celfirsname'] . " " . $rows['cellasname'], $rows['cusfirsname'] . " " . $rows['cuslasname'], $rows['thank_u_subtotal'])) . "\n";

                $i++;
            }

            exit;
        }
    }

    public function promotedCommissionReport()
    {

        $condition = array("user_type" => "U");
        $data["thank_list"] = $this->M_admin->promotedCommissionReport($condition);
        //print_r($data["thank_list"]);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/promo_commission_report", $data);
        $this->load->view("admin/footer");
    }

    public function promotedCommissionReportPdf()
    {

        $data["user_list"] = $this->M_admin->promotedCommissionReport($condition);

        $option = $this->uri->segment(4);

        if ($option == 1) {
            $this->load->library('Fpdf_gen');
            $this->fpdf = new FPDF();
            $this->fpdf->addPage('L');
            $this->fpdf->SetFont('Arial', 'B', 12);
            $this->fpdf->SetFillColor(193, 229, 252);
            $this->fpdf->Cell(270, 10, SITE_NAME.' promoted products commission report As On - ' . date('Y-m-d'), 1, 1, C, true);

            $this->fpdf->SetFont('Arial', 'B', 12);

            $width_cell = array(10, 20, 50, 60, 20, 40, 50, 20);
            $this->fpdf->SetFillColor(193, 229, 252); // Background color of header
            // Header starts ///
            $this->fpdf->Cell($width_cell[0], 10, 'Sl No', 1, 0, C, true); // First header column
            $this->fpdf->Cell($width_cell[1], 10, 'Order id', 1, 0, C, true); // Second header column
            $this->fpdf->Cell($width_cell[2], 10, 'Product Name', 1, 0, C, true); // Third header column
            $this->fpdf->Cell($width_cell[3], 10, 'Celebrity Name', 1, 0, C, true); // Third header column
            $this->fpdf->Cell($width_cell[4], 10, 'Qty', 1, 0, C, true); // Third header column
            $this->fpdf->Cell($width_cell[5], 10, 'Date', 1, 0, C, true); // Third header column
            $this->fpdf->Cell($width_cell[6], 10, 'Cate:Comm %', 1, 0, C, true); // Third header column
            $this->fpdf->Cell($width_cell[7], 10, 'Commi:', 1, 1, C, true); // Third header column
            //$this->fpdf->Cell($width_cell[6],10,'Date',1,1,C,true); // Third header column
            $this->fpdf->SetFont('Arial', '', 10);

            if (count($data["user_list"]) > 0) {
                $this->fpdf->SetFont('Arial', '', 10);
                $i = 1;
                $total = 0;
                $total2 = 0;
                foreach ($data["user_list"] as $rows) {
                    $cate = $rows['category_commission'] * $rows['purchase_qty'];

                    $c = $rows['category_commission'] * $rows['purchase_qty'];
                    $comm = ($rows['cel_com_perc'] * $c) / 100;

                    $this->fpdf->Cell($width_cell[0], 10, $i, 1, 0, C, false); // First header column
                    $this->fpdf->Cell($width_cell[1], 10, $rows['order_block_id'], 1, 0, C, false); // Second header column
                    $this->fpdf->Cell($width_cell[2], 10, $rows['product_name'], 1, 0, C, false);
                    $this->fpdf->Cell($width_cell[3], 10, $rows['user_first_name'] . " " . $rows['user_last_name'], 1, 0, C, false); // Third header column
                    // $this->fpdf->Cell($width_cell[4],10,$rows['cusfirsname']." ".$rows['cuslasname'],1,0,C,false); // First header column
                    $this->fpdf->Cell($width_cell[4], 10, $rows['purchase_qty'], 1, 0, C, false); // Second header column
                    // $this->fpdf->Cell($width_cell[5],10,$rows['sale_price_ondate'],1,0,C,false); // Third header column
                    //$this->fpdf->Cell($width_cell[5],10,$rows['thank_u_perc_ondate'],1,0,C,false); // Third header column
                    $this->fpdf->Cell($width_cell[5], 10, $rows['order_placed_date'], 1, 0, C, false); // Third header column
                    $this->fpdf->Cell($width_cell[6], 10, $cate, 1, 0, C, false); // Third header column
                    $this->fpdf->Cell($width_cell[7], 10, $comm, 1, 1, C, false);
                    $total = $total + $comm;
                    //$total2 = $total2+$rows['sum2'];
                    $i++;
                }

                $this->fpdf->Cell(250, 10, 'Total', 1, 0, C, false);
                $this->fpdf->Cell(20, 10, $total, 1, 0, C, false);
                //$this->fpdf->Cell(50,10,$total2,1,0,C,false);
            }

            echo $this->fpdf->Output(SITE_NAME.'_report_on' . date('Y_m_d') . '.pdf', 'D');
        } else {
            $fileName = SITE_NAME.'_report_on' . date('Y_m_d') . '.xls';
            // headers for download
            header("Content-Disposition: attachment; filename=\"$fileName\"");
            header("Content-Type: application/vnd.ms-excel");

            function filterData(&$str)
            {
                $str = preg_replace("/\t/", "\\t", $str);
                $str = preg_replace("/\r?\n/", "\\n", $str);
                if (strstr($str, '"')) {
                    $str = '"' . str_replace('"', '""', $str) . '"';
                }
            }

            // file name for download
            // $fileName = "vendor_payment_report_on" . date('Ymd') . ".xls";

            // headers for download
            header("Content-Disposition: attachment; filename=\"$fileName\"");
            header("Content-Type: application/vnd.ms-excel");

            $flag = false;
            $i = 1;
            foreach ($data["user_list"] as $rows) {
                $cate = $rows['category_commission'] * $rows['purchase_qty'];

                $c = $rows['category_commission'] * $rows['purchase_qty'];
                $comm = ($rows['cel_com_perc'] * $c) / 100;
                if (!$flag) {
                    // display column names as first row
                    echo implode("\t", array('Sl', 'Order id', 'Product name', 'Celebrity Name', 'Quantity', 'Category commission', 'commission')) . "\n";
                    $flag = true;
                }
                // filter data
                array_walk($row, 'filterData');

                $name = $row['user_first_name'] . " " . $row['user_last_name'];
                echo implode("\t", array($i, $rows['order_block_id'], $rows['product_name'], $rows['user_first_name'] . " " . $rows['user_last_name'], $rows['purchase_qty'], $cate, $comm)) . "\n";

                $i++;
            }

            exit;
        }
    }

    public function SocialarticleList()
    {
        $condition = array();
        $data["article_list"] = $this->M_admin->getSocialArticles();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/social/social_article_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditArticleSocial()
    {
        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);

        $data = array();

        $data["article_type"] = $this->M_admin->getSocialArticleTypes();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_article_social", $data);
        $this->load->view("admin/footer");
    }

    public function saveSocialArticle()
    {

        $this->form_validation->set_rules('txt_article_type', 'Article type', 'required');
        $this->form_validation->set_rules('txt_article', 'Article English', 'required|custom_minlength_check');
        //$this->form_validation->set_rules('txt_article_arb', 'Article Arabic', 'required|custom_minlength_check');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_article_type' => form_error('txt_article_type'),
                'txt_article' => form_error('txt_article'),
                // 'txt_article_arb' => form_error('txt_article_arb'),
            );
            echo json_encode($data);
            exit();
        }
        $_POST = $this->security->xss_clean($_POST);
        if (count($_POST) > 0) {
            $result = $this->M_admin->saveSocialArticle($_POST);
        } else {
            $result = 0;
        }
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function deleteSocialArticle()
    {
        $id = $_POST['id'];
        echo $this->M_admin->deleteSocialArticle($id);
    }

    public function listNewsLetters()
    {
        $condition = array();
        $letter_list = $this->M_admin->getNewsLetters();

        $list= array();
        foreach($letter_list as $row){
            $news['newsletter_id'] =$row["newsletter_id"];
            $news['newsletter_email'] =$row["newsletter_email"];
            $news['newsletter_date'] =(string) get_date_in_timezone($this->userTimezone, $row["newsletter_date"], "d M Y h:i A");
            $list[] = $news;
        }
        $data["letter_list"] =$list;
        //get_date_in_timezone
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/news_letter_list", $data);
        $this->load->view("admin/footer");
    }

    public function listTeyaarCommission()
    {
        $condition = array();
        $data["commission_list"] = $this->M_admin->getAllTeyaarCommission();
        //print_r($data);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/teyaar_comm_list", $data);
        $this->load->view("admin/footer");
    }

    public function listEnquiery()
    {
        $condition = array();
        $data["enq_list"] = $this->M_admin->getAllEnquieries();
        //print_r($data);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/enquiery_list", $data);
        $this->load->view("admin/footer");
    }

    public function saveTeyaarCommission()
    {
        $this->form_validation->set_rules('txt_teyaar_com', SITE_NAME.' commission percentage', 'required|percent_check');
        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_teyaar_com' => form_error('txt_teyaar_com'),
            );
            echo json_encode($data);
            exit();
        }
        $_POST = $this->security->xss_clean($_POST);
        if (count($_POST) > 0) {
            $result = $this->M_admin->saveTeyaarCommission($_POST);
        } else {
            $result = 0;
        }
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function changePassword()
    {
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/change_password", $data);
        $this->load->view("admin/footer");
    }

    public function saveChangePassword()
    {
        $this->form_validation->set_rules('txt_old_password', 'Old password', 'required|min_length[8]|max_length[20]');
        $this->form_validation->set_rules('txt_new_password', 'New password', 'required|min_length[8]|max_length[20]');
        $this->form_validation->set_rules('txt_conf_password', 'Confirm password', 'required|min_length[8]|max_length[20]|matches[txt_new_password]');
        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_old_password' => form_error('txt_old_password'),
                'txt_new_password' => form_error('txt_new_password'),
                'txt_conf_password' => form_error('txt_conf_password'),
            );
            echo json_encode($data);
            exit();
        }
        $_POST = $this->security->xss_clean($_POST);
        if (count($_POST) > 0) {
            $result = $this->M_admin->saveChangePassword($_POST);
        } else {
            $result = 0;
        }
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function loadAnalysisReport()
    {
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/analysis_report", $data);
        $this->load->view("admin/footer");
    }

    public function listGenderWiseReport()
    {

        $this->load->library('pagination');

        $limit_per_page = $_POST['limit_per_page'] > 0 ? $_POST['limit_per_page'] : 10;
        $start_index = ($this->uri->segment(4) > 0 ? ($this->uri->segment(4) - 1) * $limit_per_page : 0);
        $records = $this->M_admin->listGenderWiseReportCount($_POST);
        $total_records = $records->count;

        if ($total_records > 0) {
            $data['result'] = $this->M_admin->listGenderWiseReport($_POST, $limit_per_page, $start_index);

            $config['base_url'] = base_url() . 'admin/C_admin/listGenderWiseReport';
            $config['total_rows'] = $total_records;
            $config['per_page'] = $limit_per_page;
            $config["uri_segment"] = 4;

            // custom paging configuration
            $config['num_links'] = 2;
            $config['use_page_numbers'] = true;
            $config['reuse_query_string'] = true;

            $config['full_tag_open'] = '<ul class="pagination">';
            $config['full_tag_close'] = '</ul>';

            $config['first_link'] = $this->lang->line('first');
            $config['first_tag_open'] = '<li>';
            $config['first_tag_close'] = '</li>';

            $config['last_link'] = $this->lang->line('last');
            $config['last_tag_open'] = '<li>';
            $config['last_tag_close'] = '</li>';

            $config['next_link'] = '&gt;';
            $config['next_tag_open'] = '<li>';
            $config['next_tag_close'] = '</li>';

            $config['prev_link'] = '&lt;';
            $config['prev_tag_open'] = '<li>';
            $config['prev_tag_close'] = '</li>';

            $config['cur_tag_open'] = '<li class="active"><span>';
            $config['cur_tag_close'] = '</span></li>';

            $config['num_tag_open'] = '<li>';
            $config['num_tag_close'] = '</li>';
            $config["num_links"] = 6;

            $this->pagination->initialize($config);

            $data["links"] = $this->pagination->create_links();
        }

        $this->load->view("admin/genderwise_report_ajax", $data);
    }

    public function listRegionWiseReport()
    {

        $this->load->library('pagination');

        $limit_per_page = $_POST['limit_per_page'] > 0 ? $_POST['limit_per_page'] : 10;
        $start_index = ($this->uri->segment(4) > 0 ? ($this->uri->segment(4) - 1) * $limit_per_page : 0);
        $records = $this->M_admin->listRegionWiseReportCount($_POST);
        $total_records = $records->count;

        if ($total_records > 0) {
            $data['result'] = $this->M_admin->listRegionWiseReport($_POST, $limit_per_page, $start_index);

            $config['base_url'] = base_url() . 'admin/C_admin/listRegionWiseReport';
            $config['total_rows'] = $total_records;
            $config['per_page'] = $limit_per_page;
            $config["uri_segment"] = 4;

            // custom paging configuration
            $config['num_links'] = 2;
            $config['use_page_numbers'] = true;
            $config['reuse_query_string'] = true;

            $config['full_tag_open'] = '<ul class="pagination">';
            $config['full_tag_close'] = '</ul>';

            $config['first_link'] = $this->lang->line('first');
            $config['first_tag_open'] = '<li>';
            $config['first_tag_close'] = '</li>';

            $config['last_link'] = $this->lang->line('last');
            $config['last_tag_open'] = '<li>';
            $config['last_tag_close'] = '</li>';

            $config['next_link'] = '&gt;';
            $config['next_tag_open'] = '<li>';
            $config['next_tag_close'] = '</li>';

            $config['prev_link'] = '&lt;';
            $config['prev_tag_open'] = '<li>';
            $config['prev_tag_close'] = '</li>';

            $config['cur_tag_open'] = '<li class="active"><span>';
            $config['cur_tag_close'] = '</span></li>';

            $config['num_tag_open'] = '<li>';
            $config['num_tag_close'] = '</li>';
            $config["num_links"] = 6;

            $this->pagination->initialize($config);

            $data["links"] = $this->pagination->create_links();
        }

        $this->load->view("admin/regionwise_report_ajax", $data);
    }

    public function listSeasonWiseReport()
    {
        $this->load->library('pagination');
        /* <option value="06-01/06-30">Eid-al-Fitr</option>
        <option value="08-01/08-31">Eid-al-Adha</option>
        <option value="12-15/12-31">X-mass</option>
        <option value="01-01/01-15">New year</option>*/

        $dateRange = $_POST['seasonCombo'] > 0 ? $_POST['seasonCombo'] : 1;
        switch ($dateRange) {
            case "1":
                $_POST['txt_sale_datefrom'] = $_POST['yearCombo'] . "-" . "06-01";
                $_POST['txt_sale_dateto'] = $_POST['yearCombo'] . "-" . "06-30";
                $_POST['season'] = "Eid-al-Fitr";
                break;
            case "2":
                $_POST['txt_sale_datefrom'] = $_POST['yearCombo'] . "-" . "08-01";
                $_POST['txt_sale_dateto'] = $_POST['yearCombo'] . "-" . "08-31";
                $_POST['season'] = "Eid-al-Adha";
                break;
            case "3":
                $_POST['txt_sale_datefrom'] = $_POST['yearCombo'] . "-" . "12-15";
                $_POST['txt_sale_dateto'] = $_POST['yearCombo'] . "-" . "12-31";
                $_POST['season'] = "X-mas";
                break;
            case "4":
                $_POST['txt_sale_datefrom'] = $_POST['yearCombo'] . "-" . "01-01";
                $_POST['txt_sale_dateto'] = $_POST['yearCombo'] . "-" . "01-15";
                $_POST['season'] = "New year";
                break;
            default:
                $_POST['txt_sale_datefrom'] = $_POST['yearCombo'] . "-" . "06-01";
                $_POST['txt_sale_dateto'] = $_POST['yearCombo'] . "-" . "06-30";
                $_POST['season'] = "Eid-al-Fitr";
        }
        //print_r($_POST);
        //    exit;
        $limit_per_page = $_POST['limit_per_page'] > 0 ? $_POST['limit_per_page'] : 10;
        $start_index = ($this->uri->segment(4) > 0 ? ($this->uri->segment(4) - 1) * $limit_per_page : 0);
        $records = $this->M_admin->listSeasonWiseReportCount($_POST);
        $total_records = $records->count;

        if ($total_records > 0) {
            $data['result'] = $this->M_admin->listSeasonWiseReport($_POST, $limit_per_page, $start_index);

            $config['base_url'] = base_url() . 'admin/C_admin/listSeasonWiseReport';
            $config['total_rows'] = $total_records;
            $config['per_page'] = $limit_per_page;
            $config["uri_segment"] = 4;

            // custom paging configuration
            $config['num_links'] = 2;
            $config['use_page_numbers'] = true;
            $config['reuse_query_string'] = true;

            $config['full_tag_open'] = '<ul class="pagination">';
            $config['full_tag_close'] = '</ul>';

            $config['first_link'] = $this->lang->line('first');
            $config['first_tag_open'] = '<li>';
            $config['first_tag_close'] = '</li>';

            $config['last_link'] = $this->lang->line('last');
            $config['last_tag_open'] = '<li>';
            $config['last_tag_close'] = '</li>';

            $config['next_link'] = '&gt;';
            $config['next_tag_open'] = '<li>';
            $config['next_tag_close'] = '</li>';

            $config['prev_link'] = '&lt;';
            $config['prev_tag_open'] = '<li>';
            $config['prev_tag_close'] = '</li>';

            $config['cur_tag_open'] = '<li class="active"><span>';
            $config['cur_tag_close'] = '</span></li>';

            $config['num_tag_open'] = '<li>';
            $config['num_tag_close'] = '</li>';
            $config["num_links"] = 6;

            $this->pagination->initialize($config);

            $data["links"] = $this->pagination->create_links();
        }

        $data['season'] = $_POST['season'];

        $this->load->view("admin/seasonwise_report_ajax", $data);
    }

    public function listPriceWiseReport()
    {

        // print_r($_POST);

        $this->load->library('pagination');

        $limit_per_page = $_POST['limit_per_page'] > 0 ? $_POST['limit_per_page'] : 10;
        $start_index = ($this->uri->segment(4) > 0 ? ($this->uri->segment(4) - 1) * $limit_per_page : 0);
        $records = $this->M_admin->listPriceWiseReportCount($_POST);
        $total_records = $records->count;

        if ($total_records > 0) {
            $data['result'] = $this->M_admin->listPriceWiseReport($_POST, $limit_per_page, $start_index);

            $config['base_url'] = base_url() . 'admin/C_admin/listPriceWiseReport';
            $config['total_rows'] = $total_records;
            $config['per_page'] = $limit_per_page;
            $config["uri_segment"] = 4;

            // custom paging configuration
            $config['num_links'] = 2;
            $config['use_page_numbers'] = true;
            $config['reuse_query_string'] = true;

            $config['full_tag_open'] = '<ul class="pagination">';
            $config['full_tag_close'] = '</ul>';

            $config['first_link'] = $this->lang->line('first');
            $config['first_tag_open'] = '<li>';
            $config['first_tag_close'] = '</li>';

            $config['last_link'] = $this->lang->line('last');
            $config['last_tag_open'] = '<li>';
            $config['last_tag_close'] = '</li>';

            $config['next_link'] = '&gt;';
            $config['next_tag_open'] = '<li>';
            $config['next_tag_close'] = '</li>';

            $config['prev_link'] = '&lt;';
            $config['prev_tag_open'] = '<li>';
            $config['prev_tag_close'] = '</li>';

            $config['cur_tag_open'] = '<li class="active"><span>';
            $config['cur_tag_close'] = '</span></li>';

            $config['num_tag_open'] = '<li>';
            $config['num_tag_close'] = '</li>';
            $config["num_links"] = 6;

            $this->pagination->initialize($config);

            $data["links"] = $this->pagination->create_links();
        }

        $this->load->view("admin/pricewise_report_ajax", $data);
    }

    public function listSellingWiseReport()
    {

        // print_r($_POST);

        $this->load->library('pagination');

        $limit_per_page = $_POST['limit_per_page'] > 0 ? $_POST['limit_per_page'] : 10;
        $start_index = ($this->uri->segment(4) > 0 ? ($this->uri->segment(4) - 1) * $limit_per_page : 0);
        $records = $this->M_admin->listSellingWiseReportCount($_POST);
        $total_records = $records->count;

        if ($total_records > 0) {
            $data['result'] = $this->M_admin->listSellingWiseReport($_POST, $limit_per_page, $start_index);

            $config['base_url'] = base_url() . 'admin/C_admin/listSellingWiseReport';
            $config['total_rows'] = $total_records;
            $config['per_page'] = $limit_per_page;
            $config["uri_segment"] = 4;

            // custom paging configuration
            $config['num_links'] = 2;
            $config['use_page_numbers'] = true;
            $config['reuse_query_string'] = true;

            $config['full_tag_open'] = '<ul class="pagination">';
            $config['full_tag_close'] = '</ul>';

            $config['first_link'] = $this->lang->line('first');
            $config['first_tag_open'] = '<li>';
            $config['first_tag_close'] = '</li>';

            $config['last_link'] = $this->lang->line('last');
            $config['last_tag_open'] = '<li>';
            $config['last_tag_close'] = '</li>';

            $config['next_link'] = '&gt;';
            $config['next_tag_open'] = '<li>';
            $config['next_tag_close'] = '</li>';

            $config['prev_link'] = '&lt;';
            $config['prev_tag_open'] = '<li>';
            $config['prev_tag_close'] = '</li>';

            $config['cur_tag_open'] = '<li class="active"><span>';
            $config['cur_tag_close'] = '</span></li>';

            $config['num_tag_open'] = '<li>';
            $config['num_tag_close'] = '</li>';
            $config["num_links"] = 6;

            $this->pagination->initialize($config);

            $data["links"] = $this->pagination->create_links();
        }

        $this->load->view("admin/sellingwise_report_ajax", $data);
    }

    public function downloadGenderReport()
    {

        $limit_per_page = 1000000;
        $start_index = 0;

        if ($_POST['txt_sale_datefrom'] != "" && $_POST['txt_sale_dateto'] != "") {
            $date = $_POST['txt_sale_datefrom'] . "_" . $_POST['txt_sale_dateto'];
        } else {
            $date = date('Y_m_d');
        }

        $fileName = 'genderwise_sales_report' . $date . '.xls';
        $result = $this->M_admin->listGenderWiseReport($_POST, $limit_per_page, $start_index);

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        function filterData(&$str)
        {
            $str = preg_replace("/\t/", "\\t", $str);
            $str = preg_replace("/\r?\n/", "\\n", $str);
            if (strstr($str, '"')) {
                $str = '"' . str_replace('"', '""', $str) . '"';
            }
        }

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        $flag = false;
        $i = 1;
        foreach ($result as $rows) {
            if (!$flag) {
                // display column names as first row
                echo implode("\t", array('Sl no', 'Product name', 'Vendor Name ', 'Store Name', 'Gender', 'Total Sale')) . "\n";
                $flag = true;
            }
            // filter data
            array_walk($row, 'filterData');

            if ($rows['user_gender'] == "1") {
                $gender = "Male";
            } elseif ($rows['user_gender'] == "2") {
                $gender = "Female";
            } else {
                $gender = "-";
            }
            echo implode("\t", array($i, $rows['product_name'], $rows['vendor_name'], $rows['store_name'], $gender, $rows['count'])) . "\n";
            $i++;
        }

        exit;
    }

    public function downloadRegionReport()
    {

        $limit_per_page = 1000000;
        $start_index = 0;

        if ($_POST['txt_sale_datefrom'] != "" && $_POST['txt_sale_dateto'] != "") {
            $date = $_POST['txt_sale_datefrom'] . "_" . $_POST['txt_sale_dateto'];
        } else {
            $date = date('Y_m_d');
        }

        $fileName = 'regionwise_sales_report' . $date . '.xls';
        $result = $this->M_admin->listRegionWiseReport($_POST, $limit_per_page, $start_index);

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        function filterData(&$str)
        {
            $str = preg_replace("/\t/", "\\t", $str);
            $str = preg_replace("/\r?\n/", "\\n", $str);
            if (strstr($str, '"')) {
                $str = '"' . str_replace('"', '""', $str) . '"';
            }
        }

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        $flag = false;
        $i = 1;
        foreach ($result as $rows) {
            if (!$flag) {
                // display column names as first row
                echo implode("\t", array('Sl no', 'Product name', 'Vendor Name ', 'Store Name', 'Region', 'Total Sale')) . "\n";
                $flag = true;
            }
            // filter data
            array_walk($row, 'filterData');

            echo implode("\t", array($i, $rows['product_name'], $rows['vendor_name'], $rows['store_name'], $rows['city_name'], $rows['count'])) . "\n";
            $i++;
        }

        exit;
    }

    public function downloadSeasonReport()
    {

        $limit_per_page = 1000000;
        $start_index = 0;
        $dateRange = $_POST['seasonCombo'] > 0 ? $_POST['seasonCombo'] : 1;
        switch ($dateRange) {
            case "1":
                $_POST['txt_sale_datefrom'] = $_POST['yearCombo'] . "-" . "06-01";
                $_POST['txt_sale_dateto'] = $_POST['yearCombo'] . "-" . "06-30";
                $_POST['season'] = "Eid-al-Fitr";
                break;
            case "2":
                $_POST['txt_sale_datefrom'] = $_POST['yearCombo'] . "-" . "08-01";
                $_POST['txt_sale_dateto'] = $_POST['yearCombo'] . "-" . "08-31";
                $_POST['season'] = "Eid-al-Adha";
                break;
            case "3":
                $_POST['txt_sale_datefrom'] = $_POST['yearCombo'] . "-" . "12-15";
                $_POST['txt_sale_dateto'] = $_POST['yearCombo'] . "-" . "12-31";
                $_POST['season'] = "X-mas";
                break;
            case "4":
                $_POST['txt_sale_datefrom'] = $_POST['yearCombo'] . "-" . "01-01";
                $_POST['txt_sale_dateto'] = $_POST['yearCombo'] . "-" . "01-15";
                $_POST['season'] = "New year";
                break;
            default:
                $_POST['txt_sale_datefrom'] = $_POST['yearCombo'] . "-" . "06-01";
                $_POST['txt_sale_dateto'] = $_POST['yearCombo'] . "-" . "06-30";
                $_POST['season'] = "Eid-al-Fitr";
        }
        if ($_POST['txt_sale_datefrom'] != "" && $_POST['txt_sale_dateto'] != "") {
            $date = $_POST['txt_sale_datefrom'] . "_" . $_POST['txt_sale_dateto'];
        } else {
            $date = date('Y_m_d');
        }

        $fileName = 'seasonwise_sales_report' . $date . '.xls';
        $result = $this->M_admin->listSeasonWiseReport($_POST, $limit_per_page, $start_index);

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        function filterData(&$str)
        {
            $str = preg_replace("/\t/", "\\t", $str);
            $str = preg_replace("/\r?\n/", "\\n", $str);
            if (strstr($str, '"')) {
                $str = '"' . str_replace('"', '""', $str) . '"';
            }
        }

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        $flag = false;
        $i = 1;
        foreach ($result as $rows) {
            if (!$flag) {
                // display column names as first row
                echo implode("\t", array('Sl no', 'Product name', 'Vendor Name ', 'Store Name', 'Season', 'Total Sale')) . "\n";
                $flag = true;
            }
            // filter data
            array_walk($row, 'filterData');

            echo implode("\t", array($i, $rows['product_name'], $rows['vendor_name'], $rows['store_name'], $_POST['season'], $rows['count'])) . "\n";
            $i++;
        }

        exit;
    }

    public function downloadPriceReport()
    {

        $limit_per_page = 1000000;
        $start_index = 0;

        if ($_POST['txt_sale_datefrom'] != "" && $_POST['txt_sale_dateto'] != "") {
            $date = $_POST['txt_sale_datefrom'] . "_" . $_POST['txt_sale_dateto'];
        } else {
            $date = date('Y_m_d');
        }

        $fileName = 'pricewise_sales_report' . $date . '.xls';
        $result = $this->M_admin->listPriceWiseReport($_POST, $limit_per_page, $start_index);

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        function filterData(&$str)
        {
            $str = preg_replace("/\t/", "\\t", $str);
            $str = preg_replace("/\r?\n/", "\\n", $str);
            if (strstr($str, '"')) {
                $str = '"' . str_replace('"', '""', $str) . '"';
            }
        }

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        $flag = false;
        $i = 1;
        foreach ($result as $rows) {
            if (!$flag) {
                // display column names as first row
                echo implode("\t", array('Sl no', 'Product name', 'Vendor Name ', 'Store Name', 'Price', 'Total Sale')) . "\n";
                $flag = true;
            }
            // filter data
            array_walk($row, 'filterData');

            echo implode("\t", array($i, $rows['product_name'], $rows['vendor_name'], $rows['store_name'], $rows['sale_price'], $rows['count'])) . "\n";
            $i++;
        }

        exit;
    }

    public function downloadSellingReport()
    {

        $limit_per_page = 1000000;
        $start_index = 0;

        if ($_POST['txt_sale_datefrom'] != "" && $_POST['txt_sale_dateto'] != "") {
            $date = $_POST['txt_sale_datefrom'] . "_" . $_POST['txt_sale_dateto'];
        } else {
            $date = date('Y_m_d');
        }

        $fileName = 'sellingwise_sales_report' . $date . '.xls';
        $result = $this->M_admin->listSellingWiseReport($_POST, $limit_per_page, $start_index);

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        function filterData(&$str)
        {
            $str = preg_replace("/\t/", "\\t", $str);
            $str = preg_replace("/\r?\n/", "\\n", $str);
            if (strstr($str, '"')) {
                $str = '"' . str_replace('"', '""', $str) . '"';
            }
        }

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        $flag = false;
        $i = 1;
        foreach ($result as $rows) {
            if (!$flag) {
                // display column names as first row
                echo implode("\t", array('Sl no', 'Product name', 'Vendor Name ', 'Store Name', 'Total Sale')) . "\n";
                $flag = true;
            }
            // filter data
            array_walk($row, 'filterData');

            echo implode("\t", array($i, $rows['product_name'], $rows['vendor_name'], $rows['store_name'], $rows['count'])) . "\n";
            $i++;
        }

        exit;
    }

    public function deleteCelebrityPerc()
    {
        echo $result = $this->M_admin->deleteCelebrityPerc($_POST);
    }

    public function pendingCheckout()
    {
        $data['results'] = $this->M_admin->getPendingCheckoutList();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/pending_checkout_list", $data);
        $this->load->view("admin/footer");
    }

    public function sendCheckoutReminder()
    {

        $bag = $this->M_admin->loadMyBag($_POST['id']);

        $userId = $_POST['id'];
        $user = $this->M_admin->getBasicUserDeatils($userId);

        // print_r($bag);

        $from   = "info@Fassl.com";

        $to     = $user->user_email_id;

        $message = $this->load->view("email_templates/admin/checkout_reminder", ["bag" => $bag, "userId" => $userId, "user" => $user], true);

        //  echo $message;
        //  $message ="gfg";
        $subject = " Your cart is ready for checkout-".SITE_NAME;
        // $to="ajeshcd@gmail.com";
        //    $this->M_product->send($subject,$message,$to,$from) ;
        $this->load->library("mail_function");
        $result = $this->mail_function->SendEmail($message, $subject, $to);

        echo 1;
        /*   if($result)
        {
        echo 1;
        }
        else
        {
        echo 0;
        }*/
    }

    public function viewUserCart()
    {

        $result = $this->M_admin->loadMyBag($_POST['id']);

        if (count($result) <= 0) {
            echo "";
        } else {
            $data['my_bag'] = $result;
            $this->load->view("admin/my_cart_ajax", $data);
        }
    }

    public function listAdminStaff()
    {
        if ($this->session->userdata('admin_designation') != 1) {
            redirect(base_url() . "admin");
        }

        $data['results'] = $this->M_admin->getAdminUsers();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/list_staff", $data);
        $this->load->view("admin/footer");
    }

    public function addAdminStaff()
    {

        if ($this->session->userdata('admin_designation') != 1) {
            redirect(base_url() . "admin");
        }
        $adminId = $this->uri->segment(2) != "" ? $this->uri->segment(2) : 0;

        $adminId = $this->M_product->decryptId($adminId);

        if ($adminId > 0) {
            $oldData = $this->M_admin->getAdminUserDetails($adminId);
        } else {
            $oldData = array();
        }

        $data['results'] = $oldData;

        $data['designation'] = $this->M_admin->loadDesignation();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ["segment" => "add_stafs"]);
        $this->load->view("admin/add_edit_admin_staff", $data);
        $this->load->view("admin/footer");
    }

    public function saveAdminUsers()
    {
        $this->form_validation->set_rules('txt_first_name', 'First name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_last_name', 'Last name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_user_name', 'user name', 'trim|required|max_length[50]|min_length[8]|xss_clean|alpha_numeric');
        $this->form_validation->set_rules('txt_email', 'Email id', 'trim|required|max_length[100]');
        if ($_POST['id'] <= 0) {
            $this->form_validation->set_rules('txt_password', 'Password', 'trim|required|min_length[8]|max_length[20]|valid_password');
        }
        $this->form_validation->set_rules('txt_designation', 'Designation', 'trim|required');
        $this->form_validation->set_rules('txtStatus', 'Status', 'trim|required');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_first_name' => form_error('txt_first_name'),
                'txt_last_name' => form_error('txt_last_name'),
                'txt_user_name' => form_error('txt_user_name'),
                'txt_email' => form_error('txt_email'),
                'txt_password' => form_error('txt_password'),
                'txt_designation' => form_error('txt_designation'),
                'txtStatus' => form_error('txtStatus'),
            );
            echo json_encode($data);
            exit();
        }
        $_POST = $this->security->xss_clean($_POST);

        $result = $this->M_admin->saveAdminUsers($_POST);
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function approveAdmin()
    {
        echo $result = $this->M_admin->approveAdmin($_POST);
    }

    public function setPermission()
    {
        if ($this->session->userdata('admin_designation') != 1) {
            redirect(base_url() . "admin");
        }

        $data['menu'] = $this->M_admin->getMenus();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_permission", $data);
        $this->load->view("admin/footer");
    }

    public function saveAdminPermission()
    {
        echo $result = $this->M_admin->saveAdminPermission($_POST);
    }

    public function deleteAdmin()
    {
        if ($_POST['admin_user_id'] != 1) {
            echo $result = $this->M_admin->deleteAdmin($_POST);
        } else {
            echo 3;
        }
    }

    public function changePasswordAdminUser()
    {
        $this->form_validation->set_rules('txt_new_pwd', 'Password', 'trim|required|min_length[8]|max_length[20]|valid_password');
        $this->form_validation->set_rules('cnf_pwd', 'Confirm password', 'trim|required|matches[txt_new_pwd]|min_length[8]|max_length[20]');
        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_new_pwd' => form_error('txt_new_pwd'),
                'cnf_pwd' => form_error('cnf_pwd'),
            );
            echo json_encode($data);
            exit();
        }
        $_POST = $this->security->xss_clean($_POST);
        $result = $this->M_admin->changePasswordAdminUser($_POST);
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function changePasswordUser()
    {
        $this->form_validation->set_rules('txt_new_pwd', 'Password', 'trim|required|min_length[8]|max_length[20]|valid_password');
        $this->form_validation->set_rules('cnf_pwd', 'Confirm password', 'trim|required|matches[txt_new_pwd]|min_length[8]|max_length[20]');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_new_pwd' => form_error('txt_new_pwd'),
                'cnf_pwd' => form_error('cnf_pwd'),
            );
            echo json_encode($data);
            exit();
        }
        $_POST = $this->security->xss_clean($_POST);
        $result = $this->M_admin->changePasswordUser($_POST);
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function listAuditTrail()
    {
        if ($this->session->userdata('admin_designation') != 1) {
            redirect(base_url() . "admin");
        }

        $data['trail'] = $this->M_admin->getAudittrails();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/audit_trail_list", $data);
        $this->load->view("admin/footer");
    }

    public function listAuditTrailsAjax()
    {

        $this->load->library('pagination');
        $limit_per_page = $_POST['limit_per_page'] > 0 ? $_POST['limit_per_page'] : 10;
        $start_index = ($this->uri->segment(4) > 0 ? ($this->uri->segment(4) - 1) * $limit_per_page : 0);
        $records = $this->M_admin->listauditTrailReportCount($_POST);
        $total_records = $records->count;

        if ($total_records > 0) {
            $data['trail'] = $this->M_admin->listauditTrailReport($_POST, $limit_per_page, $start_index);

            $config['base_url'] = base_url() . 'admin/C_admin/listAuditTrailsAjax';
            $config['total_rows'] = $total_records;
            $config['per_page'] = $limit_per_page;
            $config["uri_segment"] = 4;

            // custom paging configuration
            $config['num_links'] = 2;
            $config['use_page_numbers'] = true;
            $config['reuse_query_string'] = true;

            $config['full_tag_open'] = '<ul class="pagination">';
            $config['full_tag_close'] = '</ul>';

            $config['first_link'] = $this->lang->line('first');
            $config['first_tag_open'] = '<li>';
            $config['first_tag_close'] = '</li>';

            $config['last_link'] = $this->lang->line('last');
            $config['last_tag_open'] = '<li>';
            $config['last_tag_close'] = '</li>';

            $config['next_link'] = '&gt;';
            $config['next_tag_open'] = '<li>';
            $config['next_tag_close'] = '</li>';

            $config['prev_link'] = '&lt;';
            $config['prev_tag_open'] = '<li>';
            $config['prev_tag_close'] = '</li>';

            $config['cur_tag_open'] = '<li class="active"><span>';
            $config['cur_tag_close'] = '</span></li>';

            $config['num_tag_open'] = '<li>';
            $config['num_tag_close'] = '</li>';
            $config["num_links"] = 6;

            $this->pagination->initialize($config);

            $data["links"] = $this->pagination->create_links();
        }

        $this->load->view("admin/audit_trail_list_ajax", $data);
    }

    // public function valid_password($password = '')
    // {
    //     $password = trim($password);
    //     $regex_lowercase = '/[a-z]/';
    //     $regex_uppercase = '/[A-Z]/';
    //     $regex_number = '/[0-9]/';
    //     $regex_special = '/[!@#$%^&*()\-_=+{};:,<.>§~]/';
    //     if (empty($password)) {
    //         $this->form_validation->set_message('valid_password', 'The {field} field is required.');
    //         return false;
    //     }

    //     if (preg_match_all($regex_uppercase, $password) < 1 && preg_match_all($regex_lowercase, $password) < 1) {
    //         $this->form_validation->set_message('valid_password', 'The {field} field must be at least one  letter.');
    //         return false;
    //     }
    //     if (preg_match_all($regex_number, $password) < 1) {
    //         $this->form_validation->set_message('valid_password', 'The {field} field must have at least one number.');
    //         return false;
    //     }
    //     if (preg_match_all($regex_special, $password) < 1) {
    //         $this->form_validation->set_message('valid_password', 'The {field} field must have at least one special character.');
    //         return false;
    //     }
    //     if (strlen($password) < 8) {
    //         $this->form_validation->set_message('valid_password', 'The {field} field must be at least 8 characters in length.');
    //         return false;
    //     }
    //     if (strlen($password) > 20) {
    //         $this->form_validation->set_message('valid_password', 'The {field} field cannot exceed 20 characters in length.');
    //         return false;
    //     }
    //     return true;
    // }

    // public function check_inavlid_char($string = "")
    // {
    //     $regex_special = '/[!@#$%^&*()\=+{};:<.>§~]/';

    //     if (preg_match_all($regex_special, $string) > 0) {
    //         $this->form_validation->set_message('check_inavlid_char', 'The {field} field contains invalid characters.');
    //         return false;
    //     }
    //     return true;
    // }

    // public function weight_check($val)
    // {
    //     if (!is_numeric($val)) {
    //         $this->form_validation->set_message('weight_check', 'The {field} field must be number or decimal.');
    //         return false;
    //     } else {
    //         return true;
    //     }
    // }

    // public function percent_check($val)
    // {
    //     if ($val > 100) {
    //         $this->form_validation->set_message('percent_check', 'The {field} field must be less than or equals 100.');
    //         return false;
    //     } else {
    //         return true;
    //     }
    // }

    // public function valid_url($url)
    // {
    //     $pattern = "/^((ht|f)tp(s?)\:\/\/|~/|/)?([w]{2}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?/";
    //     if (!preg_match($pattern, $url)) {
    //         return false;
    //     }

    //     return true;
    // }

    // public function alpha_space($fullname)
    // {
    //     if (!preg_match('/^[a-zA-Z\s]+$/', $fullname)) {
    //         $this->form_validation->set_message('alpha_space', 'The %s field may only contain alpha characters & White spaces');
    //         return false;
    //     } else {
    //         return true;
    //     }
    // }

    public function notifications()
    {
        // $condition                =    array("user_type"=>"U");
        $data["data"] = $this->M_admin->getnotifications();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/notifications", $data);
        $this->load->view("admin/footer");
    }

    public function sendNotification()
    {
        if (($bnotify_id = $this->M_admin->add_edit_notification())) {
            $notify_data = $this->M_admin->get_send_notification($bnotify_id);

            if ($notify_data) {

                //$where ='registration_type = U OR registration_type = C';
                $user_data = $this->M_admin->get_users1();
                //print_r($user_data);exit;
                $fcm_tokens = [];
                $notification_data = [];

                $title = $notify_data->title;
                $description = $notify_data->description;
                $url = $notify_data->url;

                $ntype = "public-notification";
                $imageURL = "";

                if (file_exists("uploads/notifications/" . $notify_data->image) && is_file("uploads/notifications/" . $notify_data->image)) {
                    $imageURL = base_url() . "uploads/notifications/" . $notify_data->image;
                }

                $notification_id = time();

                $this->load->library("FCM_Notification");

                foreach ($user_data as $row) {
                    if (!empty($row->firebase_user_key)) {
                        $notification_data["Notifications/" . $row->firebase_user_key . "/" . $notification_id] = ["title" => $title,
                            "description" => $description,
                            "notificationType" => $ntype,
                            "createdAt" => gmdate("d-m-Y H:i:s", $notification_id),
                            "orderID" => "0",
                            "url" => $url,
                            "imageURL" => $imageURL,
                            "read" => "0",
                            "seen" => "0"];
                    }

                    if (!empty($row->user_device_token)) {
                        $fcm_tokens[] = $row->user_device_token;
                        // $this->fcm_notification->send_single_notification($row->user_device_token, ["title" => $title,
                        //                                                                 "body" => $description,
                        //                                                                 "icon"=>'myicon',
                        //                                                                 "sound" =>'default',
                        //                                                                 "click_action" => "EcomNotification"],
                        //                                                                 ["type" => "public-notification",
                        //                                                                 "notificationID" => $notification_id,
                        //                                                                 "orderID" => "",
                        //                                                                 "imageURL" => $imageURL]);
                        //var_dump($this->fcm_notification->curl_error, $this->fcm_notification->curl_response);
                    }
                }

                if (count($notification_data) > 0) {
                    $fb_database = get_firebase_refrence();
                    $fb_database->getReference()->update($notification_data);
                }

                if (count($fcm_tokens) > 0) {
                    // $firebase = get_firebase_refrence(false);

                    // $messaging = $firebase->getMessaging();

                    // //$message =  Kreait\Firebase\Messaging\CloudMessage::new(); // Any instance of Kreait\Messaging\Message

                    // $message = Kreait\Firebase\Messaging\CloudMessage::withNotification(["title" => $title,
                    // "body" => $description,
                    // "icon"=>'myicon',
                    // "sound" =>'default',
                    // "click_action" => "EcomNotification"])->withData(["type" => "public-notification",
                    // "notificationID" => $notification_id,
                    // "orderID" => "",
                    // "imageURL" => $imageURL]);

                    // $sendReport = $messaging->sendMulticast($message, $deviceTokens);

                    $this->fcm_notification->send_multicast_notification(
                        $fcm_tokens,
                        array("title" => $title,
                        "body" => $description,
                        "icon" => 'myicon',
                        "sound" => 'default',
                        "click_action" => "EcomNotification"),
                        array("type" => "public-notification",
                            "notificationID" => $notification_id,
                            "orderID" => "",
                        "imageURL" => $imageURL)
                    );
                    // var_dump($this->fcm_notification->curl_error, $this->fcm_notification->curl_response);
                }

                $status = "1";
            } else {
                $status = "0";
            }
        } else {
            $status = "0";
        }

        echo json_encode(["status" => $status]);
    }

    public function add_edit_notification()
    {

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_notification", $data);
        $this->load->view("admin/footer");
    }

    public function deleteNotification()
    {
        $id = $_POST['id'];
        echo $this->M_admin->deleteNotification($id);
    }

    public function loadOrderStatus($order_status=0,$driver_id=0)
    {
        $data = array();
        $data["product_list"] = [];//$this->M_product->getAllProducts();
        $data["order_status"] = $order_status;
        $data["driver_id"] = $driver_id;

        $data["filter_status"] = $this->input->get('status', true);
        if ( is_null($data["filter_status"]) ) {
            $data["filter_status"] = -1;
        }
        if($data["filter_status"]==-1 && $order_status > 0){
            $data["filter_status"]=$order_status;
        }
        $data['order_type'] = $this->input->get("order_type");

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/order_status", $data);
        $this->load->view("admin/footer");
    }

    // Overall Sales Report
    public function overAllSalesReport()
    {
        $data['page'] = 1;
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ["segment" => "overall_sales_report"]);
        $this->load->view("admin/over_all_sales_report", $data);
        $this->load->view("admin/footer");
    }

    public function loadOverAllSalesReport( $page=1 )
    {
        $this->load->model("Overall_report_model", "overall_report");

        $filter_field   = $this->input->post('filter_field', true);
        $filter_keyword = $this->input->post('filter_keyword', true);
        $filter_status  = $this->input->post('filter_status', true);
        $limit          = (int) $this->input->post('limit', true);

        $page = ($page <= 0) ? 1 : $page;
        $limit = (int) $limit;
        $limit = ($limit <= 0) ? 20 : $limit;
        $offset = ($page - 1) * $limit;

        $search_params  = compact('filter_field', 'filter_keyword', 'filter_status');

        $total_records  = $this->overall_report->getSalesReportCount($search_params);
        $result = $this->overall_report->getSalesReport($search_params, $limit, $offset);

        $data = [];
        $dynamicColumns = [];

        $tz     = new DateTimeZone('Asia/Dubai');

        foreach ( $result as $row ) {
            $row->dynamic_columns = [];
            $category_names = explode('###', $row->product_category_name);
            $row->product_category_name = implode(' > ', array_unique($category_names));
            $row->estimated_arrival_date = '';
            $row->order_accepted_date = '';
            $row->order_ready_for_deliver_date = '';
            $row->order_dispatched_date = '';
            $row->order_delivered_date = '';
            $row->order_driver_accepted_date = '';
            $row->accepted_duration_shop = '';
            $row->working_duration_shop = '';
            $row->accepted_duration_driver = '';
            $row->pickup_duration_driver = '';
            $row->to_deliver_duration_driver = '';
            $row->total_duration_shop = '';

            $order_date = new DateTime($row->order_date, $tz);
            if ( $row->delivery_time_max > 0 ) {
                $order_date->add(new DateInterval('P'. $row->delivery_time_max .'D'));
                $row->estimated_arrival_date = $order_date->format('d-F-Y');
            }

            if (! empty($row->product_variant_id) ) {
                $variants = explode('###', $row->product_variant_id);
                foreach ( $variants as $variant ) {
                    $attribute = explode('=', $variant);
                    if ( count($attribute) < 2 ) {
                        continue;
                    }
                    $t_col_name = "attribute-" . url_title(strtolower($attribute[1]));
                    if ( array_key_exists($t_col_name, $dynamicColumns) === FALSE ) {
                        $dynamicColumns[$t_col_name] = $attribute[1];
                    }
                    $t_value = $attribute[2] ?? '';
                    $row->dynamic_columns[$t_col_name] = $t_value;
                }
            }
            if (! empty($row->category_attribute_value) ) {
                $variants = explode('###', $row->category_attribute_value);
                foreach ( $variants as $variant ) {
                    $attribute = explode('=', $variant);
                    if ( count($attribute) < 2 ) {
                        continue;
                    }
                    $t_col_name = "attribute-" . url_title(strtolower($attribute[0]));
                    if ( array_key_exists($t_col_name, $dynamicColumns) === FALSE ) {
                        $dynamicColumns[$t_col_name] = $attribute[0];
                    }
                    $t_value = !empty($attribute[2]) ? $attribute[2] : $attribute[1];
                    $row->dynamic_columns[$t_col_name] = $t_value;
                }
            }
            if (! empty($row->order_status_history) ) {
                $status_history = explode('###', $row->order_status_history);
                $status_history = array_unique($status_history);
                foreach ( $status_history as $status ) {
                    $status = explode('/', $status);
                    $t_order_status = $status[0] ?? 0;
                    $t_driver_status = $status[1] ?? 0;
                    $t_changed_date = $status[2] ?? '';
                    if ( empty($t_changed_date) ) {
                        continue;
                    }
                    // Order Accepted Date
                    if ( empty($row->order_accepted_date) && ($t_order_status == ORDER_STATUS_ACCEPTED) ) {
                        $row->order_accepted_date = $t_changed_date;
                    }
                    // Order Dispatched Date
                    if ( empty($row->order_ready_for_deliver_date) && ($t_order_status == ORDER_STATUS_READY) ) {
                        $row->order_ready_for_deliver_date = $t_changed_date;
                    }
                    // Order Dispatched Date
                    if ( empty($row->order_dispatched_date) && ($t_order_status == ORDER_STATUS_DISPATCHED) ) {
                        $row->order_dispatched_date = $t_changed_date;
                    }
                    // Order Delivered Date
                    if ( empty($row->order_delivered_date) && ($t_order_status == ORDER_STATUS_DELIVERED) ) {
                        $row->order_delivered_date = $t_changed_date;
                    }
                    // Driver Accepted Date
                    if ( ($t_order_status == ORDER_STATUS_READY) && ($t_driver_status == DRIVER_STATUS_ACCEPTED) ) {
                        $row->order_driver_accepted_date = $t_changed_date;
                    }
                }

                $order_date         = new DateTime($row->order_date, $tz);
                $order_date_tstamp  = $order_date->getTimestamp();
                $accepted_tstamp    = '';
                $ready_tstamp       = '';
                $driver_accepted_tstamp = '';
                $dispathed_tstamp   = '';

                if ( !empty($row->order_accepted_date) ) {
                    $accepted_date = new DateTime($row->order_accepted_date, $tz);
                    $accepted_tstamp = $accepted_date->getTimestamp();
                    $row->accepted_duration_shop = timespan($order_date_tstamp, $accepted_tstamp, 5);
                }
                if ( !empty($accepted_tstamp) && !empty($row->order_ready_for_deliver_date) ) {
                    $ready_date = new DateTime($row->order_ready_for_deliver_date, $tz);
                    $ready_tstamp = $ready_date->getTimestamp();
                    $row->working_duration_shop = timespan($accepted_tstamp, $ready_tstamp, 5);
                }
                if ( !empty($ready_tstamp) && !empty($row->order_driver_accepted_date) ) {
                    $driver_accepted_date = new DateTime($row->order_driver_accepted_date, $tz);
                    $driver_accepted_tstamp = $driver_accepted_date->getTimestamp();
                    $row->accepted_duration_driver = timespan($ready_tstamp, $driver_accepted_tstamp, 5);
                }
                if ( !empty($driver_accepted_tstamp) && !empty($row->order_dispatched_date) ) {
                    $dispatched_date = new DateTime($row->order_dispatched_date, $tz);
                    $dispathed_tstamp = $dispatched_date->getTimestamp();
                    $row->pickup_duration_driver = timespan($driver_accepted_tstamp, $dispathed_tstamp, 5);
                }
                if ( !empty($ready_tstamp) ) {
                    $row->total_duration_shop = timespan($order_date_tstamp, $ready_tstamp, 5);
                }
                if ( !empty($dispathed_tstamp) && !empty($row->order_delivered_date) ) {
                    $delivered_date = new DateTime($row->order_delivered_date, $tz);
                    $delivered_tstamp = $delivered_date->getTimestamp();
                    $row->to_deliver_duration_driver = timespan($dispathed_tstamp, $delivered_tstamp, 5);
                }
            }

            $data[] = $row;
        }

        ksort($dynamicColumns);

        $pagination_links = '';
        if ($total_records > 0) {
            $this->load->library('pagination');

            $config['base_url'] = base_url() . 'admin/C_admin/loadOverAllSalesReport';
            $config['total_rows'] = $total_records;
            $config['per_page'] = $limit;
            $config["uri_segment"] = 4;

            // custom paging configuration
            $config['num_links'] = 4;
            $config['use_page_numbers'] = true;
            $config['reuse_query_string'] = true;

            $config['full_tag_open'] = '<ul class="pagination" id="overall-sales-report-pagination">';
            $config['full_tag_close'] = '</ul>';

            $config['first_link'] = $this->lang->line('first');
            $config['first_tag_open'] = '<li>';
            $config['first_tag_close'] = '</li>';

            $config['last_link'] = $this->lang->line('last');
            $config['last_tag_open'] = '<li>';
            $config['last_tag_close'] = '</li>';

            $config['next_link'] = '&gt;';
            $config['next_tag_open'] = '<li>';
            $config['next_tag_close'] = '</li>';

            $config['prev_link'] = '&lt;';
            $config['prev_tag_open'] = '<li>';
            $config['prev_tag_close'] = '</li>';

            $config['cur_tag_open'] = '<li class="active"><span>';
            $config['cur_tag_close'] = '</span></li>';

            $config['num_tag_open'] = '<li>';
            $config['num_tag_close'] = '</li>';

            $this->pagination->initialize($config);

            // build paging links
            $pagination_links = $this->pagination->create_links();
        }

        $this->data = [
            'data' => $data,
            'dynamicColumns' => $dynamicColumns,
            'productGender' => [
                'm' => 'Male',
                'f' => 'Female',
                'u' => 'Unisex',
            ],
            'deliveryStatuses' => $this->config->item('order_delivery_statuses', 'app'),
            'driverStatuses' => $this->config->item('order_driver_statuses', 'app'),
            'pagination_links' => $pagination_links,
        ];

        echo $this->load->view("admin/over_all_sales_report_table", $this->data, TRUE);
        exit;
    }

    public function overAllSalesReportXlsUrl()
    {
        $filter_field   = $this->input->post('filter_field', true);
        $filter_keyword = $this->input->post('filter_keyword', true);
        $filter_status  = $this->input->post('filter_status', true);

        echo site_url("admin/C_admin/overAllSalesReportXls?filter_field={$filter_field}&filter_keyword={$filter_keyword}&filter_status=$filter_status");
    }

    public function overAllSalesReportXls()
    {
        $this->load->model("Overall_report_model", "overall_report");

        $filter_field   = $this->input->get('filter_field', true);
        $filter_keyword = $this->input->get('filter_keyword', true);
        $filter_status  = $this->input->get('filter_status', true);

        $search_params  = compact('filter_field', 'filter_keyword', 'filter_status');

        $result = $this->overall_report->getSalesReport($search_params);

        $data = [];
        $dynamicColumns = [];

        $order_numbers = [];
        foreach ( $result as $row ) {
            $row->dynamic_columns = [];
            $category_names = explode('###', $row->product_category_name);
            $row->product_category_name = implode(' > ', array_unique($category_names));
            $row->order_accepted_date = '';
            $row->order_dispatched_date = '';
            $row->order_delivered_date = '';
            $row->order_driver_accepted_date = '';
            $row->accepted_duration_shop = '';
            $row->working_duration_shop = '';
            $row->accepted_duration_driver = '';
            $row->pickup_duration_driver = '';
            $row->to_deliver_duration_driver = '';
            $row->total_duration_shop = '';

            if ( array_key_exists($row->order_block_id, $order_numbers) == FALSE ) {
                $order_numbers[$row->order_block_id] = [];
                $order_number = 0;
                $product_number = 0;
            }
            if ( array_key_exists($row->store_id, $order_numbers[$row->order_block_id]) == FALSE ) {
                $order_numbers[$row->order_block_id][$row->store_id] = [];
                $order_number++;
                $product_number = 0;
            }

            $product_number++;

            $row->order_number      = sprintf("%05d", $row->order_block_id) .'.'. $order_number;
            $row->product_number    = sprintf("%05d", $row->order_block_id) .'.'. $order_number .'.'. $product_number;

            $order_date = new DateTime($row->order_date, $tz);
            if ( $row->delivery_time_max > 0 ) {
                $order_date->add(new DateInterval('P'. $row->delivery_time_max .'D'));
                $row->estimated_arrival_date = $order_date->format('d-F-Y');
            }

            if (! empty($row->product_variant_id) ) {
                $variants = explode('###', $row->product_variant_id);
                foreach ( $variants as $variant ) {
                    $attribute = explode('=', $variant);
                    if ( count($attribute) < 2 ) {
                        continue;
                    }
                    $t_col_name = "attribute-" . url_title(strtolower($attribute[1]));
                    if ( array_key_exists($t_col_name, $dynamicColumns) === FALSE ) {
                        $dynamicColumns[$t_col_name] = $attribute[1];
                    }
                    $t_value = $attribute[2] ?? '';
                    $row->dynamic_columns[$t_col_name] = $t_value;
                }
            }
            if (! empty($row->category_attribute_value) ) {
                $variants = explode('###', $row->category_attribute_value);
                foreach ( $variants as $variant ) {
                    $attribute = explode('=', $variant);
                    if ( count($attribute) < 2 ) {
                        continue;
                    }
                    $t_col_name = "attribute-" . url_title(strtolower($attribute[0]));
                    if ( array_key_exists($t_col_name, $dynamicColumns) === FALSE ) {
                        $dynamicColumns[$t_col_name] = $attribute[0];
                    }
                    $t_value = !empty($attribute[2]) ? $attribute[2] : $attribute[1];
                    $row->dynamic_columns[$t_col_name] = $t_value;
                }
            }
            if (! empty($row->order_status_history) ) {
                $status_history = explode('###', $row->order_status_history);
                $status_history = array_unique($status_history);
                foreach ( $status_history as $status ) {
                    $status = explode('/', $status);
                    $t_order_status = $status[0] ?? 0;
                    $t_driver_status = $status[1] ?? 0;
                    $t_changed_date = $status[2] ?? '';
                    if ( empty($t_changed_date) ) {
                        continue;
                    }
                    // Order Accepted Date
                    if ( empty($row->order_accepted_date) && ($t_order_status == ORDER_STATUS_ACCEPTED) ) {
                        $row->order_accepted_date = $t_changed_date;
                    }
                    // Order Dispatched Date
                    if ( empty($row->order_ready_for_deliver_date) && ($t_order_status == ORDER_STATUS_READY) ) {
                        $row->order_ready_for_deliver_date = $t_changed_date;
                    }
                    // Order Dispatched Date
                    if ( empty($row->order_dispatched_date) && ($t_order_status == ORDER_STATUS_DISPATCHED) ) {
                        $row->order_dispatched_date = $t_changed_date;
                    }
                    // Order Delivered Date
                    if ( empty($row->order_delivered_date) && ($t_order_status == ORDER_STATUS_DELIVERED) ) {
                        $row->order_delivered_date = $t_changed_date;
                    }
                    // Driver Accepted Date
                    if ( ($t_order_status == ORDER_STATUS_READY) && ($t_driver_status == DRIVER_STATUS_ACCEPTED) ) {
                        $row->order_driver_accepted_date = $t_changed_date;
                    }
                }

                $order_date         = new DateTime($row->order_date, $tz);
                $order_date_tstamp  = $order_date->getTimestamp();
                $accepted_tstamp    = '';
                $ready_tstamp       = '';
                $driver_accepted_tstamp = '';
                $dispathed_tstamp   = '';

                if ( !empty($row->order_accepted_date) ) {
                    $accepted_date = new DateTime($row->order_accepted_date, $tz);
                    $accepted_tstamp = $accepted_date->getTimestamp();
                    $row->accepted_duration_shop = timespan($order_date_tstamp, $accepted_tstamp, 5);
                }
                if ( !empty($accepted_tstamp) && !empty($row->order_ready_for_deliver_date) ) {
                    $ready_date = new DateTime($row->order_ready_for_deliver_date, $tz);
                    $ready_tstamp = $ready_date->getTimestamp();
                    $row->working_duration_shop = timespan($accepted_tstamp, $ready_tstamp, 5);
                }
                if ( !empty($ready_tstamp) && !empty($row->order_driver_accepted_date) ) {
                    $driver_accepted_date = new DateTime($row->order_driver_accepted_date, $tz);
                    $driver_accepted_tstamp = $driver_accepted_date->getTimestamp();
                    $row->accepted_duration_driver = timespan($ready_tstamp, $driver_accepted_tstamp, 5);
                }
                if ( !empty($driver_accepted_tstamp) && !empty($row->order_dispatched_date) ) {
                    $dispatched_date = new DateTime($row->order_dispatched_date, $tz);
                    $dispathed_tstamp = $dispatched_date->getTimestamp();
                    $row->pickup_duration_driver = timespan($driver_accepted_tstamp, $dispathed_tstamp, 5);
                }
                if ( !empty($ready_tstamp) ) {
                    $row->total_duration_shop = timespan($order_date_tstamp, $ready_tstamp, 5);
                }
                if ( !empty($dispathed_tstamp) && !empty($row->order_delivered_date) ) {
                    $delivered_date = new DateTime($row->order_delivered_date, $tz);
                    $delivered_tstamp = $delivered_date->getTimestamp();
                    $row->to_deliver_duration_driver = timespan($dispathed_tstamp, $delivered_tstamp, 5);
                }

            }

            $data[] = $row;
        }

        ksort($dynamicColumns);

        $productGender = [
            'm' => 'Male',
            'f' => 'Female',
            'u' => 'Unisex',
        ];
        $deliveryStatuses = $this->config->item('order_delivery_statuses', 'app');
        $driverStatuses = $this->config->item('order_driver_statuses', 'app');

        $fileName = 'overall_sales_report.xls';

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        $columnHeaders = ['#', 'Bill No', 'Order Number', 'Product Number', 'Order Id', 'Order Date', 'Estimated Arrival Date', 'Product Id', 'Product Name', 'Product Category', 'Product Type', 'Unit Price', 'Qty.', 'Sub Total', 'Vendor Commission', 'Khiat Commission', 'Order Status', 'Requested for Tailor', 'Customer Id', 'Customer Name', 'Customer Email', 'Customer Mobile', 'Customer City', 'Shop Id', 'Shop Name', 'Shop Mobile', 'Shop Location', 'Driver Id', 'Driver', 'Driver Mobile No.', 'Driver Vehicle No.', 'Pending - Shop Date', 'Accepted - Shop Date', 'Ready for Deliver - Shop', 'Dispatched - Shop', 'Pending - Delivery', 'Accepted - Delivery', 'Start Journey - Delivery', 'Delivered - Delivery', 'Accepted Duration - Shop', 'Working Duration - Shop', 'Accepted Duration - Delivery', 'Pickup Duration - Delivery', 'Pickup to Delivery Duration', 'Total Duration in Shop'];
        foreach ($dynamicColumns as $dColId => $dColName) {
            $columnHeaders[] = $dColName;
        }
        echo implode("\t", $columnHeaders) . "\n";

        $i = 0;
        foreach ($data as $row) {
            $i++;

            $measurement_status = '';
            if ( $row->tailor_request ) {
                $measurement_status = 'Requested Tailor';
            } elseif ( $row->measurement_id > 0 ) {
                $measurement_status = 'Measurement Added';
            }

            $d = [
                $i,
                sprintf("%05d", $row->order_block_id),
                $row->order_number,
                $row->product_number,
                $row->order_no,
                get_date_in_timezone('Asia/Dubai', $row->order_date, 'd-F-Y g:i:s A'),
                $row->estimated_arrival_date,
                $row->product_id,
                $row->product_name,
                $row->product_category_name,
                $productGender[$row->product_gender],
                $row->unit_price,
                $row->purchase_qty,
                $row->sub_total,
                $row->vendor_commission,
                $row->khiat_commission,
                $deliveryStatuses[$row->deliver_status][1],
                $measurement_status,
                $row->customer_id,
                $row->customer_name,
                $row->customer_email_id,
                $row->customer_shipping_phone_number,
                $row->customer_shipping_city_name,
                $row->store_id,
                $row->store_name,
                $row->store_mobile_number,
                $row->store_city_name,
                $row->driver_id,
                $row->driver_name,
                $row->driver_mobile_number,
                $row->vehicle_reg_no,
                (!empty($row->order_accepted_date) ? get_date_in_timezone('Asia/Dubai', $row->order_accepted_date, 'd-F-Y g:i:s A') : ''),
                (!empty($row->order_ready_for_deliver_date) ? get_date_in_timezone('Asia/Dubai', $row->order_ready_for_deliver_date, 'd-F-Y g:i:s A') : ''),
                (!empty($row->order_dispatched_date) ? get_date_in_timezone('Asia/Dubai', $row->order_dispatched_date, 'd-F-Y g:i:s A') : ''),
                (!empty($row->order_ready_for_deliver_date) ? get_date_in_timezone('Asia/Dubai', $row->order_ready_for_deliver_date, 'd-F-Y g:i:s A') : ''),
                (!empty($row->order_driver_accepted_date) ? get_date_in_timezone('Asia/Dubai', $row->order_driver_accepted_date, 'd-F-Y g:i:s A') : ''),
                (!empty($row->order_dispatched_date) ? get_date_in_timezone('Asia/Dubai', $row->order_dispatched_date, 'd-F-Y g:i:s A') : ''),
                (!empty($row->order_delivered_date) ? get_date_in_timezone('Asia/Dubai', $row->order_delivered_date, 'd-F-Y g:i:s A') : ''),
                $row->accepted_duration_shop,
                $row->working_duration_shop,
                $row->accepted_duration_driver,
                $row->pickup_duration_driver,
                $row->to_deliver_duration_driver,
                $row->total_duration_shop,
            ];
            foreach ($dynamicColumns as $dColId => $dColName) {
                if (array_key_exists($dColId, $row->dynamic_columns) !== FALSE) {
                    $d[] = $row->dynamic_columns[$dColId];
                }
            }
            echo implode("\t", $d) . "\n";
        }
        exit;
    }

    public function addEditCoupon()
    {
        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('category_language_code' => $language, 'category_status' => 1);
        $data["category_list"] = $this->M_product->getCategoriesCondition($condition);

        $param = array('user_id' => $this->session->userdata('user_id'));
        $data["productList"] = $this->M_product->getProductNameId($param);

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ["segment" => "list_coupon"]);
        $this->load->view("admin/add_edit_coupon", $data);
        $this->load->view("admin/footer");
    }

    public function listCoupon()
    {
        $param = [
            'coupon_status' => 1
        ];
        $data['coupon_list'] = $this->M_product->getCouponDetails($param);

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/list_coupon", $data);
        $this->load->view("admin/footer");
    }

    public function validate_coupon_code($code){
        if(!empty($code)){
            $this->load->model("Common");
            $id = $this->input->post("id");
            $check = $this->Common->get_all_by_need('coupon',['*'],['coupon_code'=>$code,'coupon_id != '=>$id]);
            if(!empty($check)){
                $this->form_validation->set_message('validate_coupon_code', 'Coupon code already used');
                return FALSE;
            }
        }
        return TRUE;
    }

    public function saveCoupon()
    {
        $this->form_validation->set_rules('txt_title', 'Title', 'trim|required');
        $this->form_validation->set_rules('txt_code', 'Coupon Code', 'trim|required|callback_validate_coupon_code');
        $this->form_validation->set_rules('txt_coupon_desc', 'Description', 'trim|required');
        $this->form_validation->set_rules('is_service', 'Type', 'trim|required');
        $this->form_validation->set_rules('txt_coupon_amount', 'Coupon Amount', 'trim|required|numeric|greater_than_equal_to[1]|less_than_equal_to[100]');
        $this->form_validation->set_rules('txt_expiry_date', 'Expiry Date', 'trim|required');
        $this->form_validation->set_rules('txt_limit_per_coup', 'Limit per coupon', 'trim|numeric');
        $this->form_validation->set_rules('txt_limit_user', 'Limit Per User', 'trim|numeric');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_title' => form_error('txt_title'),
                'txt_code' => form_error('txt_code'),
                'txt_coupon_desc' => form_error('txt_coupon_desc'),
                'txt_discount_type' => form_error('txt_discount_type'),
                'txt_coupon_amount' => form_error('txt_coupon_amount'),
                'txt_expiry_date' => form_error('txt_expiry_date'),
                'txt_minimum_spend' => form_error('txt_minimum_spend'),
                'txt_maximum_spend' => form_error('txt_maximum_spend'),
                'txt_limit_user' => form_error('txt_limit_user'),
                'txt_limit_X_coup' => form_error('txt_limit_X_coup'),
                'txt_limit_per_coup' => form_error('txt_limit_per_coup'),
                'is_service' => form_error('is_service'),
            );
            echo json_encode($data);
            exit();
        }
        // print_r($_POST);
        $_POST = $this->security->xss_clean($_POST);
        if (count($_POST) > 0) {
            $result = $this->M_product->saveCoupon($_POST);
            $data['status'] = $result;
            echo json_encode($data);
        }
    }

    public function deleteCoupon()
    {
        // print_r($_POST);

        echo $this->M_product->deleteCoupon($_POST);
    }


    public function listCashPointsAdmin()
    {

        $param = [];//array('user_id' => $this->session->userdata('user_id'));
        $data['cash_point_list'] = $this->M_admin->getAdminDepositedCashPoints();


        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ["segment" => "list_cash_points_admin"]);
        $this->load->view("admin/list_cash_points_admin", $data);
        $this->load->view("admin/footer");
    }

    public function addEditCashPointsAdmin()
    {
        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);

        $data["user_list"] = $this->M_admin->get_customer_users(['user_status' => 1]);

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ["segment" => "list_cash_points_admin"]);
        $this->load->view("admin/add_edit_cash_points_admin", $data);
        $this->load->view("admin/footer");
    }

    public function saveAdminCashPoints()
    {
        $this->form_validation->set_rules('txt_user', 'Title', 'trim|required');
        $this->form_validation->set_rules('txt_cash_point', 'Description', 'trim|required');
        $this->form_validation->set_rules('txt_cash_point_desc', 'Discount type', 'trim|required');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_user' => form_error('txt_title'),
                'txt_cash_point' => form_error('txt_coupon_desc'),
                'txt_cash_point_desc' => form_error('txt_discount_type')
            );
            echo json_encode($data);
            exit();
        }
        // print_r($_POST);
        $_POST = $this->security->xss_clean($_POST);
        if (count($_POST) > 0) {
            $result = $this->M_admin->saveAdminCashPoints($_POST);
            $data['status'] = $result;
            echo json_encode($data);
        }
    }

    public function deleteAdminCashPoint()
    {
        // print_r($_POST);

        echo $this->M_admin->deleteAdminCashPoint($_POST);
    }
    public function metaHomeList()
    {

        $data["meta_list"] = $this->M_admin->getMetaData();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/meta_home_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditMeta()
    {
        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('category_language_code' => $language, 'category_status' => 1);
        $data["category_list"] = $this->M_admin->getCategoriesCondition($condition);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_meta_home", $data);
        $this->load->view("admin/footer");
    }
    public function saveMetaData()
    {
        $data = array();
        $this->form_validation->set_rules('txt_meta_title', 'Meta Title', 'trim|required');
        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_meta_title' => form_error('txt_meta_title'),
            );
            echo json_encode($data);
            exit();
        }

        $inputArray['meta_title']                =    $_POST['txt_meta_title'] ;
        $inputArray['meta_keyword']              =    $_POST['txt_meta_keyword'] ;
        $inputArray['meta_description']          =    $_POST['txt_meta_description'] ;

        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['meta_tags_id'] = $_POST['id'];
        }
        $inputArray = $this->security->xss_clean($inputArray);
        $result = $this->M_admin->saveMetaData($inputArray,  'meta_tags_id', 'meta_tags');
        $data['status'] = $result;
        echo json_encode($data);
    }

    /*
    | -------------------------------------------------------------------------
    | Category Attributes
    | -------------------------------------------------------------------------
    */
    public function categoryAttributeList( $cat_encrypt_id = null )
    {
        $category_id = $cat_encrypt_id ? $this->M_product->decryptId($cat_encrypt_id) : 0;

        $attr_type_list = $this->M_admin->getCategoryAttributeTypes();
        $tmp = array();
        foreach ($attr_type_list as $row) {
            $tmp[$row->cat_attribute_type_id] = $row;
        }
        $attr_type_list = $tmp;
        unset($tmp);

        $condition = array(
            'c_attr.cat_attribute_is_fabric_name' => 0,
        );
        if ($category_id > 0) {
            $condition['c_attr.category_id'] = $category_id;
        }
        $data = array(
            "cat_encrypt_id" => $cat_encrypt_id,
            "category_id" => $category_id,
            "attr_type_list" => $attr_type_list,
            "attr_list" => $this->M_admin->getCategoryAttributes($condition),
            "category_record" => false,
        );
        if ($category_id > 0) {
            $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
            $condition = array('category_language_code' => $language, 'category_id' => $category_id);
            $category_record = $this->M_admin->getCategoriesCondition($condition);
            if (count($category_record) > 0) {
                $category_record = $category_record[0];
            }
            $data['category_record'] = $category_record;
        }

        // Build parent/Child category tree
        $category_list = $this->M_admin->getCategoryWithParent();
        $category_list = json_decode(json_encode($category_list), True);
        $buildTree = function( array $elements, $parent_id = 0 ) use ( &$buildTree ) {
            $branch = array();
            foreach ($elements as $element) {
                if ($element['category_parent_id'] == $parent_id) {
                    $children = $buildTree($elements, $element['category_id']);
                    if ($children) {
                        $element['children'] = $children;
                    }
                    $branch[] = $element;
                }
            }

            return $branch;
        };
        $data['category_list'] = $buildTree($category_list);

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/category_attribute_list", $data);
        $this->load->view("admin/footer");
    }

    public function saveCategoryAttribute()
    {
        $data = array();
        if($this->input->post('txtCategory')==""){
            $cat_id=$this->input->post('cat_id_hdn');
        }else{
            $this->form_validation->set_rules('txtCategory', 'Category', 'required');
            $cat_id=$this->input->post('txtCategory');
        }
        $this->form_validation->set_rules('txt_attr_name', 'Attribute name', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('txt_attr_name_arabic', 'Attribute name arabic', 'trim|required|max_length[200]|xss_clean');

        $this->form_validation->set_rules('txtType', 'Attribute Type', 'required');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_attr_name' => form_error('txt_attr_name'),
                'txt_attr_name_arabic' => form_error('txt_attr_name_arabic'),
                'txtCategory' => form_error('txtCategory'),
                'txtType' => form_error('txtType'),
            );
            echo json_encode($data);
            exit();
        }

        $inputArray['cat_attribute_name'] = $this->input->post('txt_attr_name');
        $inputArray['cat_attribute_status'] = $this->input->post('txtStatus');
        $inputArray['cat_attribute_name_arabic'] = $this->input->post('txt_attr_name_arabic');
        $inputArray['cat_attribute_type'] = $this->input->post('txtType');
        $inputArray['cat_attribute_sort_order'] = $this->input->post('txtOrder');
        $inputArray['category_id'] =  $cat_id;

        if ($this->input->post('id')) {
            $inputArray['cat_attribute_id'] = $this->input->post('id');
        } else {
            $inputArray['cat_attribute_created_date'] = gmdate("Y-m-d H:i:s");
        }

        $inputArray = $this->security->xss_clean($inputArray);

        $result = $this->M_admin->saveCategoryAttribute($inputArray);
        $data['status'] = $result;

        echo json_encode($data);

    }

    public function sortCategoryAttribute()
    {
        $cat_attribute_id = $this->input->post('id');
        $sort_order = $this->input->post('sort_order', true);
        $sort_order = (int)$sort_order;
        if ($cat_attribute_id && $sort_order > 0) {
           echo $this->M_admin->sortCategoryAttribute($cat_attribute_id, $sort_order) ? 1 : 0;
        }
        echo 0;
    }

    public function checkOrderExists()
    {
        $cat_id = $this->input->post('id');

        $res=$this->M_admin->checkOrderExists($cat_id);

        if(!empty($res)){
            echo 0;
        }else{
            echo 1;
        }

    }

    public function deleteCategoryAttribute()
    {
        $id = $this->input->post('id');
        echo $this->M_admin->deleteCategoryAttribute($id);
    }

    public function categoryAttributeVals( $encrypted_id = null)
    {
        if (empty($encrypted_id)) {
            redirect('/category_attribute_list', 'refresh');
        }
        $cat_attribute_id = $this->M_product->decryptId($encrypted_id);

        $cat_attribute_rec = $this->M_admin->getCategoryAttributes(compact('cat_attribute_id'));
        if (count($cat_attribute_rec) > 0) {
            $cat_attribute_rec = $cat_attribute_rec[0];
        } else {
            show_404();
        }
        $cat_attribute_val_type_id = $cat_attribute_rec->cat_attribute_type;

        $data = array(
            'encrypted_id' => $encrypted_id,
            'cat_attribute_rec' => $cat_attribute_rec,
            'cat_attribute_values' => $this->M_admin->getCategoryAttributeVals(compact('cat_attribute_id', 'cat_attribute_val_type_id')),
        );

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/category_attribute_vals", $data);
        $this->load->view("admin/footer");
    }

    public function addEditCategoryAttributeVals( $encrypted_attr_id, $encrypted_attr_val_id = null )
    {
        if (empty($encrypted_attr_id)) {
            redirect('/category_attribute_list', 'refresh');
        }
        $cat_attribute_id = $this->M_product->decryptId($encrypted_attr_id);

        $cat_attribute_rec = $this->M_admin->getCategoryAttributes(compact('cat_attribute_id'));
        if (count($cat_attribute_rec) > 0) {
            $cat_attribute_rec = $cat_attribute_rec[0];
        } else {
            show_404();
        }

        $action = '';
        if (!empty($encrypted_attr_val_id)) {
            // Action: Edit
            $action = 'edit';
            $cat_attribute_val_id = $this->M_product->decryptId($encrypted_attr_val_id);

            $cat_attribute_val_rec = $this->M_admin->getCategoryAttributeVals(compact('cat_attribute_val_id'));
            if (count($cat_attribute_val_rec) > 0) {
                $cat_attribute_val_rec = $cat_attribute_val_rec[0];
            } else {
                show_404();
            }

        } else {
            // Action: Create
            $action = 'create';
            $cat_attribute_val_id = NULL;
            $cat_attribute_val_rec = NULL;
        }

        $data = array(
            'encrypted_attr_id' => $encrypted_attr_id,
            'encrypted_attr_val_id' => $encrypted_attr_val_id,
            'action' => $action,
            'cat_attribute_id' => $cat_attribute_id,
            'cat_attribute_val_id' => $cat_attribute_val_id,
            'cat_attribute_rec' => $cat_attribute_rec,
            'cat_attribute_val_rec' => $cat_attribute_val_rec,
            'cat_attribute_val_image' => NULL,
        );
        if ($action == 'edit') {
            if ( $cat_attribute_val_rec->cat_attribute_val_image ) {
                $data['cat_attribute_val_image'] = site_url($this->config->item('upload_path') . $this->config->item('cat_attribute_value_icon_upload_dir') . $cat_attribute_val_rec->cat_attribute_val_image);
            }
        }

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", array("segment" => "add_edit_category_attribute_vals"));
        $this->load->view("admin/add_edit_category_attribute_vals", $data);
        $this->load->view("admin/footer");
    }

    public function saveCategoryAttributeVal()
    {
        $data = array();

        $attr_type_uid = $this->input->post('attr_type_uid', true);
        $cat_attribute_val_id = $this->input->post('attr_val_id', true);
        $current_image_file = "";
        if (!empty($cat_attribute_val_id)) {
            $cat_attribute_val_id = $this->M_product->decryptId($cat_attribute_val_id);
            $cat_attribute_val_record = $this->M_admin->getCategoryAttributeVals(['cat_attribute_val_id' => $cat_attribute_val_id]);
            if (! empty($cat_attribute_val_record)) {
                $current_image_file = $cat_attribute_val_record[0]->cat_attribute_val_image;
            }
        }

        $this->form_validation->set_rules('txt_attr_value', 'Value', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('txt_attr_value_arabic', 'Value arabic', 'trim|required|max_length[200]|xss_clean');

        if ($attr_type_uid == 'radio_button_group') {
            $this->form_validation->set_rules('txt_attr_label', 'Label', 'trim|required|max_length[100]|xss_clean');
            $this->form_validation->set_rules('txt_attr_label_arabic', 'Label arabic', 'trim|required|max_length[200]|xss_clean');
        }

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_attr_value' => form_error('txt_attr_value'),
                'txt_attr_value_arabic' => form_error('txt_attr_value_arabic'),
            );
            if ($attr_type_uid == 'radio_button_group') {
                $data['errors']['txt_attr_label'] = form_error('txt_attr_label');
                $data['errors']['txt_attr_label_arabic'] = form_error('txt_attr_label_arabic');
            }
            echo json_encode($data);
            exit();
        } else {
            if ($attr_type_uid == 'radio_image') {
                if ($_FILES["txt_attr_icon_image"]["name"] != "") {
                    $digits = 6;
                    $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

                    $filename = $_FILES["txt_attr_icon_image"]["name"];
                    $file_ext = pathinfo($filename, PATHINFO_EXTENSION);

                    $upload_config['upload_path'] = $this->config->item('upload_path') . $this->config->item('cat_attribute_value_icon_upload_dir');
                    $upload_config['allowed_types'] = 'gif|png|jpg|jpeg';
                    $upload_config['max_size'] = $this->config->item('cat_attribute_value_icon_image_max_size');
                    $upload_config['max_width'] = $this->config->item('cat_attribute_value_icon_image_max_width');
                    $upload_config['max_height'] = $this->config->item('cat_attribute_value_icon_image_max_width');
                    $upload_config['min_width'] = $this->config->item('cat_attribute_value_icon_image_min_width');
                    $upload_config['min_height'] = $this->config->item('cat_attribute_value_icon_image_min_width');
                    $upload_config['file_name'] = $randomNo . "." . $file_ext;

                    $this->load->library('upload', $upload_config);

                    if (!$this->upload->do_upload('txt_attr_icon_image')) {
                        $data['status'] = 0;
                        $data['errors'] = array(
                            'txt_attr_icon_image' => "File upload failed. " . $this->upload->display_errors(),
                        );
                        echo json_encode($data);
                        exit();
                    } else {
                        $inputArray['cat_attribute_val_image'] = $upload_config['file_name'];
                    }
                }
            }
        }
        $cat_attribute_id = $this->input->post('attr_id');

        $inputArray['cat_attribute_id'] = $this->M_product->decryptId($cat_attribute_id);
        $inputArray['cat_attribute_val_value'] = $this->input->post('txt_attr_value');
        $inputArray['cat_attribute_val_value_arabic'] = $this->input->post('txt_attr_value_arabic');
        if ($attr_type_uid == 'radio_button_group') {
            $inputArray['cat_attribute_val_label'] = $this->input->post('txt_attr_label');
            $inputArray['cat_attribute_val_label_arabic'] = $this->input->post('txt_attr_label_arabic');
        } else {
            $inputArray['cat_attribute_val_label'] = "";
            $inputArray['cat_attribute_val_label_arabic'] = "";
        }
        $inputArray['cat_attribute_val_status'] = $this->input->post('txtStatus');

        if (!empty($cat_attribute_val_id)) {
            $inputArray['cat_attribute_val_id'] = $cat_attribute_val_id;
        } else {
            $inputArray['cat_attribute_val_sort_order'] = 1;
        }

        $inputArray = $this->security->xss_clean($inputArray);

        $result = $this->M_admin->saveCategoryAttributeValue($inputArray);

        // Delete uploaded image / previous image based on status
        if ( array_key_exists('cat_attribute_val_image', $inputArray) !== FALSE) {
            if ( $result ) {
                if (! empty($current_image_file) ) {
                    unlink( $upload_config['upload_path'] . $current_image_file );
                }
            } else {
                unlink( $upload_config['upload_path'] . $inputArray['cat_attribute_val_image'] );
            }
        }
        $data['status'] = $result;

        echo json_encode($data);
    }

    public function sortCategoryAttributeValue()
    {
        $cat_attribute_val_id = $this->input->post('id');
        $sort_order = $this->input->post('sort_order', true);
        $sort_order = (int)$sort_order;
        if ($cat_attribute_val_id && $sort_order > 0) {
           echo $this->M_admin->sortCategoryAttributeValue($cat_attribute_val_id, $sort_order) ? 1 : 0;
        }
        echo 0;
    }

    public function deleteCategoryAttributeVal()
    {
        $id = $this->input->post('id');
        echo $this->M_admin->deleteCategoryAttributeValue($id);
    }


    /*
    | -------------------------------------------------------------------------
    | Category Measurement Points
    | -------------------------------------------------------------------------
    */
    public function categoryMeasurementPoints( $cat_encrypt_id = null )
    {
        if (empty($cat_encrypt_id)) {
            redirect( site_url('category_list') , 'refresh' );
        }
        $category_id = $this->M_product->decryptId($cat_encrypt_id);

        $data = array(
            'cat_encrypt_id' => $cat_encrypt_id,
            'category_id' => $category_id,
            'category_record' => null,
        );

        if ($category_id > 0) {
            $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
            $condition = array('category_language_code' => $language, 'category_id' => $category_id);
            $category_record = $this->M_admin->getCategoriesCondition($condition);
            if (count($category_record) > 0) {
                $category_record = $category_record[0];
            }
            $data['category_record'] = $category_record;
        }

        $condition = array(
            'cat.category_id' => $category_id
        );
        $data['measurement_points'] = $this->M_admin->getMeasurementPoints($condition);

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", array("segment" => "category_list"));
        $this->load->view("admin/category_measurement_points", $data);
        $this->load->view("admin/footer");
    }

    public function is_unique_measurement_point_uid( $uid )
    {
        if (! empty($uid) ) {
            $condition = ['msr_point.point_uid' => $uid];
            $point_id = (int) $this->input->post('id', true);
            if ( $point_id > 0 ) {
                $condition['msr_point.point_id !='] = $point_id;
            }
            $records = $this->M_admin->getMeasurementPoints($condition);
            if ( count($records) > 0 ) {
                $this->form_validation->set_message('is_unique_measurement_point_uid', 'This ID already exists. Please try another one.');
                return FALSE;
            }
        }
        return TRUE;
    }

    public function saveCategoryMeasurementPoint()
    {
        $this->form_validation->set_rules('txt_point_name', 'Name', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('txt_point_name_arabic', 'Name (Arabic)', 'trim|required|max_length[200]|xss_clean');
        $this->form_validation->set_rules('txt_point_uid', 'Unique ID', 'trim|required|max_length[30]|callback_is_unique_measurement_point_uid|xss_clean');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_point_name' => form_error('txt_point_name'),
                'txt_point_name_arabic' => form_error('txt_point_name_arabic'),
                'txt_point_uid' => form_error('txt_point_uid'),
            );
            echo json_encode($data);
            exit();
        }

        $point_is_required = $this->input->post('txt_point_required');
        if (! $point_is_required ) {
            $point_is_required = 0;
        }

        $inputArray['point_name'] = $this->input->post('txt_point_name');
        $inputArray['point_name_arabic'] = $this->input->post('txt_point_name');
        $inputArray['point_status'] = $this->input->post('txtStatus');
        $inputArray['point_uid'] = $this->input->post('txt_point_uid');
        $inputArray['point_is_required'] = $point_is_required;
        $inputArray['category_id'] = $this->input->post('txtCategory');

        if ($this->input->post('id') > 0) {
            $inputArray['point_id'] = $this->input->post('id');
        } else {
            $inputArray['point_created_date'] = gmdate("Y-m-d H:i:s");
        }

        $inputArray = $this->security->xss_clean($inputArray);

        $result = $this->M_admin->saveMeasurementPoints($inputArray);
        $data['status'] = $result;

        echo json_encode($data);
    }

    public function deleteCategoryMeasurementPoint()
    {
        $id = $this->input->post('id');
        echo $this->M_admin->deleteCategoryMeasurementPoint($id);
    }

    public function categoryMeasurementVals( $point_encrypt_id = null )
    {
        if (empty($point_encrypt_id)) {
            redirect( site_url('category_list') , 'refresh' );
        }

        $data = array(
            'point_encrypt_id' => $point_encrypt_id,
            'measurement_point' => null,
        );

        $point_id = $this->M_product->decryptId($point_encrypt_id);
        if (! $point_id ) {
            show_404();
        }
        $measurement_point = $this->M_admin->getMeasurementPointById($point_id);
        if (! $measurement_point ) {
            show_404();
        }
        $data['measurement_point'] = $measurement_point;
        $data['measurement_values'] = $this->M_admin->getMeasurementVals(array( 'measurement_point_id' => $measurement_point->point_id ));

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", array("segment" => "category_list"));
        $this->load->view("admin/category_measurement_vals", $data);
        $this->load->view("admin/footer");
    }

    public function saveCategoryMeasurementVal()
    {
        $this->form_validation->set_rules('txt_point_value', 'Value', 'trim|required|numeric|greater_than[0]|max_length[10]|xss_clean');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_point_value' => form_error('txt_point_value'),
            );
            echo json_encode($data);
            exit();
        }
        $point_id = $this->input->post('point_id');
        $measurement_point = $this->M_admin->getMeasurementPointById($point_id);
        if (! $measurement_point ) {
            echo 0;
            exit;
        }

        $inputArray['point_val_value'] = $this->input->post('txt_point_value');
        $inputArray['point_val_status'] = $this->input->post('txtStatus');
        $inputArray['measurement_point_id'] = $point_id;

        if ($this->input->post('id') > 0) {
            $inputArray['point_val_id'] = $this->input->post('id');
        }
        $inputArray = $this->security->xss_clean($inputArray);

        $condition = array(
            'measurement_point_id' => $point_id,
            'point_val_value' => $inputArray['point_val_value'],
        );
        if ( isset($inputArray['point_val_id']) ) {
            $condition['point_val_id !='] = $inputArray['point_val_id'];
        }
        $duplicate_values = $this->M_admin->getMeasurementVals($condition);
        if ( count($duplicate_values) > 0 ) {
            $data['status'] = 3;
            echo json_encode($data);
            exit();
        }

        $result = $this->M_admin->saveMeasurementValue($inputArray);
        $data['status'] = $result;

        echo json_encode($data);
    }

    public function deleteCategoryMeasurementVal()
    {
        $id = $this->input->post('id');
        echo $this->M_admin->deleteCategoryMeasurementValue($id);
    }
    public function get_order_list() {

        require_once APPPATH.'third_party/ozdemir-datatable/vendor/autoload.php';
        $datatable = new Datatables(new CodeigniterAdapter);

        $permission = $this->M_admin->getAdminPermissionsByMenu((int)  $this->session->userdata('admin_id'), 3);


        $order_no       = $this->input->post("order_no", true);
        $user_id        = $this->input->post("user_id", true);
        $search_condition = "";
        if($order_no !=""){
        $search_condition="and pod.order_no='".$order_no."'";
        }
        $status       = $this->input->post("status", true);
        if($status !=""){
            $search_condition="and pod.delivery_status=".$status;
        }

        $search_from_date       = $this->input->post("f_from_date", true);
        $search_to_date         = $this->input->post("f_to_date", true);

        if(strlen($search_from_date) > 5 && strlen($search_to_date) > 5 ) {
            $search_condition .=" and pod.order_placed_date::date >= '". date("Y-m-d", strtotime($search_from_date)) ."' and  pod.order_placed_date::date <= '". date("Y-m-d", strtotime($search_to_date)) ."'";
        }
        else if(strlen($search_from_date) > 5  ) {
            $search_condition .=" and pod.order_placed_date::date = '". date("Y-m-d", strtotime($search_from_date)) ."'";
        }
        $user_id = $this->M_product->decryptId($user_id);
        $this->M_admin->getOrderListDetails1($datatable,$user_id,$search_condition);

      //  $this->M_admin->get_customer_list($datatable, $search_condition);



        $datatable->edit("date", function ($data) {
            return date("d, F Y",  strtotime($data['date']));
        });

        $datatable->edit("sale_amount", function ($data) {
            return "AED ".$data['sale_amount'];
        });
        $datatable->edit("vat_price", function ($data) {
            return "AED ".$data['vat_price'];
        });
        $datatable->edit("khiat_commission", function ($data) {
            return "AED ".$data['khiat_commission'];
        });
        $datatable->edit("vendor_commission", function ($data) {
            return "AED ".$data['vendor_commission'];
        });

        $datatable->edit("status", function($data)  {

            if($data['status']==0){ $status= "Pending"; }
                                    else if($data['status']==1){ $status= "Ready to Deliver"; }
                                    else if($data['status']==2){ $status= "Accepted"; }
                                    else if($data['status']==3){ $status= "Dispatched"; }
                                    else if($data['status']==4){ $status= "Delivered"; }

            return $status;
        });


        $datatable->add('action', function($data) use ($permission) {
            $edit_action = '';
            if ($permission->perm_edit == 1) {
                $edit_action = '<a class="dropdown-item edit" href="'.base_url() . 'user_order_summary/' . $this->M_product->encryptId($data["id"]).'"> Order Summary</a>';
            }

            $status_button = '';

                $status_button = '<a class="dropdown-item removeThis" href="#" data-toggle="modal" data-target="#confirm-modal" for="'.$data['id'].'"> Status History</a>';



            /*
            if ($permission->perm_view == 1) {
                $action .= '<a style="margin-left:12px;" class="view" href="'.base_url() . 'cash_point_user_report/' . $this->M_product->encryptId($data['id']).'">
                                <i class="fa fa-money" id="detailView" for="'.$data['id'].'"></i>
                            </a>';
            }
            */

            $action .= <<<ACTION
            <div class="btn-group">
                <button type="button" class="btn btn-secondary btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    Action
                </button>
                <div class="dropdown-menu">

                    {$edit_action}
                    {$status_button}
                </div>
            </div>
ACTION;

			return $action;

        });

        $this->output->set_output( $datatable->generate() );
    }

    public function getKandoraDetails()
    {
        $history_id = $this->input->post('id');

        //$data['category_attributes']    =   $this->M_admin->getKandoraDetailsByHistoryId($history_id);
       // $data['measurement_points']     =   $this->M_admin->getTypeMeasurementByHistoryId($history_id);
        $data['product_attributes']     =   $this->M_admin->getProductAttributesByHistoryId($history_id);

        $this->load->view('admin/view_specifications', $data);
    }

    public function getProductVariationDetails()
    {
        $product_id= $this->input->post('product_id');
        $order_id = $this->input->post('block_id');
        if($product_id==""){
            $data['orderData']=$this->M_product->getOrderSummeryDetails($order_id);

        }else{
            $data['comments']=$this->M_product->getOrderCommentDetails($order_id,$product_id);
        }

        $this->load->view('admin/view_product_specifications',$data);

        if(!empty($res)){

        }else{

        }

    }
    // public function getDriverDetails()
    // {
    //     $product_id= $this->input->post('product_id');
    //     $order_id = $this->input->post('block_id');

    //         $data['driver_comments']=$this->M_product->getDriverCommentDetails($order_id,$product_id);


    //     $this->load->view('admin/view_product_specifications',$data);

    //     if(!empty($res)){

    //     }else{

    //     }

    // }
    public function getCustomerDetails()
    {

        $user_id = $this->input->post('user_id');
        $data['orderData']=$this->M_admin->getCustomerDetails($user_id);

        $this->load->view('admin/view_product_specifications',$data);

        if(!empty($res)){

        }else{

        }

    }
    private function _get_measurement_points( $user_id, $category_id=NULL )
    {
        $condition = [];
        if ( $category_id > 0 ) {
            $condition['ump.category_id'] = $category_id;
        }
        return $this->M_admin->get_measurement_points($user_id, "1", $condition);
    }

    public function GetMeasurementDetail(){
        $measurement_id=$this->input->post('measurement_id');
        $user_id=$this->input->post('user_id');
        $data['result'] = $this->measurementDetailById($user_id,$measurement_id);
      // echo '<pre>';print_r($data['result']);exit;
        $this->load->view("admin/measurement_ajax",$data);
    }
    public function measurementDetailById($user_id,$measurement_id){
        $result = $this->M_admin->get_measurement_point_detail($user_id, $measurement_id);
        $measurement_points = [];
        if (! empty($result) ) {
           $i = 0;
           foreach ($result as $row) {
               if ( $i == 0 ) {
                   $measurement_points = (object) [
                       'measurement_id' => $row->measurement_id,
                       'title' => $row->title,
                       'category_id' => $row->category_id,
                       'category_uid' => $row->category_uid,
                       'category_name' => $row->category_name,
                       'measurements' => [],
                   ];
               }
               $measurement_points->measurements[] = [
                   'point_id' => $row->point_id,
                   'point_uid' => $row->point_uid,
                   'point_name' => $row->point_name,
                   'is_required' => $row->is_required,
                   'selected_value' => $row->value,
                   'values' => $row->values,
               ];
               $i++;
           }
        }
        return $measurement_points;
    }

    public function workList()
    {
        $condition = array("user_type" => "D");
        $data["work_list"] = $this->M_admin->getWork();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/how_it_work_list", $data);
        $this->load->view("admin/footer");
    }

    public function testimonialList()
    {
        $data["testmonials"] = $this->M_admin->getTestimonialList();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/testimony_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditTestimonial()
    {
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_testimony");
        $this->load->view("admin/footer");
    }

    public function saveTestimonials()
    {

        $data = array();

        $this->form_validation->set_rules('txt_first_name', 'First name', 'trim|required');
        $this->form_validation->set_rules('txt_last_name', 'Last Name ', 'trim|required');
        $this->form_validation->set_rules('txt_testimonial', 'Testimonial', 'trim|required');

        if ($_POST['id'] <= 0 && empty($_FILES['txtFile']['name'])) {
           // $this->form_validation->set_rules('txtFile', ' image', 'required');
        }

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_first_name' => form_error('txt_first_name'),
                'txt_last_name' => form_error('txt_last_name'),
                'txt_testimonial' => form_error('txt_testimonial'),
                'txtFile' => form_error('txtFile'),
            );
            echo json_encode($data);
            exit();
        }

        if ($_FILES["txtFile"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFile"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'testimonials/';
            $config2['allowed_types'] = 'gif|jpg|png|pdf|doc';
            // $config2['max_size'] = 2000;
            $config2['max_width'] = 2000;
            $config2['max_height'] = 1200;
            $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('txtFile')) {
                //die("file upload failed");
                $data['status'] = 0;
                $data['errors'] = array(
                    'txtFile' => strip_tags($this->upload->display_errors()),
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['profile_image'] = $config2['file_name'];
            }
        }

        $inputArray['first_name'] = ucfirst($_POST['txt_first_name']);
        $inputArray['last_name'] = $_POST['txt_last_name'];
        $inputArray['user_type'] = 1;
        $inputArray['testimonial'] = $_POST['txt_testimonial'];
        $inputArray['testimonial_arabic'] = $_POST['txt_testimonial_arabic'];

        $inputArray['testimonial_status'] = $_POST['txtStatus'];
        $inputArray['testimonial_created_time'] = gmdate("Y-m-d H:i:s");
        $inputArray['testimonial_updated_time'] = gmdate("Y-m-d H:i:s");
        $inputArray['testimonial_created_by']   = 1;
        $inputArray['testimonial_updated_by']   = 1;



        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['testimonial_id'] = $_POST['id'];

            unset($inputArray['testimonial_created_time']);
            unset($inputArray['testimonial_created_by']);
            //    unset($inputArray2['bicreated_date']);
        }

        //  print_r($inputArray);

        $inputArray = $this->security->xss_clean($inputArray);


        $result = $this->M_admin->saveTestimonials($inputArray,  'testimonial_id', 'testimonial');

        $data['status'] = $result;
        echo json_encode($data);
    }

    public function deleteTestimonial()
    {
        $id = $_POST['id'];
        echo $this->M_admin->deleteTestimonial($id);
    }

    public function newsletter()
    {
        // $condition                =    array("user_type"=>"U");
        $data["data"] = $this->M_admin->getnotifications();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/notifications", $data);
        $this->load->view("admin/footer");
    }

    public function addEditHowItWorks()
    {
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_howitwork");
        $this->load->view("admin/footer");
    }

    public function saveHowItWork()
    {

        $data = array();

        $this->form_validation->set_rules('txt_title', 'First name', 'trim|required');
        $this->form_validation->set_rules('txt_title_arabic', 'Last Name ', 'trim|required');
        $this->form_validation->set_rules('txt_work_desc', 'Testimonial', 'trim|required');

        if ($_POST['id'] <= 0 && empty($_FILES['txtFile']['name'])) {
           // $this->form_validation->set_rules('txtFile', ' image', 'required');
        }

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_title' => form_error('txt_title'),
                'txt_title_arabic' => form_error('txt_title_arabic'),
                'txt_work_desc' => form_error('txt_work_desc'),
                'txtFile' => form_error('txtFile'),
            );
            echo json_encode($data);
            exit();
        }


        $inputArray['title'] = ucfirst($_POST['txt_title']);
        $inputArray['title_arabic'] = $_POST['txt_title_arabic'];

        $inputArray['work_desc'] = $_POST['txt_work_desc'];
        $inputArray['work_desc_arbic'] = $_POST['txt_work_desc_arabic'];

        $inputArray['work_status'] = $_POST['txtStatus'];
        $inputArray['created_date'] = gmdate("Y-m-d H:i:s");
        $inputArray['updated_date'] = gmdate("Y-m-d H:i:s");




        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['work_id'] = $_POST['id'];
            unset($inputArray['created_date']);

        }


        $inputArray = $this->security->xss_clean($inputArray);
        $result = $this->M_admin->saveTestimonials($inputArray,  'work_id', 'how_it_work');

        $data['status'] = $result;
        echo json_encode($data);
    }

    function get_date_in_timezone($timezone, $date, $format = "d-m-Y H:i:s", $server_time_zone = "Etc/GMT") {

        try {
            $timezone_server    = new DateTimeZone($server_time_zone);
            $timezone_user      = new DateTimeZone($timezone);
        }
        catch (Exception $e) {
            $timezone_server    = new DateTimeZone($server_time_zone);
            $timezone_user      = new DateTimeZone($server_time_zone);
        }


        $dt = new DateTime($date, $timezone_server);

        $dt->setTimezone($timezone_user);

        //var_dump($dt);exit;
        return $dt->format($format);

    }

    public function loadIssueReplyForm()
    {
        $id = (int) $this->input->post('id', true);
        $issue = $this->M_admin->getReportedIssue($id);
        echo $this->load->view('admin/report_issue_reply_modal', compact('issue'), true);
    }

    public function sendReplyToIssue()
    {
        if ( $this->input->is_ajax_request() ) {
            $status = "0";

            $this->form_validation->set_rules('order_issue_id', 'Issue ID', 'required');
            $this->form_validation->set_rules('issue_reply', 'Reply', 'required');
            if ( $this->form_validation->run() !== FALSE ) {
                $issue_id = (int) $this->input->post('order_issue_id', true);
                $issue_reply = $this->input->post('issue_reply', true);

                $issue = $this->M_admin->getReportedIssue($issue_id);
                if (! empty($issue) && empty($issue->issue_reply) ) {
                    $reply_data = [
                        'issue_reply' => $issue_reply,
                        'issue_reply_date' => gmdate("Y-m-d H:i:s"),
                    ];
                    $status = $this->M_admin->saveReplyToIssue($issue_id, $reply_data);
                    $status = (int) $status;

                    if ( $status ) {
                        $order_issue_types = $this->config->item('order_issue_types', 'app');

                        $email_message =  $this->load->view("email_templates/admin/order_reply_issue", [
                            "order_issue_types" => $order_issue_types,
                            "reply_data" => $reply_data,
                            "issue" => $issue,
                            "assets" => base_url()."email_assets/",
                        ], true);

                        if ( $issue->issue_type > 0 ) {
                            $subject    = "Replied to Order #{$issue->order_no}: {$order_issue_types[$issue->issue_type][1]}";
                        } else {
                            $subject    = "Replied to Order #{$issue->order_no}: Issue";
                        }
                        $to = $issue->user_email_id;

                        $this->load->library("Mail_function");
                        $this->mail_function->SendEmail($email_message, $subject, $to);
                    }
                }
            }

            echo $status;
        }
    }

    public function siteConfig()
    {
        $data = $this->M_admin->getSiteConfig();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ["segment" => "site_config"]);
        $this->load->view("admin/site_config", $data);
        $this->load->view("admin/footer");
    }

    public function saveSiteConfig()
    {
        if ( $this->input->is_ajax_request() ) {
            $data = [];

            //$this->form_validation->set_rules('cash_point_earning_perc', 'Cash Point Earnings', 'required|numeric|less_than_equal_to[100]');
            $this->form_validation->set_rules('default_shipping_charge', 'Default Shipping Charge', 'required|numeric');
            //$this->form_validation->set_rules('default_measurement_charge', 'Default Measurement Charge', 'required|numeric');
            //$this->form_validation->set_rules('user_invitation_earn_cash_points', 'User Invitation Reward Points', 'required|numeric');

            if ( $this->form_validation->run() !== FALSE ) {
                $data['status'] = $this->M_admin->setSiteConfig([
                    'cash_point_earning_perc' => $this->input->post('cash_point_earning_perc'),
                    'default_shipping_charge' => $this->input->post('default_shipping_charge'),
                    'default_measurement_charge' => $this->input->post('default_measurement_charge'),
                    'user_invitation_earn_cash_points' => $this->input->post('user_invitation_earn_cash_points'),
                ]);

            } else {
                $data['status'] = 0;
                $data['errors'] = array(
                    'cash_point_earning_perc' => form_error('cash_point_earning_perc'),
                    'default_shipping_charge' => form_error('default_shipping_charge'),
                    'default_measurement_charge' => form_error('default_measurement_charge'),
                    'user_invitation_earn_cash_points' => form_error('user_invitation_earn_cash_points'),
                );
                echo json_encode($data);
                exit();
            }

            echo json_encode($data);
        }
    }

    public function reportedOrderIssues()
    {
        $data["order_issue_types"] = $this->config->item("order_issue_types", "app");
        $data["reported_issues"] = $this->M_admin->getReportedIssues();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/reported_issues", $data);
        $this->load->view("admin/footer");
    }

    public function bankList()
    {
        $data['bank_list'] = $this->M_admin->getBankList();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/bank_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditBank( $encrypted_id=NULL )
    {
        $id = '';
        $bank_name = '';
        $bank_name_arabic = '';

        if ( $encrypted_id ) {
            $id = decryptor($encrypted_id);
            if ( $id > 0 ) {
                $bank_record = $this->M_admin->getBankById($id);
                if ( $bank_record ) {
                    $bank_name = $bank_record->bank_name;
                    $bank_name_arabic = $bank_record->bank_name_arabic;
                } else {
                    show_404();
                }
            } else {
                show_404();
            }
        }

        if ( $id > 0 ) {
            $heading = 'Edit';
        } else {
            $heading = 'Add';
        }

        $data = compact('id', 'heading', 'bank_name', 'bank_name_arabic');
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ["segment" => "bank_list"]);
        $this->load->view("admin/add_edit_bank", $data);
        $this->load->view("admin/footer");
    }

    public function saveBank()
    {
        if ( $this->input->is_ajax_request() ) {
            $data = [];

            $id = (int) $this->input->post('id', true);
            $this->form_validation->set_rules('bank_name', 'Bank Name English', 'required|max_length[100]');
            $this->form_validation->set_rules('bank_name_arabic', 'Bank Name Arabic', 'required|max_length[500]');

            if ( $this->form_validation->run() !== FALSE ) {
                $data['status'] = $this->M_admin->saveBank([
                    'id' => $id,
                    'bank_name' => (string) $this->input->post('bank_name', true),
                    'bank_name_arabic' => (string) $this->input->post('bank_name_arabic', true),
                ]);
            } else {
                $data['status'] = 0;
                $data['errors'] = array(
                    'bank_name' => form_error('bank_name'),
                    'bank_name_arabic' => form_error('bank_name_arabic'),
                );
                echo json_encode($data);
                exit();
            }

            echo json_encode($data);
        }
    }

    public function deleteBank()
    {
        if ( $this->input->is_ajax_request() ) {
            $id = (int) $this->input->post('id', true);
            echo $this->M_admin->deleteBank($id);
        }
    }

    /*
    *Offer Banks
    */
    public function offerBankList()
    {
        $data['bank_list'] = $this->M_admin->getOfferBankList();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/offer_bank_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditOfferBank( $encrypted_id=NULL )
    {
        $id = '';
        $bank_name = '';
        $bank_name_arabic = '';
        $bank_image="";

        if ( $encrypted_id ) {
            $id = decryptor($encrypted_id);
            if ( $id > 0 ) {
                $bank_record = $this->M_admin->getOfferBankById($id);
                if ( $bank_record ) {
                    $bank_name = $bank_record->bank_name;
                    $bank_name_arabic = $bank_record->bank_name_arabic;
                    $bank_image =   $bank_record->bank_image;
                } else {
                    show_404();
                }
            } else {
                show_404();
            }
        }

        if ( $id > 0 ) {
            $heading = 'Edit';
        } else {
            $heading = 'Add';
        }

        $data = compact('id', 'heading', 'bank_name', 'bank_name_arabic','bank_image');
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ["segment" => "offer_bank_list"]);
        $this->load->view("admin/add_edit_offer_bank", $data);
        $this->load->view("admin/footer");
    }

    public function saveOfferBank()
    {
        if ( $this->input->is_ajax_request() ) {
            $data = [];

            $id = (int) $this->input->post('id', true);
            $this->form_validation->set_rules('bank_name', 'Bank Name English', 'required|max_length[100]');
            $this->form_validation->set_rules('bank_name_arabic', 'Bank Name Arabic', 'required|max_length[500]');

            if ( $this->form_validation->run() !== FALSE ) {
                $bank_image = "";
                if ($_FILES["bank"]["name"] != "") {
                    $digits = 6;
                    $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

                    $filename2 = $_FILES["bank"]["name"];
                    $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

                    $config2['upload_path'] = $this->config->item('upload_path') . 'bank/';
                    $config2['allowed_types'] = 'gif|jpg|png|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('bank')) {
                        //die("file upload failed");
                        $data['status'] = 0;
                        $data['errors'] = array(
                            'bank' => "File upload failed due to " . $this->upload->display_errors(),
                        );
                        echo json_encode($data);
                        exit();
                    } else {
                        $bank_image = $config2['file_name'];
                    }
                }
                $data['status'] = $this->M_admin->saveOfferBank([
                    'id' => $id,
                    'bank_name' => (string) $this->input->post('bank_name', true),
                    'bank_name_arabic' => (string) $this->input->post('bank_name_arabic', true),
                    'bank_image'    =>  $bank_image
                ]);
            } else {
                $data['status'] = 0;
                $data['errors'] = array(
                    'bank_name' => form_error('bank_name'),
                    'bank_name_arabic' => form_error('bank_name_arabic'),
                );
                echo json_encode($data);
                exit();
            }

            echo json_encode($data);
        }
    }

    public function deleteOfferBank()
    {
        if ( $this->input->is_ajax_request() ) {
            $id = (int) $this->input->post('id', true);
            echo $this->M_admin->deleteOfferBank($id);
        }
    }

    /*
    *Bank Offer
    */
    public function bankOfferList()
    {
        $data['bank_list'] = $this->M_admin->getBankOfferList();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/bank_offer_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditBankOffer( $encrypted_id=NULL )
    {
        $id = '';
        $offer_title = '';
        $offer_description = '';
        $offer_image="";
        $bank_id =  "";
        $bank_list= $this->M_admin->getOfferBankList();
        if ( $encrypted_id ) {
            $id = decryptor($encrypted_id);
            if ( $id > 0 ) {
                $bank_record = $this->M_admin->getBankOfferById($id);
                if ( $bank_record ) {
                    $offer_title = $bank_record->offer_title;
                    $offer_description = $bank_record->offer_description;
                    $offer_image =   $bank_record->offer_image;
                    $bank_id =   $bank_record->bank_id;
                } else {
                    show_404();
                }
            } else {
                show_404();
            }
        }

        if ( $id > 0 ) {
            $heading = 'Edit';
        } else {
            $heading = 'Add';
        }

        $data = compact('id', 'heading', 'offer_title', 'offer_description','offer_image','bank_id','bank_list');
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar", ["segment" => "bank_offer_list"]);
        $this->load->view("admin/add_edit_bank_offer", $data);
        $this->load->view("admin/footer");
    }

    public function saveBankOffer()
    {
        if ( $this->input->is_ajax_request() ) {
            $data = [];

            $id = (int) $this->input->post('id', true);
            $this->form_validation->set_rules('bank_name', 'Bank Name', 'required');
            $this->form_validation->set_rules('offer_title', 'offer title', 'required|max_length[500]');
            $this->form_validation->set_rules('offer_description', 'offer description', 'required|max_length[500]');
            if ( $this->form_validation->run() !== FALSE ) {
                $offer_image = "";
                if ($_FILES["offer_image"]["name"] != "") {
                    $digits = 6;
                    $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

                    $filename2 = $_FILES["offer_image"]["name"];
                    $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

                    $config2['upload_path'] = $this->config->item('upload_path') . 'offer/';
                    $config2['allowed_types'] = 'gif|jpg|png|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('offer_image')) {
                        //die("file upload failed");
                        $data['status'] = 0;
                        $data['errors'] = array(
                            'offer_image' => "File upload failed due to " . $this->upload->display_errors(),
                        );
                        echo json_encode($data);
                        exit();
                    } else {
                        $offer_image = $config2['file_name'];
                    }
                }
                $data['status'] = $this->M_admin->saveBankOffer([
                    'id' => $id,
                    'bank_name' => (string) $this->input->post('bank_name', true),
                    'offer_title' => (string) $this->input->post('offer_title', true),
                    'offer_description' =>  $this->input->post('offer_description', true),
                    'offer_image'    =>  $offer_image
                ]);
            } else {
                $data['status'] = 0;
                $data['errors'] = array(
                    'bank_name' => form_error('bank_name'),
                    'offer_title' => form_error('offer_title'),
                    'offer_description' => form_error('offer_description'),
                );
                echo json_encode($data);
                exit();
            }

            echo json_encode($data);
        }
    }

    public function deleteBankOffer()
    {
        if ( $this->input->is_ajax_request() ) {
            $id = (int) $this->input->post('id', true);
            echo $this->M_admin->deleteBankOffer($id);
        }
    }

    /**
     * Projects
     */
    public function projectList()
    {
        $project_list = $this->M_admin->admin_list_projects();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/project_list", compact('project_list'));
        $this->load->view("admin/footer");
    }

    public function projectDetails()
    {
        $project_id = (int) $this->input->post('id', true);
        if ( $project_id > 0 ) {
            $data['record'] = $this->M_admin->get_project_details($project_id);
            $data['approved_archtect'] = $this->M_admin->approved_architect($project_id);

            if (!empty($data['approved_archtect'])) {
                $request_id = $data['approved_archtect'][0]['request_id'];

                $this->load->model('Architect_model');
                $data['boq_files'] = $this->M_admin->listBoqFiles($request_id);

                $data['boq_doc_files'] = $this->M_admin->listBoqDocFiles($request_id);


                $data['design_files'] = $this->M_admin->list_Design_files($request_id);

                $data['design_doc_files'] = $this->M_admin->listdesignDocFiles($request_id);

                $data['tender_details'] = $this->M_admin->tender_details($request_id);

                $data['tender_list'] = $this->M_admin->tender_list($request_id);

                $tender_id = $this->M_admin->get_tender_id($request_id);

                if ( !empty($tender_id) ) {
                    $data['woned'] = $this->M_admin->won_bid($tender_id);
                }
            }

            $this->load->view('admin/project_details_modal', $data);
        }
    }

    public function approveProject()
    {
        $project_id = (int) $this->input->post('id', true);
        $status     = (int) $this->input->post('status', true);

        echo $result = $this->M_admin->approveProject($project_id, $status);
    }

    public function deleteProject()
    {
        $project_id = (int) $this->input->post('id', true);
        if ( $project_id > 0 ) {
            echo $this->M_admin->deleteProject($project_id);
        }
    }

    public function architectProjectRequest()
    {
        $project_id = $this->input->get('project_id', true);
        $request_list = $this->M_admin->architect_requests(['project_id' => $project_id]);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/architect_project_request", compact('request_list'));
        $this->load->view("admin/footer");
    }

    public function approveProjectRequest()
    {
        $request_id = (int) $this->input->post('id', true);
        $status     = (int) $this->input->post('status', true);

        echo $result = $this->M_admin->approveProjectRequest($request_id, $status);
    }

    public function requestDetails()
    {
        $request_id = (int) $this->input->post('id', true);
        if ( $request_id > 0 ) {
            $data['record'] = $this->M_admin->getProjectRequestDetails($request_id);
            $data['design_uploads'] = $this->M_admin->getProjectRequestDesignUploads($request_id);
            $data['boq_uploads'] = $this->M_admin->getProjectRequestBOQUploads($request_id);
            $this->load->view('admin/project_request_details_modal', $data);
        }
    }

    public function deleteProjectRequest()
    {
        $request_id = (int) $this->input->post('id', true);
        if ( $request_id > 0 ) {
            echo $this->M_admin->deleteArchitectRequest([$request_id], TRUE);
        }
    }

    public function tenderList()
    {
        $request_id  = $this->input->get('request_id', true);
        $tender_list = $this->M_admin->get_tenders(compact('request_id'));
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/tender_list", compact('tender_list'));
        $this->load->view("admin/footer");
    }

    public function tenderDetails()
    {
        $tender_id = (int) $this->input->post('id', true);
        if ( $tender_id > 0 ) {
            $data = $this->M_admin->getTenderDetails($tender_id);
            $this->load->view('admin/tender_details_modal', $data);
        }
    }

    public function deleteTender()
    {
        $tender_id = (int) $this->input->post('id', true);
        if ( $tender_id > 0 ) {
            echo $this->M_admin->deleteTender([$tender_id], TRUE);
        }
    }

    public function wonBidList()
    {
        $tender_id = $this->input->get('tender_id', true);
        $bid_list = $this->M_admin->getWonBidList(['tender_id' => $tender_id]);
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/won_bid_list", compact('bid_list'));
        $this->load->view("admin/footer");
    }

    public function wonBidDetails()
    {
        $bidding_id = (int) $this->input->post('id', true);
        if ( $bidding_id > 0 ) {
            $data = $this->M_admin->getWonBidDetails($bidding_id);
            $this->load->view('admin/won_bid_details_modal', $data);
        }
    }
    ##collection section
    public function collectionList()
    {
        $data["collection_list"] = $this->M_admin->getCollectionList();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/collection_list", $data);
        $this->load->view("admin/footer");
    }

    public function addEditCollection()
    {
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_collection");
        $this->load->view("admin/footer");
    }

    public function saveCollection()
    {

        $data = array();

        if ($_FILES["txtFile"]["name"] != "") {
            $digits = 6;
            $randomNo = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txtFile"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path'] = $this->config->item('upload_path') . 'collections/';
            $config2['allowed_types'] = 'gif|jpg|png|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('txtFile')) {
                //die("file upload failed");
                $data['status'] = 3;
                $data['errors'] = array(
                    'txtFile' => strip_tags($this->upload->display_errors()),
                );
                echo json_encode($data);
                exit();
            } else {
                $inputArray['collection_logo'] = $config2['file_name'];
            }
        }

        $this->form_validation->set_rules('txtEnglish', 'Collection Name English', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('txtArabic', 'Collection Name Arabic', 'trim|required|max_length[100]');
        if (empty($_FILES['txtFile']['name'])) {
            $this->form_validation->set_rules('txtFile', 'Image', 'required');
        }

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txtEnglish' => form_error('txtEnglish'),
                'txtArabic' => form_error('txtArabic'),
                'txtFile' => form_error('txtFile'),
            );
            echo json_encode($data);
            exit();
        }

        $inputArray['collection_name'] = ucfirst($_POST['txtEnglish']);
        $inputArray['collection_language_code'] = 1;
        $inputArray['collection_status'] = $_POST['txtStatus'];
        $inputArray['collection_created_date'] = gmdate("Y-m-d H:i:s");
        $inputArray['logo_alt_text'] = $_POST['alt_text'];

        $inputArray2 = $inputArray;
        $inputArray2['collection_name'] = ($_POST['txtArabic'] != "" ? $_POST['txtArabic'] : ucfirst($_POST['txtEnglish']));
        $inputArray2['collection_language_code'] = 2;

        if (isset($_POST['id']) && $_POST['id'] > 0) {
            $inputArray['collection_id'] = $_POST['id'];
            $inputArray2['collection_id'] = $_POST['id'];
            unset($inputArray['collection_created_date']);
            unset($inputArray2['collection_created_date']);
        }

        $inputArray = $this->security->xss_clean($inputArray);
        $inputArray2 = $this->security->xss_clean($inputArray2);

        $result = $this->M_admin->saveMasterTable($inputArray, $inputArray2, 'collection_id', 'collection_language_code', 'collection');

        $data['status'] = $result;
        echo json_encode($data);
    }

    public function deleteCollection()
    {
        $id = $_POST['id'];

        echo $this->M_admin->deleteCollection($id);
    }
    
    public function orderAccept()
    {
        // $this->validateLogin();

        $status = "0";
        $message = "";

        $history_id = $this->input->post('oid', true);
        $vendor     = $this->input->post('vendor',true);
        
        if (! empty($history_id) ) {
            $order = $this->V_product->getVendorOrderById($history_id, $vendor);
            if ( $order ) {
                if ( $order->deliver_status == ORDER_STATUS_PENDING ) {
                    $is_done = $this->M_vendor->acceptVendorOrder($vendor, $history_id, $order->order_block_id);
                    if ( $is_done ) {
                        $status = '1';
                        $message = 'Order has been accepted.';

                        $this->send_notification_user($order, ORDER_STATUS_ACCEPTED,$vendor);

                    } else {
                        $status = '0';
                        $message = 'Unable to accept the order. Please try again.';
                    }
                } else {
                    $status = '0';
                    if ( $order->deliver_status == ORDER_STATUS_ACCEPTED ) {
                        $message = 'Order is already accepted.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_READY ) {
                        $message = 'Order is already ready to deliver.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_DISPATCHED ) {
                        $message = 'Order is already dispatched.';
                    } else if ( $order->deliver_status == ORDER_STATUS_DELIVERED ) {
                        $message = 'Order is already delivered.';
                    } else if ( $order->deliver_status == ORDER_STATUS_CANCEL ) {
                        $message = 'Order is already rejected.';
                    } else {
                        $message = 'Unable to process the order. Please try again.';
                    }
                }
            } else {
                $message = 'Order Not Found.';
            }
        }

        echo json_encode(array('status'=>$status,'message'=>$message));
    } 
    
    public function send_notification_user( $order, $order_status=NULL,$vendor = "" )
    {
        $msg='';
        if ( $order ) {
            $get_order_data=$this->V_product->getVendorOrderById2($order->history_id,$vendor);
            //echo "<pre>hre"; var_dump($get_order_data); echo "</pre>"; exit();
            $user = $this->M_vendor->getUserById($order->user_id);
            
            $seller_user = $this->M_vendor->getSellerByUserId($vendor);
            if ( $user && $seller_user ) {
                $this->load->library("FCM_Notification");

                $notification_id    = time();
                $ntype              = "";
                $msg_title = "";
                if ( $order_status == ORDER_STATUS_ACCEPTED ) {
                    $ntype              = "order-accepted";
                   $msg_title = $title              = "Order Accepted";
                    
                    $msg = "Hi {$user->user_first_name}, your purchase order #{$order->order_no} has been accepted by {$seller_user->store_name}.";
                    $description        = "Hi {$user->user_first_name}, your purchase order #{$order->order_no} has been accepted by {$seller_user->store_name}.";
                } elseif ( $order_status == ORDER_STATUS_CANCEL ) {
                    $ntype              = "order-cancel";
                    $msg_title =$title              = "Order Rejected";
                    $description        = "Hi {$user->user_first_name}, your purchase order #{$order->order_no} has been rejected by {$seller_user->store_name}.";
                    $msg = "Hi {$user->user_first_name}, your purchase order #{$order->order_no} has been rejected by {$seller_user->store_name}.";
                }elseif ( $order_status == ORDER_STATUS_DISPATCHED ) {
                    $msg_title =$title              = "Order Dispatched";
                    $msg = "Hi {$user->user_first_name}, your purchase order #{$order->order_no} has been dispatched by {$seller_user->store_name}.";
                }elseif ( $order_status == ORDER_STATUS_DELIVERED ) {
                    $msg_title =$title              = "Order Delivered";
                    $msg = "Hi {$user->user_first_name}, your purchase order #{$order->order_no} has been delivered by {$seller_user->store_name}.";
                }elseif ( $order_status == ORDER_STATUS_READY ) {
                    $msg_title =$title              = "Order Ready to Ship";
                    $msg = "Hi {$user->user_first_name}, your purchase order #{$order->order_no}  has ready to ship by {$seller_user->store_name}.";
                }
                
                
                $this->load->model("website/product_model", "model_product");
                $product_data = $this->model_product->get_product($get_order_data->product_id,$order->user_id);
          //  echo "<pre>hre"; var_dump($product_data); echo "</pre>"; 
                $product_images = explode(",", $product_data->product_image); 
                $product_image  = (count($product_images) > 0) ? $product_images[0] : $product_data->product_image;


                if(file_exists("uploads/products/". $product_image) && is_file("uploads/products/". $product_image))
                    $product_image = base_url()."uploads/products/". $product_image;
                else
                    $product_image = base_url()."uploads/products/dummy.png";
                

                $email_purchased_products[] = (object) ["product_name" => $product_data->product_name, 
                                                        "product_image" => $product_image,
                                                        "cloth_type" => $product_data->p_cloth_type, 
                                                        "dress_type" => $product_data->p_dress_type,
                                                        "quantity" => $get_order_data->product_count,

                                                        "unit_price" => $get_order_data->unit_price_uc,
                                                        "unit_shipping_charge" => $get_order_data->unit_shipping_charge_uc,
                                                        "product_sub_price" =>  $get_order_data->product_sub_price_uc,
                                                        "product_total_tax" =>  $get_order_data->product_total_tax_uc,
                                                        "product_total" => $get_order_data->order_sub_total,
                                                        "signle_cash_point_value" => $this->single_point_bc_value,  
                                                        
                                                        ];
                $email_message =  $this->load->view("email_templates/order_status_change", [
                                                "product_list" => $email_purchased_products, 
                                                "order_details" => (object) $get_order_data,
                                                "message"=>$msg,
                                                "subject"=>$msg_title
                                                ], true); 
                  //echo "<pre>hre"; var_dump($email_purchased_products); echo "</pre>"; exit();
                $subject    = $msg_title;
                $to         = $user->user_email_id;

                //$to         = "rejeesh.a2solution@gmail.com";

                $this->load->library("Mail_function");
                $ret=$this->mail_function->SendEmail($email_message, $subject, $to);
                //var_dump($ret);
                //echo "<pre>hre"; var_dump($product_data); echo "</pre>"; exit();
                
                if ( empty($ntype) ) {
                    return TRUE;
                }

                if ( !empty($user->firebase_user_key) ) {
                    $notification_data["Notifications/".$user->firebase_user_key."/".$notification_id] = [
                        "title" => $title,
                        "description" => $description,
                        "notificationType" => $ntype,
                        "createdAt" => gmdate("d-m-Y H:i:s", $notification_id),
                        "orderID" => (string) $order->order_block_id,
                        "url" => "",
                        "imageURL" => "",
                        "read" => "0",
                        "seen" => "0"
                    ];

                    $fb_database = get_firebase_refrence();
                    $fb_database->getReference()->update($notification_data);

                }

                if (! empty($user->user_device_token) ) {
                    $this->fcm_notification->send_single_notification($user->user_device_token,
                        [
                            "title" => $title,
                            "body" => $description,
                            "icon"=>'myicon',
                            "sound" =>'default',
                            "click_action" => "EcomNotification"
                        ],
                        [
                            "type" => $ntype,
                            "notificationID" => $notification_id,
                            "orderID" => (string) $order->order_block_id,
                            "imageURL" => ""
                        ]
                    );
                }
                
                
            }
        }
    }
    
    public function orderReadyToDeliver()
    {
        $this->validateLogin();

        $status = "0";
        $message = "";

        $history_id = $this->input->post('oid', true);
        $vendor     = $this->input->post('vendor',true);

        if (! empty($history_id) ) {
            $order = $this->V_product->getVendorOrderById($history_id, $vendor);
            if ( $order ) {
                if ( $order->deliver_status == ORDER_STATUS_ACCEPTED ) {
                    $is_done = $this->M_vendor->setVendorOrderReadyForDelivery($vendor, $history_id,$order->order_block_id);
                    if ( $is_done ) {

                        $this->send_notification_user($order,ORDER_STATUS_READY,$vendor);

                        $status     = '1';
                        $message    = 'Your order is ready for delivery.';
                    } else {
                        $message    = 'Unable to process the order. Please try again.';
                    }
                } else {
                    if ( $order->deliver_status == ORDER_STATUS_PENDING ) {
                        $message = 'You\'ve to accept the order first.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_READY ) {
                        $message = 'Order is already ready to deliver.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_DISPATCHED ) {
                        $message = 'Order is already dispatched.';
                    } else if ( $order->deliver_status == ORDER_STATUS_DELIVERED ) {
                        $message = 'Order is already delivered.';
                    } else if ( $order->deliver_status == ORDER_STATUS_CANCEL ) {
                        $message = 'Order is already cancelled.';
                    } else {
                        $message = 'Unable to process the order. Please try again.';
                    }
                }
            } else {
                $message = 'Order Not Found.';
            }
        }

        echo json_encode(array('status'=>$status,'message'=>$message));
    }
    
    public function orderCancel()
    {
        $this->validateLogin();

        $status = "1";
        $message = "";

        $history_id = $this->input->post('oid', true);
        $vendor     = $this->input->post('vendor',true);

        if (! empty($history_id) ) {
            $order = $this->V_product->getVendorOrderById($history_id, $vendor);
            if ( $order ) {
                if ( $order->deliver_status == ORDER_STATUS_PENDING ) {
                    $is_done = $this->M_vendor->cancelVendorOrder($vendor, $history_id,$order->order_block_id);
                    if ( $is_done ) {
                        $status = '1';
                        $message = 'Order has been rejected.';

                        $this->send_notification_user($order, ORDER_STATUS_CANCEL,$vendor);

                    } else {
                        $status = '0';
                        $message = 'Unable to reject the order. Please try again.';
                    }
                } else {
                    $status = '0';
                    if ( $order->deliver_status == ORDER_STATUS_ACCEPTED ) {
                        $message = 'Order is already accepted.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_READY ) {
                        $message = 'Order is already ready to deliver.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_DISPATCHED ) {
                        $message = 'Order is already dispatched.';
                    } else if ( $order->deliver_status == ORDER_STATUS_DELIVERED ) {
                        $message = 'Order is already delivered.';
                    } else if ( $order->deliver_status == ORDER_STATUS_CANCEL ) {
                        $message = 'Order is already rejected.';
                    } else {
                        $message = 'Unable to cancel the order. Please try again.';
                    }
                }
            } else {
                $message = 'Order Not Found.';
            }
        }

        echo json_encode(array('status'=>$status,'message'=>$message));
    }
    
    public function orderStartJourney()
    {
        $this->validateLogin();

        $status = "0";
        $message = "";

        $history_id = $this->input->post('oid', true);
        $vendor     = $this->input->post('vendor',true);

        if (! empty($history_id) ) {
            $order = $this->V_product->getVendorOrderById($history_id, $vendor);
            if ( $order ) {
                if ( $order->deliver_status == ORDER_STATUS_READY ) {
                    $is_done = $this->M_vendor->setVendorOrderStartJourney($vendor, $history_id,$order->order_block_id);
                    if ( $is_done ) {

                        $this->send_notification_user($order,ORDER_STATUS_DISPATCHED,$vendor);

                        $status     = '1';
                        $message    = 'Order is picked up for delivery.';
                    } else {
                        $message    = 'Unable to process the order. Please try again.';
                    }
                } else {                    
                    if ( $order->deliver_status == ORDER_STATUS_PENDING ) {
                        $message = 'Order is not accepted yet.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_ACCEPTED ) {
                        $message = 'Order is not ready for delivery.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_DISPATCHED ) {
                        $message = 'Order is already picked up for delivery.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_DELIVERED ) {
                        $message = 'Order is already delivered.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_CANCEL ) {
                        $message = 'Order is already cancelled.';
                    } else {
                        $message = 'Unable to process the order. Please try again.';
                    }
                }
            } else {
                $message = 'Order Not Found.';
            }
        }

        echo json_encode(array('status'=>$status,'message'=>$message));
    }
    
    public function orderDeliver()
    {
        $this->validateLogin();

        $status = "0";
        $message = "";

        $history_id = $this->input->post('oid', true);
        $vendor     = $this->input->post('vendor',true);

        if (! empty($history_id) ) {
            $order = $this->V_product->getVendorOrderById($history_id, $vendor);
            if ( $order ) {
                if ( $order->deliver_status == ORDER_STATUS_DISPATCHED ) {
                    $is_done = $this->M_vendor->setVendorOrderDelivered($vendor, $history_id,$order->order_block_id);
                    if ( $is_done ) {

                       $this->send_notification_user($order,ORDER_STATUS_DELIVERED,$vendor); 

                        $status     = '1';
                        $message    = 'You\'ve delivered the order.';
                    } else {
                        $message    = 'Unable to deliver the order. Please try again.';
                    }
                } else {                    
                    if ( $order->deliver_status == ORDER_STATUS_PENDING ) {
                        $message = 'Order is not accepted yet.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_ACCEPTED ) {
                        $message = 'Order is not ready for delivery.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_READY ) {
                        $message = 'Order is not picked up for delivery.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_DELIVERED ) {
                        $message = 'Order is already delivered.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_CANCEL ) {
                        $message = 'Order is already cancelled.';
                    } else {
                        $message = 'Unable to process the order. Please try again.';
                    }
                }
            } else {
                $message = 'Order Not Found.';
            }
        }

        echo json_encode(array('status'=>$status,'message'=>$message));
    }

    public function topSellingProducts()
    {
        $data = array();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/top_selling_product_report", $data);
        $this->load->view("admin/footer");
    }

    public function getTopSellingProducts()
    {
        require_once APPPATH.'third_party/ozdemir-datatable/vendor/autoload.php';
        $datatable = new Datatables(new CodeigniterAdapter);
        $search_condition       = "";

        $search_from_date       = $this->input->post("f_from_date", true);
        $search_to_date         = $this->input->post("f_to_date", true);
        
        if(strlen($search_from_date) > 5 && strlen($search_to_date) > 5 )
        {
            $search_condition .=" and pod.order_placed_date::date >= '". date("Y-m-d", strtotime($search_from_date)) ."' and  pod.order_placed_date::date <= '". date("Y-m-d", strtotime($search_to_date)) ."'";
        }

        $this->M_product->get_top_selling_products($datatable, $search_condition);

        $this->output->set_output( $datatable->generate() ); 
    }

    public function outOfStock()
    {
        $data = array();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/out_of_stock_report", $data);
        $this->load->view("admin/footer");
    }

    public function getOutOfStockProducts()
    {
        require_once APPPATH.'third_party/ozdemir-datatable/vendor/autoload.php';
        $datatable = new Datatables(new CodeigniterAdapter);
        $search_condition       = "";

        $search_from_date       = $this->input->post("f_from_date", true);
        $search_to_date         = $this->input->post("f_to_date", true);
        
        if(strlen($search_from_date) > 5 && strlen($search_to_date) > 5 )
        {
            $search_condition .=" and p.product_created_date::date >= '". date("Y-m-d", strtotime($search_from_date)) ."' and  p.product_created_date::date <= '". date("Y-m-d", strtotime($search_to_date)) ."'";
        }

        $this->M_product->getOutOfStockProducts($datatable, $search_condition);

        $datatable->edit("product_created_date", function ($data) {
            return date("d, F Y",  strtotime($data['product_created_date']));
        });

        $datatable->edit("image", function ($data) {
            $imageNameArray = explode(",",$data['image']);
            $image_name     = $imageNameArray[0];
            if(!file_exists('uploads/products/'.$image_name))
            {
                $image_name = 'dummy.png';
            }

            return  '<img width="40px" height="40px" src="'.base_url(). 'uploads/products/'.$image_name.'">';
        });

        $this->output->set_output( $datatable->generate() ); 
    }

    public function customerReport()
    {
        $data=[];
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/customer_report", $data);
        $this->load->view("admin/footer");
    }

    public function getCustomerReport()
    {
        require_once APPPATH.'third_party/ozdemir-datatable/vendor/autoload.php';
        $datatable = new Datatables(new CodeigniterAdapter);
        $search_condition       = "";

        $search_from_date       = $this->input->post("f_from_date", true);
        $search_to_date         = $this->input->post("f_to_date", true);
        
        if(strlen($search_from_date) > 5 && strlen($search_to_date) > 5 )
        {
            $search_condition .=" and ut.user_created_date::date >= '". date("Y-m-d", strtotime($search_from_date)) ."' and  ut.user_created_date::date <= '". date("Y-m-d", strtotime($search_to_date)) ."'";
        }

        $this->M_admin->getCustomerReport($datatable, $search_condition);

        $datatable->edit("user_status", function ($data) {
            return ($data['user_status'] == 1 ? 'Active' : 'Inactive');
             
        });

        $datatable->edit("user_created_date", function ($data) {
            return date("d, F Y",  strtotime($data['user_created_date']));
        });

        $datatable->edit("order_count", function ($data) {
            return '<a class="label label-warning" href="'.base_url('order_status?user_id='.$data['user_id']).'"><i class="fa fa-eye"></i> '.$data['order_count'].'</a>';
        });


        $this->output->set_output( $datatable->generate() ); 
    }

    public function storeReport()
    {
        $data = array();

        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/store_report", $data);
        $this->load->view("admin/footer");
    }

    public function driverReport()
    {
        //$condition = array("user_type" => "D");
        $data["vendor_list"] = $this->M_admin->getVenderCondition();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/driver_report", $data);
        $this->load->view("admin/footer");
    }

    public function getDriverReport()
    {
        require_once APPPATH.'third_party/ozdemir-datatable/vendor/autoload.php';
        $datatable = new Datatables(new CodeigniterAdapter);
        $search_condition       = "";

        $search_from_date       = $this->input->post("f_from_date", true);
        $search_to_date         = $this->input->post("f_to_date", true);
        $vendor_id         = $this->input->post("vendor_id", true);

        if($vendor_id)
        {
            $search_condition .=" and dd.vendor_id=".$vendor_id;
        }
        
        if(strlen($search_from_date) > 5 && strlen($search_to_date) > 5 )
        {
            $search_condition .=" and ut.user_created_date::date >= '". date("Y-m-d", strtotime($search_from_date)) ."' and  ut.user_created_date::date <= '". date("Y-m-d", strtotime($search_to_date)) ."'";
        }

        $this->M_admin->getDriversList($datatable, $search_condition);

        $datatable->edit("user_status", function ($data) {
            return ($data['user_status'] == 1 ? 'Active' : 'Inactive');
        });

        $datatable->edit("orders_assigned", function ($data) {
            if($data['orders_assigned']){
                return  '<a class="btn btn-primary btn-sm" style="padding:10px;width:40px;" href="'.base_url(). 'order_status/0/'.$data['driver_id'].'">'.$data['orders_assigned'].'</a>';
            }
            else
            {
                return  '<a class="btn btn-primary btn-sm" style="padding:10px;width:40px;" href="javascript:;">0</a>';
            }
        });

        $datatable->edit("user_created_date", function ($data) {
            return date("d, F Y",  strtotime($data['user_created_date']));
        });

        $this->output->set_output( $datatable->generate() ); 
    }

    public function excelDriverReport($vendor_id="",$from_date="",$to_date="")
    {
        $search_condition = "";

        if($vendor_id)
        {
            $search_condition .=" and dd.vendor_id=".$vendor_id;
        }

        if($from_date!="" && $to_date !="")
        {
            $search_condition .=" and ut.user_created_date::date >= '". date("Y-m-d", strtotime($from_date)) ."' and  ut.user_created_date::date <= '". date("Y-m-d", strtotime($to_date)) ."'";
        }
        $data["driver_list"] = $this->M_admin->getDriversExcelList($search_condition);

        $fileName = 'driver_report_on' . date('Y_m_d') . '.xls';

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        function filterData(&$str)
        {
            $str = preg_replace("/\t/", "\\t", $str);
            $str = preg_replace("/\r?\n/", "\\n", $str);
            if (strstr($str, '"')) {
                $str = '"' . str_replace('"', '""', $str) . '"';
            }
        }

        // file name for download
        // $fileName = "vendor_payment_report_on" . date('Ymd') . ".xls";

        // headers for download
        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        $flag = false;
        $i = 1;
        foreach ($data["driver_list"] as $row)
        {
            $postedDate = date("d-m-Y H:i",strtotime($row->user_created_date));

            if (!$flag) {
                // display column names as first row
                echo implode("\t", array('Sl no', 'Driver Name', 'Email id', 'Mobile Number','Store', 'Vehicle Number', 'City','Country','Bank Name','Account Number','IFSC Code','Swift Code','Status', 'Created at')) . "\n";
                $flag = true;
            }
            // filter data
            array_walk($row, 'filterData');

            $store_name = $row->store_name=="" ? '': $row->store_name;
            echo implode("\t", array($i, $row->user_name ,$row->user_email_id,$row->mobile_no,$row->store_name,$row->vehicle_no, $row->city_name, $row->country_name, $row->bank_name, $row->bank_account_number, $row->bank_ifsc_code, $row->bank_swift_code, $row->user_status==1 ? 'Active' : 'Inactive',$postedDate)) . "\n";
            $i++;
        }
    }

    public function getStoreReport()
    {
        require_once APPPATH.'third_party/ozdemir-datatable/vendor/autoload.php';
        $datatable = new Datatables(new CodeigniterAdapter);
        $search_condition       = "";

        $search_from_date       = $this->input->post("f_from_date", true);
        $search_to_date         = $this->input->post("f_to_date", true);
        
        if(strlen($search_from_date) > 5 && strlen($search_to_date) > 5 )
        {
            $search_condition .=" and ut.user_created_date::date >= '". date("Y-m-d", strtotime($search_from_date)) ."' and  ut.user_created_date::date <= '". date("Y-m-d", strtotime($search_to_date)) ."'";
        }

        $this->M_admin->getStoreReport($datatable, $search_condition);

        $datatable->edit("user_status", function ($data) {
            return ($data['user_status'] == 1 ? 'Active' : 'Inactive');
             
        });

        $datatable->edit("user_created_date", function ($data) {
            return date("d, F Y",  strtotime($data['user_created_date']));
        });
        $datatable->edit("order_count", function ($data) {
            return '<a class="label label-warning" href="'.base_url('order_status?vendor_id='.$data['user_id']).'"><i class="fa fa-eye"></i> '.$data['order_count'].'</a>';
        });
        $this->output->set_output( $datatable->generate() ); 
    }

    public function excelStoreReport($from_date="",$to_date="")
    {
        $search_condition = "";
        if($from_date!="" && $to_date !="")
        {
            $search_condition .=" and ut.user_created_date::date >= '". date("Y-m-d", strtotime($from_date)) ."' and  ut.user_created_date::date <= '". date("Y-m-d", strtotime($to_date)) ."'";
        }
        $data["store_list"] = $this->M_admin->getStoreExcelReport($search_condition);

        $fileName = 'store_report_on' . date('Y_m_d') . '.xls';

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        function filterData(&$str)
        {
            $str = preg_replace("/\t/", "\\t", $str);
            $str = preg_replace("/\r?\n/", "\\n", $str);
            if (strstr($str, '"')) {
                $str = '"' . str_replace('"', '""', $str) . '"';
            }
        }

        // file name for download
        // $fileName = "vendor_payment_report_on" . date('Ymd') . ".xls";

        // headers for download
        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        $flag = false;
        $i = 1;
        foreach ($data["store_list"] as $row)
        {
            $postedDate = date("d-m-Y H:i",strtotime($row->user_created_date));

            if (!$flag) {
                // display column names as first row
                echo implode("\t", array('Sl no', 'First Name', 'Last Name', 'Store Name','Email id', 'Phone Number','City', 'Country','Status','Created at')) . "\n";
                $flag = true;
            }
            // filter data
            array_walk($row, 'filterData');

            $store_name = $row->store_name=="" ? 'NA': $row->store_name;
            echo implode("\t", array($i, $row->user_first_name ,$row->user_last_name,$row->store_name,$row->user_email_id,$row->mobile_no, $row->city_name, $row->country_name, $row->user_status==1 ? 'Active' : 'Inactive',$postedDate)) . "\n";
            $i++;
        }
    }

    public function excelTopSellingProducts($from_date="",$to_date="")
    {
        $search_condition = "";
        if($from_date!="" && $to_date !="")
        {
            $search_condition .=" and pod.order_placed_date::date >= '". date("Y-m-d", strtotime($from_date)) ."' and  pod.order_placed_date::date <= '". date("Y-m-d", strtotime($to_date)) ."'";
        }
        $data["product_list"] = $this->M_product->get_top_selling_products_report($search_condition);

        $fileName = 'top_selling_report_on' . date('Y_m_d') . '.xls';
        

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        function filterData(&$str)
        {
            $str = preg_replace("/\t/", "\\t", $str);
            $str = preg_replace("/\r?\n/", "\\n", $str);
            if (strstr($str, '"')) {
                $str = '"' . str_replace('"', '""', $str) . '"';
            }
        }

        // file name for download
        // $fileName = "vendor_payment_report_on" . date('Ymd') . ".xls";

        // headers for download
        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        $flag = false;
        $i = 1;
        foreach ($data["product_list"] as $row)
        {
            if (!$flag) {
                // display column names as first row
                echo implode("\t", array('Sl no', 'Product Name', 'Category Name', 'Store Name', 'Product Sold')) . "\n";
                $flag = true;
            }
            // filter data
            array_walk($row, 'filterData');

            echo implode("\t", array($i, $row->product_name, $row->category_name ,$row->store_name,$row->sold)) . "\n";
            $i++;
        }
    }

    public function excelOutOfStockProducts($from_date="",$to_date="")
    {
        $fileName = 'out_of_stock_report_on' . date('Y_m_d') . '.xls';

        if($from_date!="" && $to_date !="")
        {
            $search_condition .=" and p.product_created_date::date >= '". date("Y-m-d", strtotime($from_date)) ."' and  p.product_created_date::date <= '". date("Y-m-d", strtotime($to_date)) ."'";
        }
        $data["out_of_stocks"] = $this->M_product->getOutOfStockProductsReport($search_condition);

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        function filterData(&$str)
        {
            $str = preg_replace("/\t/", "\\t", $str);
            $str = preg_replace("/\r?\n/", "\\n", $str);
            if (strstr($str, '"')) {
                $str = '"' . str_replace('"', '""', $str) . '"';
            }
        }

        $product_type = [0=>'',1=>'Simple',2=>'Variable'];
        $flag = false;
        $i = 1;
        foreach ($data["out_of_stocks"] as $row)
        {
            $postedDate = date("d-m-Y H:i",strtotime($row->product_created_date));

            if (!$flag) {
                // display column names as first row
                echo implode("\t", array('Sl no', 'Product Name', 'Vendor Name', 'Created Date', 'Stock Quantity')) . "\n";
                $flag = true;
            }
            // filter data
            array_walk($row, 'filterData');

            echo implode("\t", array($i, $row->product_name ,$row->store_name, $postedDate, $row->stock_quantity)) . "\n";
            $i++;
        }
    }

    public function excelCustomerReport($from_date="",$to_date="")
    {
        $fileName = 'customer_report_on' . date('Y_m_d') . '.xls';

        if($from_date!="" && $to_date !="")
        {
            $search_condition .=" and ut.user_created_date::date >= '". date("Y-m-d", strtotime($from_date)) ."' and  ut.user_created_date::date <= '". date("Y-m-d", strtotime($to_date)) ."'";
        }
        $data["customer_report"] = $this->M_admin->getCustomerExcelReport($search_condition);

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        function filterData(&$str)
        {
            $str = preg_replace("/\t/", "\\t", $str);
            $str = preg_replace("/\r?\n/", "\\n", $str);
            if (strstr($str, '"')) {
                $str = '"' . str_replace('"', '""', $str) . '"';
            }
        }

        $flag = false;
        $i = 1;

        foreach ($data["customer_report"] as $row)
        {
            $postedDate = date("d-m-Y H:i",strtotime($row->user_created_date));

            if (!$flag) {
                // display column names as first row
                echo implode("\t", array('Sl no', 'First Name', 'Last Name', 'Email id', 'Mobile No', 'City', 'Country', 'Status', 'Created Date')) . "\n";
                $flag = true;
            }
            // filter data
            array_walk($row, 'filterData');
            $status = ($row->user_status == 1 ? 'Active' : 'Inactive');
            echo implode("\t", array($i, $row->user_first_name ,$row->user_last_name,$row->user_email_id,$row->mobile_no,$row->city_name,$row->country_name,$status,$postedDate)) . "\n";
            $i++;
        }
    }

    public function excelSalesReport($status=0,$from_date="",$to_date="")
    {
        $search_params =[];
        $search_params['vendor_id'] =$this->input->get("vendor_id");
        $search_params['user_id'] =$this->input->get("user_id");
        $search_params['order_type'] =$this->input->get("order_type");
        $search_params['status'] =$status;
        $search_params['txt_sale_datefrom'] =$from_date;
        $search_params['txt_sale_dateto'] =$to_date;
//printr($search_params);
        $data['order_list'] = $this->M_product->getSalesHistory($search_params, 0, 0);

        //echo '<pre>'; print_r($data['order_list']);die;

        $fileName = 'sales_report_on' . date('Y_m_d') . '.xls';

        
        $data["customer_report"] = $this->M_admin->getCustomerExcelReport($search_condition);

        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        function filterData(&$str)
        {
            $str = preg_replace("/\t/", "\\t", $str);
            $str = preg_replace("/\r?\n/", "\\n", $str);
            if (strstr($str, '"')) {
                $str = '"' . str_replace('"', '""', $str) . '"';
            }
        }

        $flag = false;
        $i = 1;

        foreach ($data["order_list"] as $row)
        {
            $postedDate = date("d-m-Y H:i",strtotime($row->order_placed_date));
            $product_nameArr = '';
            $TotalAmt = 0;
            if(count($row->r_products) > 0)
            {
                $product_nameArr = implode(',', array_column($row->r_products, 'product_name'));
                $TotalAmt+= array_sum(array_column($row->r_products, 'unit_price'));
            }
            $service_nameArr= '';
            if(count($row->r_services) > 0)
            {
                $service_nameArr = implode(',', array_column($row->r_services, 'product_name'));
                $TotalAmt+= array_sum(array_column($row->r_services, 'unit_price'));
            }


            

            if (!$flag) {
                // display column names as first row
                echo implode("\t", array('Sl no', 'Order No', 'Customer Name','Email','Phone number', 'Product','Services',' Order Amount' ,'Order Placed on')) . "\n";
                $flag = true;
            }
            // filter data
            array_walk($row, 'filterData');
            echo implode("\t", array($i, '#'.$row->order_no ,$row->customer_name,$row->user_email_id,$row->dial_code.$row->phone_number,$product_nameArr,$service_nameArr,$TotalAmt,$postedDate)) . "\n";
            $i++;
        }
 
    }

    public function manageTimeSlot()
    {
        $data = [];
        $data["storeTimeSlots"] = $this->M_admin->getStoreTimeSlots()->result();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/manage_time_slot", $data);
        $this->load->view("admin/footer");
    }


    public function addEditTimeslot()
    {
        $data = [];
        $data["store_list"] = $this->M_admin->getStoreExcelReport();
        $this->load->view("admin/header");
        $this->load->view("admin/sidebar");
        $this->load->view("admin/add_edit_timeslot", $data);
        $this->load->view("admin/footer");
    }

    public function saveTimeslot()
    {
        $status = 0;
        $this->form_validation->set_rules('store_id', 'Store', 'trim|required|callback_is_unique_time_slot');
        $this->form_validation->set_rules('day_id', 'Day Name', 'trim|required');
        $this->form_validation->set_rules('time_slot', 'Time Slot', 'trim|required');
        
        if ($this->form_validation->run() == false)
        {
            $data['status'] = 0;
            $data['errors'] = array(
                'store_id' => form_error('store_id'),
                'day_id' => form_error('day_id'),
                'time_slot' => form_error('time_slot')
            );
            echo json_encode($data);
            exit();
        }
        else
        {
            $result = $this->M_admin->saveTimeslot($_POST);

            if($result)
                $status = 1;
        }

        echo json_encode(['status'=>$status]);
    }

    public function is_unique_time_slot( $store_id )
    {
        if (! empty($store_id) ) {
            $id = (int)$this->input->post('id', true);
            
            $condition = [
                'store_id'=>(int)$this->input->post('store_id', true),
                'day_id'=>(int)$this->input->post('day_id', true),
                'time_slot'=>(string)$this->input->post('time_slot', true)
            ];
            
            if(!empty($id))
            {
                $condition['slot_id !='] = $id;
            }

            $isExists = $this->M_admin->getStoreTimeSlots($condition)->row();
            if ( $isExists ) {
                $this->form_validation->set_message('is_unique_time_slot', 'This time slot already added for the this store.');
                return FALSE;
            }
        }
        return TRUE;
    }

    public function deleteTimeSlot()
    {
        $id = $_POST['id'];
        echo $this->M_admin->deleteTimeSlot($id);
    }
}