<?php

class M_vendor extends CI_Model
{

    public function insertShipping($data)
    {
        $vendorid  = $this->session->userdata("user_id");

        //delete all previous shipping
        $this->db->where('vendor_id', $vendorid);
        $this->db->delete('shipping_charge');
        //  print_r($data);
        foreach ($data['ship_method_name'] as $key => $kk) {
            $dataToSave[] = array(
                'ship_charge_id' => '10',
                'vendor_id' => $vendorid,
                'ship_method_name' => $data['ship_method_name'][$key],
                'min_weight' => $data['min_weight'][$key],
                'max_weight' => $data['max_weight'][$key],
                'ship_cost' => $data['ship_cost'][$key],
                'ship_created_date' => gmdate('Y-m-d H:i:s'),
                'ship_updated_date' => gmdate('Y-m-d H:i:s'),
            );
        }
        $this->db->insert_batch('shipping_charge', $dataToSave);
        return 1;
    }

    public function login($data)
    {
        // $query = $this->db->get_where('user_table',$data );
        // echo $this->db->last_query();
        $query =  $this->db->select('u.*,sd.seller_details_id,sd.verified_status')
            ->from('user_table u')->join('seller_details sd', 'sd.user_id = u.user_id', 'left')
            ->where($data)->get();
        return $query->row();
    }


    //update shipping class
    public function updateShippingMethod($vid, $data)
    {
        $this->db->where('user_id', $vid);
        $this->db->update('seller_details', $data);
        return 1;
    }


    //get Shipping Details
    public function getSellerShippingWeight($vid)
    {
        $this->db->select('*');
        $this->db->from('shipping_charge');
        // $this->db->where('dsi_language_code',$language);
        $this->db->where('vendor_id', $vid);

        $query = $this->db->get();
        // echo $this->db->last_query();
        return $query->result();
    }

    public function saveChangePassword($data)
    {
        $sql = "select  count(user_password) as count from user_table where user_password= '" . MD5($data["txt_old_password"]) . "' ";
        $rs = $this->db->query($sql);
        $count = $result = $rs->row()->count;
        if ($count <= 0) {
            return -1;
        } else {
            $user_id  = $this->session->userdata("user_id");

            $this->db->trans_start();

            $input['user_password']  =  MD5($data["txt_new_password"]);

            $this->db->where('user_id', $user_id);
            $this->db->update('user_table', $input);

            $this->db->trans_complete();


            if ($this->db->trans_status() === FALSE) {

                return 0;
            } else {
                return 1;
            }
        }
    }

    public function forgotPassword($data)
    {

        $query = $this->db->get_where('user_table', $data);
        // echo $this->db->last_query();
        // exit;

        $result =  $query->row();
        if ($result != "") {
            if ($result->user_id > 0) {

                $six_digit_random_number                          =   mt_rand(100000, 999999);
                $inputUserBasic['user_password']                  =   md5($six_digit_random_number);
                $userId                                           =   $result->user_id;
                /* $this->db->where('user_id', $userId);
                                    $this->db->update('user_table',$inputUserBasic);*/

                $input['user_id']                         =      $userId;
                $input['session_start_time']              =      gmdate("Y-m-d H:i:s");
                $currentDate = strtotime($input['session_start_time']);
                $futureDate = $currentDate + (60 * 5);
                $formatDate = date("Y-m-d H:i:s", $futureDate);
                $input['session_end_time']                =      $formatDate;
                $this->db->where('user_id', $userId);
                $this->db->delete('password_reset');
                $this->db->insert('password_reset', $input);

                $subject  =  "Account Password reset ! ";
                $to       =   $result->user_email_id;

                //   $to      =  "ajithkumar.a2solution@gmail.com";

                $from    =  "info@fassl.com";

                $encryptedUserId = $this->M_product->encryptId($userId);

                $link = base_url() . "vendor/reset_password/" . $encryptedUserId;
                // http://a2itproducts.com/fassl/images/admin_inner_logo.png
                $message = '<div style="background: #373242;max-width: 663px;
    margin: 0 auto;"> 
    <div style="background:url(' . base_url() . '/images/admin_inner_logo.png);background-size:cover;text-align:center;width:57%;height:147px;">
		
	</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 ' . $result->user_first_name . ',</p>
			<p>Please click <a href=' . $link . '> here </a>to reset your password ,the link will expire after 5 minuts .</p>
			
			<p style="margin-bottom:5px">Simply Sell and Buy!</p>
			<p style="margin:0">fassl.com</p>
			<span style="display: block;
    text-align: center;
    color: #000000a6;
    padding: 14px 0;
    font-size: 11px;">&copy 2018 fassl All rights reserved.</span>
		</div>
	</div>
</div>';


                //$this->send($subject,$message,$to,$from) ;

                $this->load->library("Email_teyaar");
                $this->email_teyaar->SendEmail($message, $subject, $to);

                echo 1;
            } else {
                return 0;
            }
        } else {
            return 3;
        }
    }

    public function checkLinkExpired($userId)
    {
        $now = gmdate("Y-m-d H:i:s");
        // $now= '2018-12-07 08:38:31';
        $sql = " select * from password_reset where user_id=" . $userId . " and session_end_time>='" . $now . "' ";

        $rs = $this->db->query($sql);
        return $row = $rs->result();
    }

    public function resetPassword($data)
    {

        $userId  = $data['user_id'];

        $sql = " select  * from user_table   where user_id=" . $userId . "  ";


        $rs = $this->db->query($sql);

        $result = $row = $rs->row();


        // $digits    =  6;
        //$randomNo  = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

        $inputUserBasic['user_password']  = MD5($data['new_password']);
        $this->db->where('user_id', $userId);
        $this->db->update('user_table', $inputUserBasic);

        $subject =  "Account Password reset ! ";
        $to      =   $result->user_email_id;
        //  $to      =  "ajithkumar.a2solution@gmail.com";
        $from    =  "info@fassl.com";

        $message = '<div style="background: #373242;max-width: 663px;
    margin: 0 auto;">
    <div style="background:url(' . base_url() . '/images/admin_inner_logo.png);background-size:cover;text-align:center;width:57%;height:147px;">
		
	</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 ' . $result->user_first_name . ',</p>
			<p>You have successfully changed your Password ,Your new Paasword is ' . $data['new_password'] . '.</p>
			
			<p style="margin-bottom:5px">Simply Sell and Buy!</p>
			<p style="margin:0">fassl.com</p>
			<span style="display: block;
    text-align: center;
    color: #000000a6;
    padding: 14px 0;
    font-size: 11px;">&copy 2018 fassl All rights reserved.</span>
		</div>
	</div>
</div>';


        // $this->send($subject,$message,$to,$from) ;
        $this->load->library("Email_teyaar");
        $this->email_teyaar->SendEmail($message, $subject, $to);

        return 1;
    }

    private function _getVendorQuery($condition, $order_by=null, $limit=null)
    {
        if ( $order_by ) {
            $this->db->order_by($order_by);
        }
        if ( $limit ) {
            $this->db->limit($limit);
        }
        $query =  $this->db->select('u.*,sd.*')
                            ->from('user_table u')
                            ->join('seller_details sd', 'u.user_id = sd.user_id', 'left')
                            ->where($condition)
                            ->get();
        return $query;
    }

    public function getVendors($condition)
    {
        return $this->_getVendorQuery($condition)->result();
    }

    public function getVendorById($id)
    {
        return $this->_getVendorQuery(['u.user_id' => $id], null, 1)->row();
    }

    public function updateKandoraProfile( $userId, array $data=[] )
    {
        $seller_data['is_kandora_seller'] = $data['is_kandora_seller'] ?? 0;

        if ( $seller_data['is_kandora_seller'] ) {
            $this->generateKandoraProducts($userId);
        } else {
            $this->disableKandoraProducts($userId);
        }

        $this->db->trans_start();

        $this->db->where('user_id', $userId);
        $this->db->update('seller_details', $seller_data);

        $this->db->trans_complete();

        if ( $this->db->trans_status() === FALSE ) {
            return 0;
        } else {
            return 1;
        }
    }

    public function updateVendorProfile( $userId, array $data=[] )
    {
        if (! empty($data) ) {
            $time_now = gmdate("Y-m-d H:i:s");

            $user_data['user_first_name']   = $data['first_name'] ?? '';
            $user_data['user_last_name']    = $data['last_name'] ?? '';
            $user_data['user_country_id']   = $data['country_id'] ?? '';

            $user_data['facebook_link']   = $data['facebook_link'] ?? '';
            $user_data['instagram_link']   = $data['instagram_link'] ?? '';
            $user_data['twitter_link']   = $data['twitter_link'] ?? '';


            $seller_data['store_name']          = $data['store_name'] ?? '';
            $seller_data['store_name_arabic']   = $data['store_name_arabic'] ?? '';
            $seller_data['city']                = $data['city_id'] ?? '';
            $seller_data['location']            = $data['location'] ?? '';
            $seller_data['latitude']            = $data['latitude'] ?? '';
            $seller_data['longitude']           = $data['longitude'] ?? '';
            $seller_data['street_name']         = $data['street_name'] ?? '';
            $seller_data['building_no']         = $data['building_no'] ?? '';
            $seller_data['land_phone']          = $data['land_phone'] ?? '';
            $seller_data['about_seller_desc']   = $data['about_seller_desc'] ?? '';
            $seller_data['about_seller_desc_arb'] = $data['about_seller_desc_arabic'] ?? '';
            $seller_data['delivery_time_min']   = (int)$data['delivery_time_min'] ?? 0;
            $seller_data['delivery_time_max']   = (int)$data['delivery_time_max'] ?? 0;            
            $seller_data['document_type_id']    = $data['document_type'] ?? "";
            $seller_data['document_number']     = $data['document_number'] ?? "";
            $seller_data['seller_bank_id']      = (int)$data['bank_id'] ?? "";
            $seller_data['bank_account_number'] = $data['bank_account_number'] ?? "";
            $seller_data['bank_ifsc_code']      = $data['bank_ifsc_code'] ?? "";
            $seller_data['bank_swift_code']     = $data['bank_swift_code'] ?? "";
            $seller_data['store_updated_date']  = $time_now;            

            $document_name = $data['document_name'] ?? "";
            if (! empty($document_name) ) {
                $seller_data['doument_name'] = $document_name;
            }
            
            $seller_default_image = $data['seller_default_image'] ?? "";
            if (! empty($seller_default_image) ) {
                $seller_data['seller_default_image'] = $seller_default_image;
            }

            $this->db->trans_start();
            
            $this->db->where('user_id', $userId);
            $this->db->update('user_table', $user_data);            
                        
            $this->db->where('user_id', $userId);
            $this->db->update('seller_details', $seller_data);

            $this->db->trans_complete();

            if ( $this->db->trans_status() === FALSE ) {
                return 0;
            } else {
                return 1;
            }
        }
        
        return 0;
    }

    public function generateKandoraProducts( $userId )
    {
        if (! empty($userId) ) {
            $category_uid = $this->config->item('kandora_parent_category_uid');

            $kandora_prices = $this->input->post('kandora_price');
            $kandora_cash_points = $this->input->post('kandora_cash_point');
            if ( empty($kandora_prices) ) {
                return FALSE;
            }            
            
            $sub_categories = $this->db->select('DISTINCT ON (sub_cat.category_id) sub_cat.category_id, sub_cat.category_uid, sub_cat.category_parent_id', TRUE)
                                       ->from('category sub_cat')
                                       ->join('category main_cat', 'sub_cat.category_parent_id = main_cat.category_id', 'inner')
                                       ->where('sub_cat.category_parent_id !=', 0)
                                       ->where('main_cat.category_uid', $category_uid)
                                       ->get()->result_array();
                                      
            $main_categories    = array_column($sub_categories, 'category_parent_id');
            $main_categories    = array_unique(array_filter($main_categories));
            $sub_categories     = array_column($sub_categories, 'category_id', 'category_uid');
            foreach ($sub_categories as $s_uid => $s_id) {
                $cat_arr[] = $s_id;
            }

            $products_master = array();
            $products = $this->db->select('DISTINCT ON (pattr.product_attribute_id) pattr.product_attribute_id, pattr.product_id, cat.category_uid')
                              ->from('product_attribute pattr')
                              ->join('product p', 'pattr.product_id = p.product_id', 'left')
                              ->join('product_category pcat', 'p.product_id = pcat.product_id', 'left')
                              ->join('category cat', 'pcat.category_id = cat.category_id', 'left')
                              ->where('p.is_kandora', 1)
                              ->where_in('pcat.category_id', $cat_arr)
                              ->where('p.product_vender_id', $userId)
                              ->where('cat.category_language_code', 1)
                              ->get()->result_array();
            if (! empty($products) ) {
                $products_master = array_column($products, 'product_id', 'category_uid');
                $products = array_column($products, 'product_attribute_id', 'category_uid');
            }
            
            // Already generated
            if ( count($products) > 0 ) {
                $this->db->update('product', ['product_status' => 1], ['product_vender_id' => $userId, 'is_kandora' => 1]);

                foreach ($products_master as $t_cat_id => $t_product_id) {
                    $t_cash_point = $kandora_cash_points[$t_cat_id] ?? 0;
                    $this->db->update('product', ['cash_points' => $t_cash_point], ['product_id' => $t_product_id]);
                }

                foreach ($sub_categories as $s_uid => $s_id) {
                    $t_price = $kandora_prices[$s_uid] ?? 0;
                    $t_row_id = $products[$s_uid] ?? NULL;
                    if (! $t_row_id) continue;
                    if ( $t_price == 0 ) continue;

                    $this->db->update('product_attribute', ['regular_price' => $t_price, 'sale_price' => $t_price], ['product_attribute_id' => $t_row_id]);                    
                }
            } else {
                $this->config->load('kandora');
                $product_templates = $this->config->item('kandora');
                foreach ($product_templates as $key => $tmpl) {
                    $product_data = array_merge([
                        'is_kandora' => 1,
                        'product_type' => 1,
                        'product_vender_id' => $userId,
                        'product_sale_from' => date('Y-m-d'),
                        'product_sale_to' => '2037-12-31',
                        'product_status' => 1,
                        'product_vendor_status' => 1,
                        'product_gender' => 'm',
                        'cash_points' => $kandora_cash_points[$key] ?? 0,
                    ], $tmpl);
                    $this->db->insert('product', $product_data);
                    $product_id = $this->db->insert_id();
                    
                    $product_categories = [];
                    foreach ($main_categories as $t_cat_id) {
                        $product_categories[] = [
                            'product_id' => $product_id,
                            'category_id' => $t_cat_id,
                        ];
                    }
                    $t_cat_id = $sub_categories[$key] ?? 0;
                    if ( $t_cat_id > 0 ) {
                        $product_categories[] = [
                            'product_id' => $product_id,
                            'category_id' => $t_cat_id,
                        ];
                    }
                    $this->db->insert_batch('product_category', $product_categories);

                    $product_attribute = [
                        'product_id' => $product_id,
                        'allow_back_order' => 1,
                        'sold_individually' => 1,
                        'image' => $product_data['product_image'] ?? '',
                        'sale_price' => $kandora_prices[$key] ?? 0,
                        'regular_price' => $kandora_prices[$key] ?? 0,
                    ];
                    $this->db->insert('product_attribute', $product_attribute);
                }
            }
            
        }
        return TRUE;
    }

    public function disableKandoraProducts( $userId )
    {
        if (! empty($userId) ) {
            $this->db->update('product', ['product_status' => 0], ['product_vender_id' => $userId, 'is_kandora' => 1]);
            return $this->db->affected_rows() > 0;
        }
        return TRUE;
    }

    public function updateSellerData( $userId, array $data=[])
    {
        if (! empty($data) ) {
            $this->db->where('user_id', $userId);
            $this->db->update('seller_details', $data);
            return $this->db->affected_rows() > 0;
        }

        return 0;
    }

    public function acceptVendorOrder( $vendor_id, $history_id, $order_id, $comment=NULL  )
    {
        $this->db->trans_start();

        $status_data = [
            'deliver_status'    => ORDER_STATUS_ACCEPTED,
            'driver_status'     => DRIVER_STATUS_NOT_READY,
            'store_viewed'      => 1,
        ];
        $time_now = gmdate("Y-m-d H:i:s");

        $this->db->select('poh.history_id, poh.product_id, poh.product_attribute_id');
        $this->db->from('product_order_history poh');
        $this->db->join('product product', 'poh.product_id = product.product_id', 'left');
        $this->db->where('poh.deliver_status', ORDER_STATUS_PENDING);
        $this->db->where('poh.history_id', $history_id);
        $this->db->where('product.product_vender_id', $vendor_id);        
        $order_history = $this->db->get()->result_array();
        $history_ids = array_column($order_history, 'history_id');

        $status = FALSE;
        if ( count($history_ids) > 0 ) {
            $this->db->where_in('history_id', $history_ids);
            $this->db->update('product_order_history poh', $status_data);
            $status = $this->db->affected_rows() > 0;
        }
        
        if ( $status ) {
            // Add to status history                
            $product_attribute_ids = array_column($order_history, 'product_attribute_id');
            $status_history_ids = $this->db->select('product_attribute_id')
                                            ->from('product_order_status_history')
                                            ->where('history_id', $history_id)
                                            ->where('order_block_id', $order_id)
                                            ->where('order_status', $status_data['deliver_status'])
                                            ->where('driver_status', $status_data['driver_status'])
                                            ->where_in('product_attribute_id', $product_attribute_ids)
                                            ->get()->result_array();
            $existing_product_attribute_ids = array_column($status_history_ids, 'product_attribute_id');
            $product_attribute_ids_to_create = array_diff($product_attribute_ids, $existing_product_attribute_ids);
            $status_history_data = [];
            if ( count($product_attribute_ids_to_create) > 0 ) {
                foreach ( $product_attribute_ids_to_create as $t_product_attribute_id ) {
                    $status_history_data[$t_product_attribute_id] = [
                        'order_status' => $status_data['deliver_status'],
                        'order_block_id' => $order_id,
                        'product_attribute_id' => $t_product_attribute_id,
                        'changed_by' => $vendor_id,
                        'changed_date' => $time_now,
                        'changed_user_type' => 'V',
                        'driver_status' => $status_data['driver_status'],
                        'vendor_comment' => $comment,
                        'history_id'    =>  $history_id
                    ];
                }
            }
            if (! empty($status_history_data) ) {
                $status_history_data = array_values($status_history_data);
                $this->db->insert_batch('product_order_status_history', $status_history_data);
            }
        }

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return $status;
        }
    }
    public function setVendorServiceAccepted( $vendor_id, $order_line_id, $comment=NULL )
    {
        $this->db->trans_start();

        $status_data = [
            'deliver_status'    => ORDER_STATUS_ACCEPTED,
            'driver_status'     => DRIVER_STATUS_NOT_READY,
            'store_viewed'      => 1,
        ];
        $time_now = gmdate("Y-m-d H:i:s");

        $this->db->select('poh.history_id, poh.service_id, poh.order_block_id');
        $this->db->from('product_order_history poh');
        $this->db->join('services services', 'poh.service_id = services.service_id', 'left');
        $this->db->where('poh.deliver_status', ORDER_STATUS_PENDING);
        $this->db->where('poh.history_id', $order_line_id);
        $this->db->where('services.service_vendor_user_id', $vendor_id);
        $order_history = $this->db->get()->result_array();
        $history_ids = array_column($order_history, 'history_id');

        $status = FALSE;
        if ( count($history_ids) > 0 ) {
            $this->db->where_in('history_id', $history_ids);
            $this->db->update('product_order_history poh', $status_data);
            $status = $this->db->affected_rows() > 0;

            $order_id = $order_history[0]['order_block_id'];
        }

        if ( $status ) {
            // Add to status history
            // $product_attribute_ids = array_column($order_history, 'product_attribute_id');
            // $status_history_ids = $this->db->select('product_attribute_id')
            //                                 ->from('product_order_status_history')
            //                                 ->where('history_id', $order_line_id)
            //                                 ->where('order_status', $status_data['deliver_status'])
            //                                 ->where('driver_status', $status_data['driver_status'])
            //                                 ->where_in('product_attribute_id', $product_attribute_ids)
            //                                 ->get()->result_array();
            // $existing_product_attribute_ids = array_column($status_history_ids, 'product_attribute_id');
            // $product_attribute_ids_to_create = array_diff($product_attribute_ids, $existing_product_attribute_ids);
            // $status_history_data = [];
            // if ( count($product_attribute_ids_to_create) > 0 ) {
            //     foreach ( $product_attribute_ids_to_create as $t_product_attribute_id ) {
            //         $status_history_data[$t_product_attribute_id] = [
            //             'order_status' => $status_data['deliver_status'],
            //             'order_block_id' => $order_id,
            //             'product_attribute_id' => $t_product_attribute_id,
            //             'changed_by' => $vendor_id,
            //             'changed_date' => $time_now,
            //             'changed_user_type' => 'V',
            //             'driver_status' => $status_data['driver_status'],
            //             'vendor_comment' => $comment,
            //         ];
            //     }
            // }
            // if (! empty($status_history_data) ) {
            //     $status_history_data = array_values($status_history_data);
            //     $this->db->insert_batch('product_order_status_history', $status_history_data);
            // }
        }

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return $status;
        }
    }

    public function setVendorOrderReadyForDelivery( $vendor_id, $order_line_id, $order_id, $comment=NULL, $driver_id=NULL )
    {
        $this->db->trans_start();

        $status_data = [
            'deliver_status'    => ORDER_STATUS_READY,
            'driver_status'     => DRIVER_STATUS_PENDING,            
        ];
        if ( $driver_id > 0 ) {
            $status_data['driver_id'] = $driver_id;
        }

        $order_line_id = explode(',', $order_line_id);
        if ( is_array($order_line_id) ) {
            $order_line_id = array_map('trim', $order_line_id);
            $order_line_id = array_map('intval', $order_line_id);
            $order_line_id = array_filter($order_line_id);
        }

        $time_now = gmdate("Y-m-d H:i:s");

        $this->db->select('poh.history_id, poh.product_id, poh.product_attribute_id, poh.order_block_id');
        $this->db->from('product_order_history poh');
        $this->db->join('product product', 'poh.product_id = product.product_id', 'left');
        $this->db->where('poh.deliver_status', ORDER_STATUS_ACCEPTED);
        if ( is_array($order_line_id) ) {
            $this->db->where_in('poh.history_id', $order_line_id);
        } else {
            $this->db->where('poh.history_id', $order_line_id);
        }
        $this->db->where('product.product_vender_id', $vendor_id);
        $order_history = $this->db->get()->result_array();
        $history_ids = array_column($order_history, 'history_id');

        $status = FALSE;
        if ( count($history_ids) > 0 ) {
            // Create a picking
            $this->db->insert('product_order_picking', ['driver_id' => $driver_id, 'created_date' => $time_now]);
            $picking_id = $this->db->insert_id('product_order_picking_picking_id_seq');
            if ( $picking_id > 0 ) {
                $status_data['picking_id'] = $picking_id;
                $this->db->where_in('history_id', $history_ids);
                $this->db->update('product_order_history poh', $status_data);
                $status = $this->db->affected_rows() > 0;
            }
        }
        
        if ( $status ) {
            // Add to status history                
            $product_attribute_ids = array_column($order_history, 'product_attribute_id');
            $status_history_ids = $this->db->select('product_attribute_id')
                                            ->from('product_order_status_history')
                                            ->where('order_block_id', $order_id)
                                            ->where_in('history_id', $history_ids)
                                            ->where('order_status', $status_data['deliver_status'])
                                            ->where('driver_status', $status_data['driver_status'])
                                            ->where_in('product_attribute_id', $product_attribute_ids)
                                            ->get()->result_array();
            $existing_product_attribute_ids = array_column($status_history_ids, 'product_attribute_id');
            $product_attribute_ids_to_create = array_diff($product_attribute_ids, $existing_product_attribute_ids);
            $status_history_data = [];
            if ( count($product_attribute_ids_to_create) > 0 ) {
                foreach ( $product_attribute_ids_to_create as $t_product_attribute_id ) {
                    $status_history_data[$t_product_attribute_id] = [
                        'order_status' => $status_data['deliver_status'],
                        'order_block_id' => $order_id,
                        'product_attribute_id' => $t_product_attribute_id,
                        'changed_by' => $vendor_id,
                        'changed_date' => $time_now,
                        'changed_user_type' => 'V',
                        'driver_status' => $status_data['driver_status'],
                        'vendor_comment' => $comment,
                        'history_id'    =>  $history_id
                    ];
                }
            }
            if (! empty($status_history_data) ) {
                $status_history_data = array_values($status_history_data);
                $this->db->insert_batch('product_order_status_history', $status_history_data);
            }
        }

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return $status;
        }
    }

    public function setVendorOrderStartJourney( $vendor_id, $history_id, $order_id, $comment=NULL )
    {
        $this->db->trans_start();

        $status_data = [
            'deliver_status'    => ORDER_STATUS_DISPATCHED,
            'driver_status'     => DRIVER_STATUS_START_JOURNEY,            
        ];
        $time_now = gmdate("Y-m-d H:i:s");

        $this->db->select('poh.history_id, poh.product_id, poh.product_attribute_id');
        $this->db->from('product_order_history poh');
        $this->db->join('product product', 'poh.product_id = product.product_id', 'left');
        $this->db->where('poh.deliver_status', ORDER_STATUS_READY);
        $this->db->where('poh.history_id', $history_id);
        $this->db->where('product.product_vender_id', $vendor_id);        
        $order_history = $this->db->get()->result_array();
        $history_ids = array_column($order_history, 'history_id');

        $status = FALSE;
        if ( count($history_ids) > 0 ) {
            $this->db->where_in('history_id', $history_ids);
            $this->db->update('product_order_history poh', $status_data);
            $status = $this->db->affected_rows() > 0;
        }
        
        if ( $status ) {
            // Add to status history                
            $product_attribute_ids = array_column($order_history, 'product_attribute_id');
            $status_history_ids = $this->db->select('product_attribute_id')
                                            ->from('product_order_status_history')
                                            ->where('order_block_id', $order_id)
                                            ->where('history_id', $history_id)
                                            ->where('order_status', $status_data['deliver_status'])
                                            ->where('driver_status', $status_data['driver_status'])
                                            ->where_in('product_attribute_id', $product_attribute_ids)
                                            ->get()->result_array();
            $existing_product_attribute_ids = array_column($status_history_ids, 'product_attribute_id');
            $product_attribute_ids_to_create = array_diff($product_attribute_ids, $existing_product_attribute_ids);
            $status_history_data = [];
            if ( count($product_attribute_ids_to_create) > 0 ) {
                foreach ( $product_attribute_ids_to_create as $t_product_attribute_id ) {
                    $status_history_data[$t_product_attribute_id] = [
                        'order_status' => $status_data['deliver_status'],
                        'order_block_id' => $order_id,
                        'product_attribute_id' => $t_product_attribute_id,
                        'changed_by' => $vendor_id,
                        'changed_date' => $time_now,
                        'changed_user_type' => 'V',
                        'driver_status' => $status_data['driver_status'],
                        'vendor_comment' => $comment,
                        'history_id'    =>  $history_id
                    ];
                }
            }
            if (! empty($status_history_data) ) {
                $status_history_data = array_values($status_history_data);
                $this->db->insert_batch('product_order_status_history', $status_history_data);
            }
        }

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return $status;
        }
    }

    public function setVendorOrderDelivered( $vendor_id,$history_id, $order_id, $comment=NULL )
    {
        $this->db->trans_start();

        $status_data = [
            'deliver_status'    => ORDER_STATUS_DELIVERED,
            'driver_status'     => DRIVER_STATUS_DELIVERED, 
            'delivered_date'     =>  gmdate("Y-m-d H:i:s")
        ];
        $time_now = gmdate("Y-m-d H:i:s");

        $this->db->select('poh.history_id, poh.product_id, poh.product_attribute_id, pod.user_id, COALESCE(poh.total_cash_points, 0) AS total_cash_points');
        $this->db->from('product_order_history poh');
        $this->db->join('product_order_details pod', 'poh.order_block_id = pod.order_block_id', 'left');
        $this->db->join('product product', 'poh.product_id = product.product_id', 'left');
        $this->db->where('poh.deliver_status', ORDER_STATUS_ACCEPTED);
        $this->db->where('poh.history_id', $history_id);
        $this->db->where('product.product_vender_id', $vendor_id);        
        $order_history = $this->db->get()->result_array();
        $history_ids = array_column($order_history, 'history_id');

        $status = FALSE;
        if ( count($history_ids) > 0 ) {
            $this->db->where_in('history_id', $history_ids);
            $this->db->update('product_order_history poh', $status_data);
            $status = $this->db->affected_rows() > 0;
        }
        
        if ( $status ) {
            // Add to status history                
            $product_attribute_ids = array_column($order_history, 'product_attribute_id');
            $status_history_ids = $this->db->select('product_attribute_id')
                                            ->from('product_order_status_history')
                                            ->where('order_block_id', $order_id)
                                            ->where('history_id', $history_id)
                                            ->where('order_status', $status_data['deliver_status'])
                                            ->where('driver_status', $status_data['driver_status'])
                                            ->where_in('product_attribute_id', $product_attribute_ids)
                                            ->get()->result_array();
            $existing_product_attribute_ids = array_column($status_history_ids, 'product_attribute_id');
            $product_attribute_ids_to_create = array_diff($product_attribute_ids, $existing_product_attribute_ids);
            $status_history_data = [];
            if ( count($product_attribute_ids_to_create) > 0 ) {
                foreach ( $product_attribute_ids_to_create as $t_product_attribute_id ) {
                    $status_history_data[$t_product_attribute_id] = [
                        'order_status' => $status_data['deliver_status'],
                        'order_block_id' => $order_id,
                        'product_attribute_id' => $t_product_attribute_id,
                        'changed_by' => $vendor_id,
                        'changed_date' => $time_now,
                        'changed_user_type' => 'V',
                        'driver_status' => $status_data['driver_status'],
                        'vendor_comment' => $comment,
                        'history_id'    =>  $history_id
                    ];
                }
            }
            if (! empty($status_history_data) ) {
                $status_history_data = array_values($status_history_data);
                $this->db->insert_batch('product_order_status_history', $status_history_data);
            }
            // Customer earned cash points
            $user_id    = $order_history[0]['user_id'];
            $user_data  = $this->db->get_where('user_table', ['user_id' => $user_id])->row();        
            
            $earned_cash_points = array_column($order_history, 'total_cash_points');
            $earned_cash_points = array_sum($earned_cash_points);
            if ( $earned_cash_points > 0 ) {
                $cash_point_data = [
                    'cp_user_id' => $user_id, 
                    'cp_status' => 1,
                    'cp_date' => $time_now,
                    'used_earned_points' => $earned_cash_points,
                    'order_block_id' => $order_id,
                ];
                $this->db->insert('cash_points', $cash_point_data);

                $user_data = $this->db->get_where('user_table', ['user_id' => $user_id])->row();

                $user_points = $user_data->user_points + $earned_cash_points;
                $this->db->update('user_table', ['user_points' => $user_points], ['user_id' => $user_id]);
            }

            // Change order status
            $not_cancelled_items = $this->db->select('deliver_status')
                                        ->from('product_order_history')
                                        ->where('order_block_id', $order_id)
                                        ->where('deliver_status !=', ORDER_STATUS_CANCEL)
                                        ->get()->result_array();
            
            // If all items are cancelled
            if ( count($not_cancelled_items) == 0 ) {
                $order_status = ORDER_STATUS_CANCEL;
            } else {
                // Delivery status must be the least value amongst all deliver status
                $order_status = min(array_column($not_cancelled_items, 'deliver_status'));
            }
            
            $this->db->where('order_block_id', $order_id);
            $this->db->where('delivery_status !=', ORDER_STATUS_CANCEL);
            $this->db->update('product_order_details', [
                'delivery_status' => $order_status
            ]);
        }

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return $status;
        }
    }

    public function completeBooking( $vendor_id, $order_line_id, $comment=NULL )
    {
        $this->db->trans_start();

        $status_data = [
            'deliver_status'        => ORDER_STATUS_DELIVERED,
            'store_viewed'          => 1,
        ];
        $time_now = gmdate("Y-m-d H:i:s");

        $this->db->select('poh.history_id, poh.product_id, poh.product_attribute_id, poh.deliver_status, pattr.stock_quantity, poh.purchase_qty, poh.order_block_id');
        $this->db->from('product_order_history poh');
        $this->db->join('services services', 'poh.service_id = services.service_id', 'left');
        $this->db->join('product_attribute pattr', 'poh.product_attribute_id = pattr.product_attribute_id', 'left');
        $this->db->where('poh.deliver_status', ORDER_STATUS_ACCEPTED);
        $this->db->where('poh.history_id', $order_line_id);
        $this->db->where('services.service_vendor_user_id', $vendor_id);
        $order_history = $this->db->get()->result_array();
        $history_ids = array_column($order_history, 'history_id');
        //echo $this->db->last_query();

        $status = FALSE;
        if ( count($history_ids) > 0 ) {
            $this->db->where_in('history_id', $history_ids);
            $this->db->update('product_order_history poh', $status_data);
            $status = $this->db->affected_rows() > 0;

            $order_id = $order_history[0]['order_block_id'];
        }

        if ( $status ) {
            $not_cancelled_items = $this->db->select('deliver_status, total_cash_points')
                                        ->from('product_order_history')
                                        ->where('history_id', $order_line_id)
                                        ->where('deliver_status !=', ORDER_STATUS_DELIVERED)
                                        ->get()->result_array();

            // If all items are cancelled
            if ( count($not_cancelled_items) == 0 ) {
                $order_status = ORDER_STATUS_DELIVERED;
                $earned_cash_points = 0;
            } else {
                // Delivery status must be the least value amongst all deliver status
                $order_status = min(array_column($not_cancelled_items, 'deliver_status'));
                $earned_cash_points = array_sum(array_column($not_cancelled_items, 'total_cash_points'));
            }

            $this->db->where('order_block_id', $order_id);
            $this->db->where('delivery_status !=', ORDER_STATUS_DELIVERED);
            $this->db->update('product_order_details', [
                'delivery_status' => $order_status
            ]);

            // Add to status history
            // $product_attribute_ids = array_column($order_history, 'product_attribute_id');
            // $status_history_ids = $this->db->select('product_attribute_id')
            //                                 ->from('product_order_status_history')
            //                                 ->where('history_id', $order_line_id)
            //                                 ->where('order_status', $status_data['deliver_status'])
            //                                 ->where('driver_status', DRIVER_STATUS_NOT_READY)
            //                                 ->where_in('product_attribute_id', $product_attribute_ids)
            //                                 ->get()->result_array();
            // $existing_product_attribute_ids = array_column($status_history_ids, 'product_attribute_id');
            // $product_attribute_ids_to_create = array_diff($product_attribute_ids, $existing_product_attribute_ids);
            // $status_history_data = [];
            // if ( count($product_attribute_ids_to_create) > 0 ) {
            //     foreach ( $product_attribute_ids_to_create as $t_product_attribute_id ) {
            //         $status_history_data[$t_product_attribute_id] = [
            //             'order_status' => $status_data['deliver_status'],
            //             'order_block_id' => $order_id,
            //             'product_attribute_id' => $t_product_attribute_id,
            //             'changed_by' => $vendor_id,
            //             'changed_date' => $time_now,
            //             'changed_user_type' => 'V',
            //             'driver_status' => DRIVER_STATUS_NOT_READY,
            //             'vendor_comment' => $comment,
            //         ];
            //     }
            // }
            // if (! empty($status_history_data) ) {
            //     $status_history_data = array_values($status_history_data);
            //     $this->db->insert_batch('product_order_status_history', $status_history_data);
            // }
            
        }

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return $status;
        }
    }
    public function cancelVendorBooking( $vendor_id, $order_line_id, $comment=NULL )
    {
        $this->db->trans_start();

        $status_data = [
            'deliver_status'        => ORDER_STATUS_CANCEL,
            'product_cash_point'    => 0,
            'total_cash_points'     => 0,
            'store_viewed'          => 1,
        ];
        $time_now = gmdate("Y-m-d H:i:s");

        $this->db->select('poh.history_id, poh.product_id, poh.product_attribute_id, poh.deliver_status, pattr.stock_quantity, poh.purchase_qty, poh.order_block_id');
        $this->db->from('product_order_history poh');
        $this->db->join('services services', 'poh.service_id = services.service_id', 'left');
        $this->db->join('product_attribute pattr', 'poh.product_attribute_id = pattr.product_attribute_id', 'left');
        $this->db->where('poh.deliver_status', ORDER_STATUS_PENDING);
        $this->db->where('poh.history_id', $order_line_id);
        $this->db->where('services.service_vendor_user_id', $vendor_id);
        $order_history = $this->db->get()->result_array();
        $history_ids = array_column($order_history, 'history_id');

        $status = FALSE;
        if ( count($history_ids) > 0 ) {
            $this->db->where_in('history_id', $history_ids);
            $this->db->update('product_order_history poh', $status_data);
            $status = $this->db->affected_rows() > 0;

            $order_id = $order_history[0]['order_block_id'];
        }

        if ( $status ) {
            $not_cancelled_items = $this->db->select('deliver_status, total_cash_points')
                                        ->from('product_order_history')
                                        ->where('history_id', $order_line_id)
                                        ->where('deliver_status !=', ORDER_STATUS_CANCEL)
                                        ->get()->result_array();

            // If all items are cancelled
            if ( count($not_cancelled_items) == 0 ) {
                $order_status = ORDER_STATUS_CANCEL;
                $earned_cash_points = 0;
            } else {
                // Delivery status must be the least value amongst all deliver status
                $order_status = min(array_column($not_cancelled_items, 'deliver_status'));
                $earned_cash_points = array_sum(array_column($not_cancelled_items, 'total_cash_points'));
            }

            $this->db->where('order_block_id', $order_id);
            $this->db->where('delivery_status !=', ORDER_STATUS_CANCEL);
            $this->db->update('product_order_details', [
                'delivery_status' => $order_status,
                'earned_cash_points' => $earned_cash_points,
            ]);

            // Add to status history
            // $product_attribute_ids = array_column($order_history, 'product_attribute_id');
            // $status_history_ids = $this->db->select('product_attribute_id')
            //                                 ->from('product_order_status_history')
            //                                 ->where('history_id', $order_line_id)
            //                                 ->where('order_status', $status_data['deliver_status'])
            //                                 ->where('driver_status', DRIVER_STATUS_NOT_READY)
            //                                 ->where_in('product_attribute_id', $product_attribute_ids)
            //                                 ->get()->result_array();
            // $existing_product_attribute_ids = array_column($status_history_ids, 'product_attribute_id');
            // $product_attribute_ids_to_create = array_diff($product_attribute_ids, $existing_product_attribute_ids);
            // $status_history_data = [];
            // if ( count($product_attribute_ids_to_create) > 0 ) {
            //     foreach ( $product_attribute_ids_to_create as $t_product_attribute_id ) {
            //         $status_history_data[$t_product_attribute_id] = [
            //             'order_status' => $status_data['deliver_status'],
            //             'order_block_id' => $order_id,
            //             'product_attribute_id' => $t_product_attribute_id,
            //             'changed_by' => $vendor_id,
            //             'changed_date' => $time_now,
            //             'changed_user_type' => 'V',
            //             'driver_status' => DRIVER_STATUS_NOT_READY,
            //             'vendor_comment' => $comment,
            //         ];
            //     }
            // }
            // if (! empty($status_history_data) ) {
            //     $status_history_data = array_values($status_history_data);
            //     $this->db->insert_batch('product_order_status_history', $status_history_data);
            // }
            
        }

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return $status;
        }
    }
    public function cancelVendorOrder( $vendor_id,$history_id, $order_id, $comment=NULL )
    {
        
        $this->db->trans_start();

        $status_data = [
            'deliver_status'        => ORDER_STATUS_CANCEL,
            'product_cash_point'    => 0,
            'total_cash_points'     => 0,
            'store_viewed'          => 1,
        ];
        $time_now = gmdate("Y-m-d H:i:s");

        $this->db->select('poh.history_id, poh.product_id, poh.product_attribute_id, poh.deliver_status, pattr.stock_quantity, poh.purchase_qty');
        $this->db->from('product_order_history poh');
        $this->db->join('product product', 'poh.product_id = product.product_id', 'left');
        $this->db->join('product_attribute pattr', 'poh.product_attribute_id = pattr.product_attribute_id', 'left');
        $this->db->where('poh.deliver_status', ORDER_STATUS_PENDING);
        $this->db->where('poh.history_id', $history_id);
        $this->db->where('product.product_vender_id', $vendor_id);        
        $order_history = $this->db->get()->result_array();

        $history_ids = array_column($order_history, 'history_id');

        $status = FALSE;
        if ( count($history_ids) > 0 ) {
            $this->db->where_in('history_id', $history_ids);
            $this->db->update('product_order_history poh', $status_data);
            $status = $this->db->affected_rows() > 0;
        }
        
        if ( $status ) {
            $not_cancelled_items = $this->db->select('deliver_status, total_cash_points')
                                        ->from('product_order_history')
                                        ->where('order_block_id', $order_id)
                                        ->where('deliver_status !=', ORDER_STATUS_CANCEL)
                                        ->get()->result_array();
            
            // If all items are cancelled
            if ( count($not_cancelled_items) == 0 ) {
                $order_status = ORDER_STATUS_CANCEL;
                $earned_cash_points = 0;
            } else {
                // Delivery status must be the least value amongst all deliver status
                $order_status = min(array_column($not_cancelled_items, 'deliver_status'));
                $earned_cash_points = array_sum(array_column($not_cancelled_items, 'total_cash_points'));
            }
            
            $this->db->where('order_block_id', $order_id);
            $this->db->where('delivery_status !=', ORDER_STATUS_CANCEL);
            $this->db->update('product_order_details', [
                'delivery_status' => $order_status,
                'earned_cash_points' => $earned_cash_points,
            ]);
        
            // Add to status history                
            $product_attribute_ids = array_column($order_history, 'product_attribute_id');
            $status_history_ids = $this->db->select('product_attribute_id')
                                            ->from('product_order_status_history')
                                            ->where('order_block_id', $order_id)
                                            ->where('history_id', $history_id)
                                            ->where('order_status', $status_data['deliver_status'])
                                            ->where('driver_status', DRIVER_STATUS_NOT_READY)
                                            ->where_in('product_attribute_id', $product_attribute_ids)
                                            ->get()->result_array();
            $existing_product_attribute_ids = array_column($status_history_ids, 'product_attribute_id');
            $product_attribute_ids_to_create = array_diff($product_attribute_ids, $existing_product_attribute_ids);
            $status_history_data = [];
            if ( count($product_attribute_ids_to_create) > 0 ) {
                foreach ( $product_attribute_ids_to_create as $t_product_attribute_id ) {
                    $status_history_data[$t_product_attribute_id] = [
                        'order_status' => $status_data['deliver_status'],
                        'order_block_id' => $order_id,
                        'product_attribute_id' => $t_product_attribute_id,
                        'changed_by' => $vendor_id,
                        'changed_date' => $time_now,
                        'changed_user_type' => 'V',
                        'driver_status' => DRIVER_STATUS_NOT_READY,
                        'vendor_comment' => $comment,
                        'history_id'    =>  $history_id
                    ];
                }
            }
            if (! empty($status_history_data) ) {
                $status_history_data = array_values($status_history_data);
                $this->db->insert_batch('product_order_status_history', $status_history_data);
            }
            // Update stock quantity
            foreach ( $order_history as $history ) {
                $this->db->update('product_attribute', ['stock_quantity' => $history['stock_quantity']+$history['purchase_qty']], ['product_attribute_id' => $history['product_attribute_id']]);
            }
        }

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            return 0;
        } else {
            return $status;
        }
    }

    public function getAllActiveDrivers() {

        return $this->db->select('*')
                        ->from('user_table u')
                        ->join('driver_details s', 'u.user_id =s.user_id', 'inner')
                        ->where("u.user_type = 'D'")
                        ->order_by('u.user_id', 'desc')
                        ->order_by('u.user_status', 1)
                        ->order_by('u.user_deleted', 0)
                        ->get()
                        ->result();
    }

    public function getUserById( $user_id, $lang_code = 1 ) {

        return $this->db->select("user_table.*, country_name")
                        ->from("user_table")
                        ->join("country", "country.country_id = user_table.user_country_id and country.country_language_code = {$lang_code} ", "left")
                        ->where("user_id", $user_id)
                        ->get()
                        ->row();
    }

    public function getSellerByUserId( $user_id )
    {
        return $this->db->get_where('seller_details', ['user_id' => $user_id])->row();
    }

    private function _getSalesHistoryQuery( array $search_params=array(), $limit=NULL, $offset=NULL )
    {
        $this->db->select("DISTINCT ON (pod.order_block_id) pod.order_block_id, pod.order_no, pod.order_placed_date, poh.deliver_status, poh.driver_status, usr.company_name AS customer_name, pod.user_id, COUNT(product.product_id) AS total_products, AVG(poh.product_total_shipping_charge_uc) AS shipping_charge, SUM(poh.unit_measurement_charge_uc) AS measurement_charge, (SUM(poh.product_total_uc) + AVG(poh.product_total_shipping_charge_uc) + SUM(poh.unit_measurement_charge_uc)) grand_total, ush.user_shiping_details_building, ush.user_shiping_details_street, ush.user_shiping_details_loc, ush.user_shiping_details_landmark, ush.user_shiping_details_flatno, ush.user_shiping_details_floorno, ush.user_shiping_details_phone, ct.city_name, cn.country_name", FALSE);
        $this->db->from('product_order_details pod');        
        $this->db->join('user_table usr', 'pod.user_id = usr.user_id', 'left');
        $this->db->join('user_shiping_details ush', 'ush.user_shiping_details_id = pod.shipping_address_id', 'left');
        $this->db->join('(SELECT * FROM city WHERE city_language_code = 1) ct', 'ush.user_shiping_details_city = ct.city_id', 'left');
        $this->db->join('(SELECT * FROM country WHERE country_language_code = 1) cn', 'cn.country_id = ct.city_country_id', 'left');
        $this->db->join('product_order_history poh', 'pod.order_block_id = poh.order_block_id', 'left');
        $this->db->join('product product', 'poh.product_id = product.product_id', 'left');
        $this->db->join('seller_details store', 'product.product_vender_id = store.user_id', 'left');
        $this->db->order_by('pod.order_block_id DESC');
        $this->db->group_by(['pod.order_block_id', 'pod.order_no', 'pod.order_placed_date', 'poh.deliver_status', 'poh.driver_status', 'usr.company_name', 'pod.user_id', 'ush.user_shiping_details_building', 'ush.user_shiping_details_street', 'ush.user_shiping_details_loc', 'ush.user_shiping_details_landmark', 'ush.user_shiping_details_flatno', 'ush.user_shiping_details_floorno', 'ush.user_shiping_details_phone', 'ct.city_name', 'cn.country_name']);

        if ( $limit ) {
            $this->db->limit($limit, $offset);
        }

        $search_key = strtolower($search_params['search_key'] ?? '');
        if (! empty($search_key) ) {
            $this->db->group_start();
                $this->db->like('pod.order_block_id::text', $search_key);
                $this->db->or_like('pod.order_no::text', $search_key);
                $this->db->or_like('LOWER(store.store_name)', $search_key);
                $this->db->or_like('LOWER(product.product_name)', $search_key);
            $this->db->group_end();
        }
        if ( array_key_exists('order_status', $search_params) && $search_params['order_status'] >= 0 ) {
            $this->db->where('poh.deliver_status', $search_params['order_status']);
        }
        $sale_date_from = $search_params['order_start_date'] ?? NULL;
        if (! empty($sale_date_from) ) {
            $this->db->where('DATE(pod.order_placed_date) >=', $sale_date_from);
        }
        $sale_date_to = $search_params['order_end_date'] ?? NULL;
        if (! empty($sale_date_to) ) {
            $this->db->where('DATE(pod.order_placed_date) <=', $sale_date_to);
        }
        if ( array_key_exists('vendor_id', $search_params) && $search_params['vendor_id'] >= 0 ) {
            $this->db->where('product.product_vender_id', $search_params['vendor_id']);
        }

        return $this->db->get();
    }

    public function getSalesHistoryCount( array $search_params=array() )
    {
        return $this->_getSalesHistoryQuery($search_params)->num_rows();
    }

    public function getSalesHistory( array $search_params=array(), $limit=NULL, $offset=NULL )
    {
        $res = $this->_getSalesHistoryQuery($search_params, $limit, $offset)->result();

        $result = [];
        foreach ($res as $row) {
            $row->products = [];
            $result[$row->order_block_id] = $row;
        }

        // Fetch order products
        $order_block_ids = array_column($res, 'order_block_id');
        if (! empty($order_block_ids) ) {
            if ( array_key_exists('vendor_id', $search_params) && $search_params['vendor_id'] >= 0 ) {
                $this->db->where('product.product_vender_id', $search_params['vendor_id']);
            }
        
            $this->db->select('poh.order_block_id, poh.purchase_qty, poh.unit_price, poh.product_sub_price, poh.unit_shipping_charge, poh.deliver_status, pattr.product_attribute_id, pattr.image, product.product_name');
            $this->db->select(
                "
                STRING_AGG (
                    (
                        product_variation.attribute_name::TEXT || ': ' ||
                        product_variation.attribute_values::TEXT
                    ), ', '
                ) AS product_variant_name
                "
            );
            $this->db->from('product_order_history poh');
            $this->db->join('product_attribute pattr', 'poh.product_attribute_id = pattr.product_attribute_id', 'left');
            $this->db->join('product product', 'pattr.product_id = product.product_id', 'left');
            $this->db->join(
                "
                (SELECT 
                    pvar.product_attribute_id,  
                    pvar.product_variations_id,
                    attr.attribute_name,
                    attrv.attribute_values,
                    attrv.attribute_value_in,
                    attrv.attribute_value_color,
                    attrv.attribute_value_label,
                    attrv.attribute_value_image
                FROM product_variations pvar
                LEFT JOIN attribute attr ON pvar.attribute_id = attr.attribute_id
                LEFT JOIN attribute_values attrv ON pvar.attribute_values_id = attrv.attribute_values_id
                ) AS product_variation
                ",
                'pattr.product_attribute_id = product_variation.product_attribute_id',
                'left'
            );
            $this->db->where('pattr.product_attribute_id !=', NULL);
            $this->db->where('product.product_id !=', NULL);
            $this->db->where_in('poh.order_block_id', $order_block_ids);
            $this->db->order_by('product.product_name ASC');
            $this->db->group_by(['poh.order_block_id', 'poh.purchase_qty', 'poh.unit_price', 'poh.product_sub_price', 'poh.unit_shipping_charge', 'poh.deliver_status', 'pattr.product_attribute_id', 'pattr.image', 'product.product_name']);
            $order_products = $this->db->get()->result();
            foreach ($order_products as $product_row) {
                if ( array_key_exists($product_row->order_block_id, $result)) {
                    $result[$product_row->order_block_id]->products[] = $product_row;
                }
            }
        }

        return $result;
    }

    public function getKandoraCategoryColors( $category_uid, $lang_code="1" )
    {
        if ( $lang_code == "2" ) {
            $this->db->select('cattrv.cat_attribute_val_value_arabic AS cat_attribute_value, cattrv.cat_attribute_val_label_arabic AS cat_attribute_value_label, cattr.cat_attribute_name_arabic AS cat_attribute_name');
        } else {
            $this->db->select('cattrv.cat_attribute_val_value AS cat_attribute_value, cattrv.cat_attribute_val_label AS cat_attribute_value_label, cattr.cat_attribute_name');
        }
        $this->db->select('cattrv.cat_attribute_val_id AS cat_attribute_value_id, cattrv.cat_attribute_val_image AS cat_attribute_value_image, cattr.cat_attribute_id');
        $this->db->from('category_attribute_values cattrv');
        $this->db->join('category_attribute cattr', 'cattrv.cat_attribute_id = cattr.cat_attribute_id', 'left');
        $this->db->join('category cat', 'cattr.category_id = cat.category_id', 'left');
        $this->db->join('category_attribute_type cattr_type', 'cattr.cat_attribute_type = cattr_type.cat_attribute_type_id', 'left');
        $this->db->where('cattr.cat_attribute_type = cattrv.cat_attribute_val_type_id');
        $this->db->where('cat.category_uid', $category_uid);
        $this->db->where('cat.category_language_code', $lang_code);
        $this->db->where('cattr.cat_attribute_status', 1);
        $this->db->where('cattr.cat_attribute_is_color', 1);
        $this->db->where('cattrv.cat_attribute_val_status', 1);

        $this->db->order_by('cattr.cat_attribute_sort_order ASC, cattrv.cat_attribute_val_sort_order ASC');
        
        return $this->db->get()->result_array();
    }

    public function getSellerKandoraColors( $store_id, $category_uid, $lang_code="1" )
    {
        if ( $lang_code == "2" ) {
            $this->db->select('cattrv.cat_attribute_val_value_arabic AS cat_attribute_value, cattrv.cat_attribute_val_label_arabic AS cat_attribute_value_label, cattr.cat_attribute_name_arabic AS cat_attribute_name');
        } else {
            $this->db->select('cattrv.cat_attribute_val_value AS cat_attribute_value, cattrv.cat_attribute_val_label AS cat_attribute_value_label, cattr.cat_attribute_name');
        }
        $this->db->select('cattrv.cat_attribute_val_id AS cat_attribute_value_id, cattrv.cat_attribute_val_image AS cat_attribute_value_image, cattr.cat_attribute_id, cattr_store_val.cat_attribute_val_store_status AS attribute_val_store_status');
        $this->db->from('category_attribute_values cattrv');
        $this->db->join('category_attribute cattr', 'cattrv.cat_attribute_id = cattr.cat_attribute_id', 'left');
        $this->db->join('category cat', 'cattr.category_id = cat.category_id', 'left');
        $this->db->join('category_attribute_type cattr_type', 'cattr.cat_attribute_type = cattr_type.cat_attribute_type_id', 'left');
        $this->db->join('(SELECT * FROM category_attribute_store_values WHERE cat_attribute_store_id = '. $this->db->escape($store_id) .') cattr_store_val', 'cattrv.cat_attribute_val_id = cattr_store_val.cat_attribute_val_id', 'left');
        $this->db->where('cattr.cat_attribute_type = cattrv.cat_attribute_val_type_id');
        $this->db->where('cat.category_uid', $category_uid);
        $this->db->where('cat.category_language_code', $lang_code);
        $this->db->where('cattr.cat_attribute_status', 1);
        $this->db->where('cattr.cat_attribute_is_color', 1);
        $this->db->where('cattrv.cat_attribute_val_status', 1);
        $this->db->group_start();
            $this->db->where('cattrv.cat_attribute_val_store_id', $store_id);
            $this->db->or_where('cattrv.cat_attribute_val_store_id', NULL);
        $this->db->group_end();        

        $this->db->order_by('cattr.cat_attribute_sort_order ASC, cattrv.cat_attribute_val_sort_order ASC');
        
        return $this->db->get()->result_array();
    }

    public function saveSellerKandoraColor( $store_id, $all_colors, $colors )
    {
        if (! empty($all_colors) && !empty($colors) ) {
            $this->db->trans_start();

            $this->db->where('cat_attribute_store_id', $store_id);
            $this->db->where_in('cat_attribute_val_id', $all_colors);
            $this->db->delete('category_attribute_store_values');

            $this->db->insert_batch('category_attribute_store_values', $colors);

            if ( $this->db->trans_status() === FALSE ) {
                $this->db->trans_rollback();
                return 0;
            } else {
                $this->db->trans_commit();
                return 1;
            }
        }

        return 0;
    }

    public function getFabricName( $category_uid )
    {
        $this->db->select('cattr.*');
        $this->db->from('category_attribute cattr');
        $this->db->join('category cat', 'cattr.category_id = cat.category_id', 'left');        
        $this->db->where('cat.category_uid', $category_uid);
        $this->db->where('cat.category_language_code', 1);
        $this->db->where('cattr.cat_attribute_status', 1);
        $this->db->where('cattr.cat_attribute_is_fabric_name', 1);
        $this->db->limit(1);

        $row = $this->db->get()->row();
        if ( $row ) {
            $this->db->select('cattrv.*');
            $this->db->from('category_attribute_values cattrv');
            $this->db->join('category_attribute cattr', 'cattrv.cat_attribute_id = cattr.cat_attribute_id', 'left');
            $this->db->where('cattrv.cat_attribute_val_status', 1);
            $this->db->where('cattr.cat_attribute_status', 1);
            $this->db->where('cattr.cat_attribute_is_color', 0);
            $this->db->where('cattr.cat_attribute_parent_id', $row->cat_attribute_id);
            $row->fabric_types = $this->db->get()->result_array();
        }

        return $row;
    }

    public function getSellerFabricNames( $store_id, $category_uid, $lang_code="1" )
    {
        $this->db->select('DISTINCT ON (cattrv.cat_attribute_val_id) cattrv.cat_attribute_val_id AS cat_attribute_value_id');
        if ( $lang_code == "2" ) {
            $this->db->select('cattrv.cat_attribute_val_value_arabic AS cat_attribute_value, cattr.cat_attribute_name_arabic AS cat_attribute_name');
        } else {
            $this->db->select('cattrv.cat_attribute_val_value AS cat_attribute_value, cattr.cat_attribute_name');
        }
        $this->db->select("cattrv.cat_attribute_val_type_id, COALESCE(cattrv.cat_attribute_val_extra_price, 0) AS extra_price, cattr.cat_attribute_id, STRING_AGG(cfab_type.cat_fabric_type_value_id::TEXT, ',') AS cat_fabric_types, STRING_AGG(cfab_color.cat_fabric_color_id::TEXT, ',') AS cat_fabric_colors");
        $this->db->from('category_attribute_values cattrv');
        $this->db->join('category_attribute cattr', 'cattrv.cat_attribute_id = cattr.cat_attribute_id', 'left');
        $this->db->join('category cat', 'cattr.category_id = cat.category_id', 'left');
        $this->db->join('category_attribute_type cattr_type', 'cattr.cat_attribute_type = cattr_type.cat_attribute_type_id', 'left');
        $this->db->join('category_fabric_type cfab_type', 'cattrv.cat_attribute_val_id = cfab_type.cat_fabric_name_value_id', 'left');
        $this->db->join('category_fabric_color cfab_color', 'cattrv.cat_attribute_val_id = cfab_color.cat_fabric_name_value_id', 'left');
        $this->db->where('cattr.cat_attribute_type = cattrv.cat_attribute_val_type_id');
        $this->db->where('cat.category_uid', $category_uid);
        $this->db->where('cat.category_language_code', $lang_code);
        $this->db->where('cattr.cat_attribute_status', 1);
        $this->db->where('cattr.cat_attribute_is_fabric_name', 1);
        $this->db->where('cattrv.cat_attribute_val_status', 1);
        $this->db->where('cattrv.cat_attribute_val_store_id', $store_id);
        $this->db->group_by(['cattrv.cat_attribute_val_id', 'cattrv.cat_attribute_val_type_id', 'cattr.cat_attribute_id']);
        if ( $lang_code == "2" ) {
            $this->db->group_by(['cattrv.cat_attribute_val_value_arabic', 'cattr.cat_attribute_name_arabic']);
        } else {
            $this->db->group_by(['cattrv.cat_attribute_val_value', 'cattr.cat_attribute_name']);
        }
        $this->db->order_by('cattrv.cat_attribute_val_id ASC');
        
        return $this->db->get()->result_array();
    }

    public function saveSellerFabricNames( $data, $userId, $category_uid, $price )
    {
        if (! empty($data) ) {
            $this->db->trans_start();

            // Update product price
            if (! empty($category_uid) ) {
                $product = $this->db->select('DISTINCT ON (pattr.product_attribute_id) pattr.product_attribute_id, pattr.product_id, cat.category_uid')
                              ->from('product_attribute pattr')
                              ->join('product p', 'pattr.product_id = p.product_id', 'left')
                              ->join('product_category pcat', 'p.product_id = pcat.product_id', 'left')
                              ->join('category cat', 'pcat.category_id = cat.category_id', 'left')
                              ->where('p.is_kandora', 1)
                              ->where('cat.category_uid', $category_uid)
                              ->where('p.product_vender_id', $userId)
                              ->where('cat.category_language_code', 1)
                              ->get()->row_array();
                
                if (! empty($product) ) {
                    $this->db->update('product', ['product_status' => 1], ['product_id' => $product['product_id']]);
                    $this->db->update('product_attribute', ['regular_price' => $price, 'sale_price' => $price], ['product_attribute_id' => $product['product_attribute_id']]);
                } else {
                    $this->config->load('kandora');
                    $product_templates = $this->config->item('kandora');

                    $sub_categories = $this->db->select('DISTINCT ON (sub_cat.category_id) sub_cat.category_id, sub_cat.category_uid, sub_cat.category_parent_id', TRUE)
                                       ->from('category sub_cat')
                                       ->join('category main_cat', 'sub_cat.category_parent_id = main_cat.category_id', 'inner')
                                       ->where('sub_cat.category_parent_id !=', 0)
                                       ->where('sub_cat.category_uid', $category_uid)
                                       ->get()->result_array();
                                      
                    $main_categories    = array_column($sub_categories, 'category_parent_id');
                    $main_categories    = array_unique(array_filter($main_categories));
                    $sub_categories     = array_column($sub_categories, 'category_id', 'category_uid');

                    $product_data = array_merge([
                        'is_kandora' => 1,
                        'product_type' => 1,
                        'product_vender_id' => $userId,
                        'product_sale_from' => date('Y-m-d'),
                        'product_sale_to' => '2037-12-31',
                        'product_status' => 1,
                        'product_vendor_status' => 1,
                        'product_gender' => 'm',
                        'cash_points' => 0,
                    ], $product_templates[$category_uid]);

                    $this->db->insert('product', $product_data);
                    $product_id = $this->db->insert_id();

                    $product_categories = [];
                    foreach ($main_categories as $t_cat_id) {
                        $product_categories[] = [
                            'product_id' => $product_id,
                            'category_id' => $t_cat_id,
                        ];
                    }
                    $t_cat_id = $sub_categories[$category_uid] ?? 0;
                    if ( $t_cat_id > 0 ) {
                        $product_categories[] = [
                            'product_id' => $product_id,
                            'category_id' => $t_cat_id,
                        ];
                    }
                    $this->db->insert_batch('product_category', $product_categories);

                    $product_attribute = [
                        'product_id' => $product_id,
                        'allow_back_order' => 1,
                        'sold_individually' => 1,
                        'image' => $product_data['product_image'] ?? '',
                        'sale_price' => $price,
                        'regular_price' => $price,
                    ];
                    $this->db->insert('product_attribute', $product_attribute);
                }
            }

            $category_fabric_types  = [];
            $category_fabric_colors = [];
            foreach ($data as $cat_attribute_value_id => $row) {
                $is_new = $row['is_new'] ?? 1;
                $fabric_types = $row['cat_fabric_types'] ?? [];
                $fabric_colors = $row['cat_fabric_colors'] ?? [];
                unset($row['is_new']);
                unset($row['cat_fabric_types']);
                unset($row['cat_fabric_colors']);

                if ( $is_new == 0 ) {
                    $t_action = 'update';
                    if ( $row['cat_attribute_val_status'] == 0 ) {
                        $count = $this->db->get_where('product_order_user_attribute', ['attribute_value_id' => $cat_attribute_value_id])->num_rows();
                        if ( $count == 0 ) {
                            $t_action = 'delete';
                        }
                    }
                    if ( $t_action == 'delete' ) {
                        $this->db->delete('category_attribute_values', ['cat_attribute_val_id' => $cat_attribute_value_id]);
                        $cat_attribute_value_id = 0;
                    } else {
                        $this->db->where('cat_attribute_val_id', $cat_attribute_value_id);
                        $this->db->update('category_attribute_values', $row);
                    }

                    $this->db->delete('category_fabric_type', ['cat_fabric_name_value_id' => $cat_attribute_value_id]);

                    $this->db->delete('category_fabric_color', ['cat_fabric_name_value_id' => $cat_attribute_value_id]);

                } else {
                    $this->db->insert('category_attribute_values', $row);
                    $cat_attribute_value_id = $this->db->insert_id('category_attribute_value_cat_attribute_val_id_seq');
                }

                if ( $cat_attribute_value_id > 0 ) {
                    foreach ($fabric_types as $type_value_id) {
                        $category_fabric_types[] = [
                            'cat_fabric_name_value_id' => $cat_attribute_value_id,
                            'cat_fabric_type_value_id' => $type_value_id,
                        ];
                    }
                    foreach ($fabric_colors as $color_id) {
                        $category_fabric_colors[] = [
                            'cat_fabric_name_value_id' => $cat_attribute_value_id,
                            'cat_fabric_color_id' => $color_id,
                        ];
                    }
                }
            }

            if (! empty($category_fabric_types) ) {
                $this->db->insert_batch('category_fabric_type', $category_fabric_types);
            }
            if (! empty($category_fabric_colors) ) {
                $this->db->insert_batch('category_fabric_color', $category_fabric_colors);
            }

            if ( $this->db->trans_status() === FALSE ) {
                $this->db->trans_rollback();
                return 0;
            } else {
                $this->db->trans_commit();
                return 1;
            }
        }

        return 0;
    }

    public function isFabricNamesConfigured( $store_id )
    {
        $this->db->select("DISTINCT ON (cat.category_uid) cat.category_uid");
        $this->db->from('category_attribute_values cattrv');
        $this->db->join('category_attribute cattr', 'cattrv.cat_attribute_id = cattr.cat_attribute_id', 'left');
        $this->db->join('category cat', 'cattr.category_id = cat.category_id', 'left');        
        $this->db->where('cattr.cat_attribute_type = cattrv.cat_attribute_val_type_id');        
        $this->db->where('cat.category_language_code', 1);
        $this->db->where('cattr.cat_attribute_status', 1);
        $this->db->where('cattr.cat_attribute_is_fabric_name', 1);
        $this->db->where('cattrv.cat_attribute_val_status', 1);
        $this->db->where('cattrv.cat_attribute_val_store_id', $store_id);
                
        $result = $this->db->get()->result_array();
        $result = array_column($result, 'category_uid');
        if ( count($result) == 3 ) {
            return 1;
        }

        return 0;
    }

    public function getRecentSales( $store_id, $days=10 )
    {
        $date = time() - (86400*$days);
        $date = date('Y-m-d', $date);
        $this->db->select('DATE(pod.order_placed_date) AS order_date, COUNT(pod.order_block_id) AS order_count');
        $this->db->from('product_order_details pod');
        $this->db->join('(SELECT DISTINCT order_block_id, product_id FROM product_order_history) poh', 'pod.order_block_id = poh.order_block_id', 'left');
        $this->db->join('product product', 'poh.product_id = product.product_id', 'left');
        $this->db->where('product.product_vender_id', $store_id);
        $this->db->where('product.product_id !=', NULL);
        $this->db->where('DATE(pod.order_placed_date) >=', $date);
        $this->db->group_by(['DATE(pod.order_placed_date)']);
        return $this->db->get()->result();
    }
    
    public function saveDriver($data){
        
        $this->db->select('count(user_email_id) as count');
        $this->db->from('user_table c');
        $this->db->where('user_email_id', $data['txt_email']);
        $query = $this->db->get();
        // echo $this->db->last_query();
        if ($query->row()->count>0) {
            return 3;
            // exit;
        }
        
        $this->db->select('count(user_custom_id) as count');
        $this->db->from('user_table c');
        $this->db->where('user_custom_id', $data['user_custom_id']);
        $query = $this->db->get();
        // echo $this->db->last_query();
        if ($query->row()->count>0) {
            return 4;
            exit;
        }
        
        $inputUserBasic['user_first_name']     =    $data['txt_first_name'];
        $inputUserBasic['user_last_name']      =    $data['txt_last_name'];
        $inputUserBasic['user_email_id']       =    $data['txt_email'];
        $inputUserBasic['user_gender']         =    $data['radio_gender'];
        $inputUserBasic['user_country_id']     =    $data['select_country'];
        $inputUserBasic['user_password']       =    MD5($data['txt_password']);
        $inputUserBasic['user_status']         =    0;
        $inputUserBasic['user_deleted']        =    0;
        $inputUserBasic['user_created_by']     =    'A';
        $inputUserBasic['user_created_date']   =    gmdate("Y-m-d H:i:s");
        $inputUserBasic['user_type']           =    'D';
        $inputUserBasic['user_custom_id']      =   $data['txt_user_id'];
        $inputUserBasic['phone_number']        =   $data['txt_Phone'];
        $inputUserBasic['phone_verified']      =   $data['phone_verified'] ?? 0;
        
        if ( $_FILES["txt_image"]["name"] != "" ) {
            $digits   =  6;
            $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

            $filename = $_FILES["txt_image"]["name"];
            $file_ext = pathinfo($filename, PATHINFO_EXTENSION);

            $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']            =  1024;
            $config1['max_height']           =  1024;
            $config1['file_name']            =  $randomNo.".".$file_ext;

            //$this->load->library('upload', $config2);
            $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 {
                $inputUserBasic['image'] = $config1['file_name'];
            }
        }        
        
        $this->db->trans_start();
        $this->db->insert('user_table', $inputUserBasic);
        $insertId = $this->db->insert_id();
        
        $inputUserShiping['country_id'] =    $data['select_country'];
        $inputUserShiping['city']       =    $data['select_city'];
        $inputUserShiping['mobile_no']  =    $data['dail_code']."-".$data['txt_Phone'];
        $inputUserShiping['vehicle_reg_no'] =    $data['txt_veh_no'];
        
        $inputUserShiping['street_name']     =    $data['txt_street'];
        /*$inputUserShiping['building_no']     =    $data['txt_building'][$i] ?? "";
        $inputUserShiping['latitude']        =    $data['latti'][$i] ?? "";
        $inputUserShiping['longitude']       =    $data['longi'][$i] ?? "";
        $inputUserShiping['land_phone']      =    $data['txt_Land_Phone'][$i] ?? NULL;
        $inputUserShiping['document_number']    =    $data['txt_License'][$i] ?? "";
        $inputUserShiping['vehicle_type_id']   =    $data['vehicle_type'][$i] ?? "";        
        $inputUserShiping['emirates_id_number'] =   $data['txt_emirates_id'][$i] ?? "";*/
        // $inputUserShiping['driver_earning_percentage'] = $data['txt_earning_percentage'][$i] ?? "";

            if ($_FILES["txt_doc"]["name"]!="") {
                $digits   =  6;
                $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

                $filename2 = $_FILES["txt_doc"]["name"];
                $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

                $config2['upload_path']          =  $this->config->item('upload_path').$this->config->item('driver_document_upload_dir');
                $config2['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
                $config2['max_size']             =  1000;                
                $config2['file_name']            =  $randomNo.".".$file_ext2;

                //$this->load->library('upload', $config2);
                $this->load->library('upload', $config2);
                $this->upload->initialize($config2);

                if (! $this->upload->do_upload('txt_doc')) {
                //die("file upload failed");
                    $data['status'] = 0;
                    $data['errors'] = array(
                        'txt_doc' => $this->upload->display_errors('', ''),
                    );
                    echo json_encode($data);
                    exit();
                } else {
                    // $inputUserShiping['document_number']      =    $data['txt_doc_no'][$i];
                    // $inputUserShiping['document_type_id']     =    $data['select_doc_type'][$i] ?? 0;
                    $inputUserShiping['doument_name']         =    $config2['file_name'];
                }
            }

            if ($_FILES["txt_doc2"]["name"]!="") {
                $digits   =  6;
                $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

                $filename2 = $_FILES["txt_doc2"]["name"];
                $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

                $config2['upload_path']          =  $this->config->item('upload_path').'driver_documents/';
                $config2['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
                $config2['max_size']             =  1000;
                $config2['file_name']            =  $randomNo.".".$file_ext2;

                //$this->load->library('upload', $config2);
                $this->load->library('upload', $config2);
                $this->upload->initialize($config2);

                if (! $this->upload->do_upload('txt_doc2')) {
                  //die("file upload failed");
                    $data['status'] = 0;
                    $data['errors'] = array(
                        'txt_doc2' => $this->upload->display_errors('', ''),
                    );
                    echo json_encode($data);
                    exit();
                } else {
                    // $inputUserShiping['document_type_id']   = $data['select_doc_type'][$i]>0?$data['select_doc_type'][$i] : 0;
                    $inputUserShiping['mulkiya']            = $config2['file_name'];
                }
            }

            if ( $_FILES["txt_doc3"]["name"] != "" ) {
                $digits   =  6;
                $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

                $filename3 = $_FILES["txt_doc3"]["name"];
                $file_ext3 = pathinfo($filename3, PATHINFO_EXTENSION);

                $config2['upload_path']          =  $this->config->item('upload_path').'driver_documents/';
                $config2['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
                $config2['max_size']             =  1000;
                $config2['file_name']            =  $randomNo.".".$file_ext3;

                $this->load->library('upload', $config2);
                $this->upload->initialize($config2);

                if (! $this->upload->do_upload('txt_doc3')) {
                    $data['status'] = 0;
                    $data['errors'] = array(
                        'txt_doc3' => $this->upload->display_errors('',''),
                    );
                    echo json_encode($data);
                    exit();
                } else {
                    $inputUserShiping['emirates_id_file'] = $config2['file_name'];
                }
            }

            $inputUserShiping['driver_bank_id']      = $data['driver_bank_id'] ?? "";
            $inputUserShiping['bank_account_number'] = $data['driver_bank_account_number'] ?? "";
            $inputUserShiping['bank_ifsc_code']      = $data['driver_bank_ifsc_code'] ?? "";
            $inputUserShiping['bank_swift_code']     = $data['driver_bank_swift_code'] ?? "";
            $inputUserShiping['vendor_id']           = $this->session->userdata("user_id");
            $inputUserShiping['user_id']             = $insertId;
            
            $this->db->insert('driver_details', $inputUserShiping);
        
        
        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }

    function updateDriver($data)
    {
        $userId                                 =    $data['id'];
        $inputUserBasic['user_first_name']      =    $data['txt_first_name'];
        $inputUserBasic['user_last_name']       =    $data['txt_last_name'];
        $inputUserBasic['user_gender']          =    $data['radio_gender'];
        $inputUserBasic['user_country_id']      =    $data['select_country'];        

        $user_password = $data['txt_password'] ?? '';
        if ( !empty($user_password) ) {
            $inputUserBasic['user_password'] = MD5($user_password);
        }

        if ( $_FILES["txt_image"]["name"] != "" ) {
            $digits   =  6;
            $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

            $filename = $_FILES["txt_image"]["name"];
            $file_ext = pathinfo($filename, PATHINFO_EXTENSION);

            $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']            =  1024;
            // $config1['max_height']           =  1024;
            $config1['file_name']            =  $randomNo.".".$file_ext;

            //$this->load->library('upload', $config2);
            $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 {
                $inputUserBasic['image'] = $config1['file_name'];
            }
        }

        $this->db->trans_start();

        $this->db->where('user_id', $userId);
        $this->db->update('user_table', $inputUserBasic);        

        $inputUserShiping['country_id'] =    $data['select_country'];
        $inputUserShiping['city']       =    $data['select_city'];
        $inputUserShiping['mobile_no']  =    $data['dail_code']."-".$data['txt_Phone'];
        $inputUserShiping['vehicle_reg_no'] = $data['txt_veh_no'];        
        $inputUserShiping['street_name']     = $data['txt_street'];

        if ($_FILES["txt_doc"]["name"]!="") {
            $digits   =  6;
            $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txt_doc"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path']          =  $this->config->item('upload_path').$this->config->item('driver_document_upload_dir');
            $config2['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
            $config2['max_size']             =  1000;
            $config2['file_name']            =  $randomNo.".".$file_ext2;

            //$this->load->library('upload', $config2);
            $this->load->library('upload', $config2);
            $this->upload->initialize($config2);

            if (! $this->upload->do_upload('txt_doc')) {
            //die("file upload failed");
                $data['status'] = 0;
                $data['errors'] = array(
                    'txt_doc' => $this->upload->display_errors('', ''),
                );
                echo json_encode($data);
                exit();
            } else {
                // $inputUserShiping['document_number']      =    $data['txt_doc_no'][$i];
                // $inputUserShiping['document_type_id']     =    $data['select_doc_type'][$i] ?? 0;
                $inputUserShiping['doument_name']         =    $config2['file_name'];
            }
        }

        if ($_FILES["txt_doc2"]["name"]!="") {
            $digits   =  6;
            $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

            $filename2 = $_FILES["txt_doc2"]["name"];
            $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);

            $config2['upload_path']          =  $this->config->item('upload_path').'driver_documents/';
            $config2['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
            $config2['max_size']             =  1000;
            $config2['file_name']            =  $randomNo.".".$file_ext2;

            //$this->load->library('upload', $config2);
            $this->load->library('upload', $config2);
            $this->upload->initialize($config2);

            if (! $this->upload->do_upload('txt_doc2')) {
              //die("file upload failed");
                $data['status'] = 0;
                $data['errors'] = array(
                    'txt_doc2' => $this->upload->display_errors('', ''),
                );
                echo json_encode($data);
                exit();
            } else {
                // $inputUserShiping['document_type_id']   = $data['select_doc_type'][$i]>0?$data['select_doc_type'][$i] : 0;
                $inputUserShiping['mulkiya']            = $config2['file_name'];
            }
        }

        if ( $_FILES["txt_doc3"]["name"] != "" ) 
        {
            $digits    = 6;
            $randomNo  = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

            $filename3 = $_FILES["txt_doc3"]["name"];
            $file_ext3 = pathinfo($filename3, PATHINFO_EXTENSION);

            $config2['upload_path']          =  $this->config->item('upload_path').'driver_documents/';
            $config2['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
            $config2['max_size']             =  1000;
            $config2['file_name']            =  $randomNo.".".$file_ext3;

            $this->load->library('upload', $config2);
            $this->upload->initialize($config2);

            if (! $this->upload->do_upload('txt_doc3')) {
                $data['status'] = 0;
                $data['errors'] = array(
                    'txt_doc3' => $this->upload->display_errors('', ''),
                );
                echo json_encode($data);
                exit();
            } else {
                $inputUserShiping['emirates_id_file'] = $config2['file_name'];
            }
        }

        $inputUserShiping['driver_bank_id']      = $data['driver_bank_id'] ?? "";
        $inputUserShiping['bank_account_number'] = $data['driver_bank_account_number'] ?? "";
        $inputUserShiping['bank_ifsc_code']      = $data['driver_bank_ifsc_code'] ?? "";
        $inputUserShiping['bank_swift_code']     = $data['driver_bank_swift_code'] ?? "";
        
        $this->db->where('user_id', $userId);
        $this->db->update('driver_details', $inputUserShiping);

        $this->db->trans_complete();
        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return 0;
        } else {
            $this->db->trans_commit();
            return 1;
        }
    }
    
    public function getDriverList( array $params=[] )
    {        
        $this->db->select('u.*,d.*');
        $this->db->from('driver_details d');
        $this->db->join('user_table u','u.user_id = d.user_id','left');        
        $this->db->where('d.vendor_id', $this->session->userdata("user_id"));

        if ( isset($params['status']) ) {
            $this->db->where('u.user_status', (int) $params['status']);
        }
        return $this->db->get()->result();
    }

    public function get_user_driver( $driver_id=NULL )
    {
        if ( $driver_id > 0 ) {
            $this->db->where('u.user_id', $driver_id);
        }
        return $this->db->select('*')
                        ->from('user_table u')
                        ->join('driver_details s', 'u.user_id =s.user_id', 'inner')
                        ->where("u.user_type = 'D'")
                        ->order_by('u.user_id', 'desc')
                        ->order_by('u.user_status', 1)
                        ->get()
                        ->result();
    }

    public function get_order_lines( $order_line_id )
    {
        $order_line_id = explode(',', $order_line_id);
        if ( is_array($order_line_id) ) {
            $order_line_id = array_map('trim', $order_line_id);
            $order_line_id = array_map('intval', $order_line_id);
            $order_line_id = array_filter($order_line_id);
        }

        if (! empty($order_line_id) ) {
            if ( is_array($order_line_id) ) {
                $this->db->where_in('history_id', $order_line_id);
            } else {
                $this->db->where('history_id', $order_line_id);
            }
        }

        $this->db->from('product_order_history');
        $this->db->where('picking_id >', 0);
        
        return $this->db->get();
    }
}
