<?php
defined('BASEPATH') or exit('No direct script access allowed');

class C_vendor extends Vendor_Dashboard_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->config('kandora');
        $this->load->model("Common");
        $this->load->model('V_product');
        $this->load->model("webservices/user_model","model_user");
    }

    public function index()
    {
        if ( $this->session->userdata('user_id') !== null) {
            redirect( site_url('vendor/dashboard'), 'refresh' );
        } else {
            redirect( site_url('store'), 'refresh' );
        }
    }

    public function loadVendorLoginForm()
    {
        $this->load->view("vendor/login_form_modal");
    }

    public function vendorLogin()
    {
        // Clear all login sessions
        $this->clearLoginSessions();

        $data = array(
            'user_email_id' => $this->input->post('username'),
            'user_password' => MD5($this->input->post('password')),
            'user_type' => 'V'
        );

        $status     = "0";
        $message    = "0";

        $result = $this->M_vendor->login($data);

        if (count((array)$result) <= 0) {
            $status     = "0";
            $message    = "Wrong Email Address or Password";
        } else {
            if ( $result->verified_status == 0 ) {
                $status     = "0";
                $message    = "Your account is under verification. Please try again later.";
            } elseif ( $result->user_status == 0 ) {
                $status     = "0";
                $message    = "Your account was suspended.";
            } elseif ( $result->user_email_id != "" ) {
                $status     = "1";
                $message    = "Login Success";

                $this->session->set_userdata("admin_email", $result->user_email_id);
                $this->session->set_userdata("user_id", $result->user_id);

                $this->session->set_userdata("admin_name", $result->user_first_name);
                $this->session->set_userdata("user_type", "V");
                $this->session->set_userdata("admin_display_name", $result->user_first_name . " " . $result->user_last_name);
                $this->session->set_userdata("admin_designation", '');

                $this->session->set_userdata("store_detail_id", $result->seller_details_id);
            } else {
                $status     = "0";
                $message    = "Wrong Email Address or Password";
            }
        }

        $this->addData(compact('status', 'message'));
        $this->render('json');
    }

    public function changepasword()
    {
        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("vendor/change_password");
        $this->load->view("vendor/footer");
    }

    public function forgotPassword()
    {
        $data['user_email_id'] = $this->input->post('txt_email', true);

        $this->load->library('form_validation');
        $this->form_validation->set_rules('txt_email', 'Email', 'required|valid_email');

        if ($this->form_validation->run() == FALSE) {
            echo validation_errors();
            exit;
        } else {
            echo   $this->M_vendor->forgotPassword($data);
            exit;
        }
        //  print_r($_POST);
    }


    public function saveChangePassword()
    {
        $this->form_validation->set_rules('txt_old_password', 'Old password', 'required|min_length[8]|max_length[20]');
        $this->form_validation->set_rules('txt_new_password', 'New password', 'required|min_length[8]|max_length[20]');
        $this->form_validation->set_rules('txt_conf_password', 'Confirm password', 'required|min_length[8]|max_length[20]|matches[txt_new_password]');
        if ($this->form_validation->run() == FALSE) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_old_password' => form_error('txt_old_password'),
                'txt_new_password' => form_error('txt_new_password'),
                'txt_conf_password' => form_error('txt_conf_password')
            );
            echo json_encode($data);
            exit();
        }
        $_POST = $this->security->xss_clean($_POST);
        if (count($_POST) > 0) {
            $result         =   $this->M_vendor->saveChangePassword($_POST);
        } else {
            $result = 0;
        }
        $data['status'] = $result;
        echo json_encode($data);
    }

    public function resetPassword()
    {
        $data =   array();
        $userId =   $this->M_product->decryptId($this->uri->segment(3));
        $data['user_id'] =  $userId;

        if ($userId <= 0) {
            $data['error']        =  1;
        } else {
            $session =  $this->M_vendor->checkLinkExpired($userId);

            if (count($session) > 0) {
                $data['error']                =  0;
                $data['session']           =  $session;
            } else {
                $data['error']        =  2;
            }
        }

        $this->load->view("vendor/forgot_password_reset", $data);
    }

    public function saveNewPassword()
    {
        $this->form_validation->set_rules('new_password', 'New password', 'required');
        $this->form_validation->set_rules('confirm_password', 'Confirm password', 'required');
        if ($this->form_validation->run() == FALSE) {
            $data['status'] = 0;
            $data['errors'] = array(

                'new_password' => form_error('new_password'),
                'confirm_password' => form_error('confirm_password')
            );
            echo json_encode($data);
            exit();
        } else {
            $result                =   $this->M_vendor->resetPassword($_POST);
            $data['status']  =  $result;
            echo json_encode($data);
            exit();
        }
    }

    public function logout()
    {
        $this->session->sess_destroy();
        $this->session->unset_userdata('admin_email');
        $this->session->unset_userdata('admin_id');
        $this->session->unset_userdata('admin_name');
        $this->session->unset_userdata('user_type');
        $this->session->unset_userdata('admin_display_name');
        $this->session->unset_userdata('admin_designation');
        $this->session->unset_userdata('user_id');
        redirect("vendor");
    }

    public function logout_user()
    {
        $this->session->sess_destroy();
        $this->session->unset_userdata('admin_email');
        $this->session->unset_userdata('admin_id');
        $this->session->unset_userdata('admin_name');
        $this->session->unset_userdata('user_type');
        $this->session->unset_userdata('admin_display_name');
        $this->session->unset_userdata('admin_designation');
        $this->session->unset_userdata('user_id');
        redirect("vendor");
    }

    public function dashboard()
    {
        $this->validateLogin();
        $this->addMetaTitle('Dashboard');
        $this->addBreadCrumb(
            [current_url(), 'Dashboard']
        );
        $this->setSidebarActiveMenu('dashboard');

        $total_products = $this->M_product->getVendorProductsCount([
            'vendor_id' => $this->vendor_user->user_id,
            // 'is_kandora' => 0,
        ]);
        
        $result = $this->M_product->get_store_details();
        $this->session->set_userdata("store_detail_id", $result->seller_details_id);        
        
        // Sales Chart & Earnings Chart
        $month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
        $current_month = date('n');
        $start_year = date('Y');
        $current_month_days = date('t');
        $list_count = 0;
        $chart_keys = [];
        $chart_labels = [];
        $sales_chart_delivered = [];
        $sales_chart_cancelled = [];
        for ($i = $current_month; $i > 0; $i--) {
            $m = ($i < 10) ? "0{$i}" : $i;
            $chart_keys[] = "{$start_year}-{$m}";
            $chart_labels[] = "'" . $month_names[$i-1] . "'";

            $list_count++;
            if ($list_count > 5) break;
            if ($i == 1) {
                $start_year--;
                $current_month = 13;
                $i = 13;
            }
        }
        $search_condition = [
            'start_date' => $chart_keys[count($chart_keys)-1] . "-01",
            'end_date' => $chart_keys[0] . "-{$current_month_days}",
            'status' => ORDER_STATUS_DELIVERED,
            'store_id' => $this->vendor_user->user_id,
        ];
        $delivered_data = $this->M_admin->getSalesGroupByMonth($search_condition);

        $search_condition['status'] = ORDER_STATUS_CANCEL;
        $cancelled_data = $this->M_admin->getSalesGroupByMonth($search_condition);

        $earnings_chart_vendor = [];
        $earnings_search = $search_condition;
        unset($earnings_search['status']);
        $earnings_data = $this->M_admin->getEarningsGroupByMonth($earnings_search);
        $vendor_commission = array_column($earnings_data, 'vendor_commission', 'order_date');

        $chart_labels = array_reverse($chart_labels);
        $chart_keys = array_reverse($chart_keys, TRUE);
        foreach ($chart_keys as $chart_key) {
            $tmp_delivered = $delivered_data[$chart_key] ?? 0;
            $tmp_cancelled = $cancelled_data[$chart_key] ?? 0;
            $sales_chart_delivered[] = $tmp_delivered;
            $sales_chart_cancelled[] = $tmp_cancelled;

            // Earnings
            $tmp_vendor_commission      = $vendor_commission[$chart_key] ?? 0;
            $earnings_chart_vendor[]    = round($tmp_vendor_commission);
        }

        $sales_chart_labels     = '[' . implode(',', $chart_labels) . ']';
        $sales_chart_delivered  = '[' . implode(',', $sales_chart_delivered) . ']';
        $sales_chart_cancelled  = '[' . implode(',', $sales_chart_cancelled) . ']';

        $earnings_chart_label = '[' . implode(',', $chart_labels) . ']';
        $earnings_chart_vendor = '[' . implode(',', $earnings_chart_vendor) . ']';
        // echo $this->M_product->getOrderCount(ORDER_STATUS_PENDING);exit;

        $services_count = $this->M_product->_get_service_list(['vendor_id'=>$this->vendor_user->user_id])->num_rows();
        $booking_count = $this->V_product->get_service_booking_list($this->vendor_user->user_id)->num_rows();

        $this->addData([
            'order_total_count' => $this->M_product->getOrderCount('') ?? 0,
            'order_pending_count' => $this->M_product->getOrderCount(ORDER_STATUS_PENDING) ?? 0,
            'order_accepted_count' => $this->M_product->getOrderCount(ORDER_STATUS_ACCEPTED) ?? 0,
            'order_ready_count' => $this->M_product->getOrderCount(ORDER_STATUS_READY) ?? 0,
            'order_dispatched_count' => $this->M_product->getOrderCount(ORDER_STATUS_DISPATCHED) ?? 0,
            'order_delivered_count' => $this->M_product->getOrderCount(ORDER_STATUS_DELIVERED) ?? 0,
            'order_cancelled_count' => $this->M_product->getOrderCount(ORDER_STATUS_CANCEL) ?? 0,
            'total_sales' => $this->M_product->getVendorTotalSales($this->vendor_user->user_id) ?? 0.00,
            'total_product' =>  $total_products,
            'footer_section' => 'vendor_dashboard',
            'sales_chart_labels' => $sales_chart_labels,
            'sales_chart_delivered' => $sales_chart_delivered,
            'sales_chart_cancelled' => $sales_chart_cancelled,
            'earnings_chart_label' => $earnings_chart_label,
            'earnings_chart_vendor' => $earnings_chart_vendor,
            'services_count'    =>$services_count,
            'booking_count'     =>$booking_count
        ]);

        $this->addAssets([
            'footer' => [
                'vendor/dashboard_footer_assets',
            ]
        ]);

        $this->render('vendor/dashboard');
    }

    public function reportsAjax($status=0, $page=1)
    {

        ## Read value
        $draw = $this->input->post('draw',true);
        $rowss = $this->input->post('start',true);//$_POST['start'];
        $rowperpage = $this->input->post('length',true);//$_POST['length']; // Rows display per page
        $columnIndex = $this->input->post('order',true)[0]['column']; // Column index
        $columnName = $this->input->post('columns',true)[$columnIndex]['data']; // Column name
        $columnSortOrder = $this->input->post('order',true)[0]['dir']; // asc or desc
        $searchValue = $this->input->post('search',true)['value']; // Search value



        $status = 0;

        $status = ( !$status ) ? -1 : $status-1;
        $page =1;//( !$draw || $draw < 0 ) ? 1 : $draw;
        $limit = $rowperpage ;

        $offset = $rowss;
        $order_start_date =  $this->input->post('search_start_date');
        if (! empty($order_start_date) ) {
            $start_date = explode("-",$order_start_date);

            $order_start_date = $start_date[2]."-".$start_date[1]."-".$start_date[0];
        }
        $order_end_date =  $this->input->post('search_end_date');
        if (! empty($order_end_date) ) {
            $end_date = explode("-",$order_end_date);
            $order_end_date =$end_date[2]."-".$end_date[1]."-".$end_date[0];
        }
        $search_params = [
            'vendor_id' => $this->vendor_user->user_id,
            'search_key' => $searchValue,
            'order_start_date' => $order_start_date,
            'order_end_date' => $order_end_date,
            'order_status' => $this->input->post('search_order_status', true),
        ];
        $order_count = $this->M_product->getVendorOrderHistoryCount($search_params);
        if ( $order_count > 0 ) {
            $order_list = $this->M_product->getVendorOrderHistoryWithProducts($search_params, $limit, $offset);
        } else {
            $order_list = [];
        }
        $data = array();
        $prod_image = "";
        $imgs = "";
     foreach($order_list as $t_row ){
        $t_statuses = [
            0 => 'Pending',
            1 => 'Dispatched',
            2 => 'Delivered',
            3 => 'Cancelled',
        ];
        $t_order_status = array_key_exists($t_row->deliver_status, $t_statuses) ? $t_statuses[$t_row->deliver_status] : "";
        $t_order_datetime = get_date_in_timezone('Asia/Dubai', $t_row->order_placed_date, 'd-F-Y/g:i A');
        list($t_order_date, $t_order_time) = explode('/', $t_order_datetime);
        $t_address_line1 = [$t_row->user_shiping_details_building, $t_row->user_shiping_details_street, $t_row->user_shiping_details_loc];
        $t_address_line1 = implode(', ', array_filter($t_address_line1));

        $prod_image = $t_row->product_image;
        if(!empty($prod_image)){
            $img2 = explode(",",$prod_image);
            // $imgs  = "<img src=".base_url()."uploads/vender_images/".$img2[0]." style='width:50px;height:50px;'>";
            $imgs = "<img src=".base_url()."assets_v2/images/placeholder.png"." style='width:50px;height:50px;'>";
        }else{
            $imgs = "<img src=".base_url()."assets_v2/images/placeholder.png"." style='width:50px;height:50px;'>";
        }

        $data[] = array(
           "order_placed_date"=> get_date_in_timezone('Asia/Dubai', $t_row->order_placed_date, 'd-F-Y/g:i A'),
           "order_no"=>$t_row->order_no,
           "product_image"=>$imgs,
           "product_name"=>$t_row->product_name,
           "quantity"=>$t_row->purchase_qty,
           "address"=>$t_row->user_first_name.' '.$t_row->user_last_name.'<br>'.$t_address_line1.'<br>'. $t_row->city_name.' ,'.$t_row->country_name ,
           "order_status"=>$t_order_status,
           "discount_price"=>$t_row->discount_price,
           "vat"=>$t_row->vat_price,
           "order_grand_total"=>$t_row->currency_code.' '.number_format($t_row->total_price, 2, ".", ",")
        );
     }
        $response = array(
            "draw" => intval($draw),
            "iTotalRecords" => $order_count,
            "iTotalDisplayRecords" => $order_count,
            "aaData" => $data,
            "order_end_date"=>$this->input->post('search_end_date')
          );
        echo json_encode($response);

    }

    public function reportsOld( $status=0, $page=1 )
    {
        $status = ( !$status ) ? -1 : $status-1;
        $page = ( !$page || $page < 0 ) ? 1 : $page;
        $limit = $this->input->post('search_limit', true) ?? 10;

        $this->addData([
            'footer_section' => 'order_listing',
            'status_list' => [
                [0, 'Pending'],
                [1, 'Dispatched'],
                [2, 'Delivered'],
                [3, 'Cancelled'],
            ],
            'status' => $status+1,
            'page' => $page,
            'limit' => $limit,
        ]);

        // Handle non-ajax request
        if (! $this->input->is_ajax_request() ) {
            $this->validateLogin();
            $this->addMetaTitle('Reports');
            $this->addBreadCrumb(
                [current_url(), 'Reports']
            );
            $this->setSidebarActiveMenu('reports');
            $this->addAssets([
                'header' => [
                    'vendor/reports_header_assets',
                ],
                'footer' => [
                    'vendor/reports_footer_assets',
                ]
            ]);

            $this->render('vendor/reports');

        // Handle ajax request
        } else {
            $order_start_date = $this->input->post('search_start_date', true);
            if (! empty($order_start_date) ) {
                $order_start_date = date('Y/m/d', strtotime($order_start_date));
            }
            $order_end_date = $this->input->post('search_end_date', true);
            if (! empty($order_end_date) ) {
                $order_end_date = date('Y/m/d', strtotime($order_end_date));
            }
            $search_params = [
                'vendor_id' => $this->vendor_user->user_id,
                'search_key' => $this->input->post('search_key', true),
                'order_start_date' => $order_start_date,
                'order_end_date' => $order_end_date,
                'order_status' => $this->input->post('search_order_status', true),
            ];
            $offset = ($page - 1) * $limit;

            $order_count = $this->M_product->getVendorOrderHistoryCount($search_params);
            if ( $order_count > 0 ) {
                $order_list = $this->M_product->getVendorOrderHistory($search_params, $limit, $offset);
            } else {
                $order_list = [];
            }

            $data = compact('order_count', 'order_list', 'limit');

            // Pagination Starts
            // $this->load->library('pagination');

            // $config['base_url'] = current_url();
            // $config['total_rows'] = $order_count;
            // $config['per_page'] = $limit;
            // $config['num_links'] = 3;
            // $config["uri_segment"] = 4;
            // $config['use_page_numbers'] = true;
            // $config['reuse_query_string'] = true;
            // $config['attributes'] = ['class' => 'page-link'];

            // $config['full_tag_open'] = '<ul class="pagination">';
            // $config['full_tag_close'] = '</ul>';

            // $config['first_link'] = $this->lang->line('first');
            // $config['first_tag_open'] = '<li class="page-item">';
            // $config['first_tag_close'] = '</li>';

            // $config['last_link'] = $this->lang->line('last');
            // $config['last_tag_open'] = '<li class="page-item">';
            // $config['last_tag_close'] = '</li>';

            // $config['next_link'] = '&gt;';
            // $config['next_tag_open'] = '<li class="page-item">';
            // $config['next_tag_close'] = '</li>';

            // $config['prev_link'] = '&lt;';
            // $config['prev_tag_open'] = '<li class="page-item">';
            // $config['prev_tag_close'] = '</li>';

            // $config['cur_tag_open'] = '<li class="page-item active"><span class="page-link">';
            // $config['cur_tag_close'] = '</span></li>';

            // $config['num_tag_open'] = '<li class="page-item">';
            // $config['num_tag_close'] = '</li>';

            // $this->pagination->initialize($config);

            // $data["pagination_links"] = $this->pagination->create_links();
            // Pagination Ends

            $this->addData([
                'order_count' => $data['order_count'],
                'html' => $this->load->view('vendor/report_list', $data, true),
                'search_params' => $search_params,
            ]);

            $this->render('json');
        }
    }

    public function reports( $status=null, $page=null )
    {
        $status = ( !$status ) ? -1 : $status-1;
        $page = ( !$page || $page < 0 ) ? 1 : $page;
        $limit = $this->input->post('search_limit', true) ?? 10;
        $offset = ($page - 1) * $limit;

        $order_delivery_statuses = $this->config->item('order_delivery_statuses', 'app');
        $status_list = [];
        foreach ($order_delivery_statuses as $status_key => $status_label) {
            $status_list[] = [$status_key, $status_label[$this->lang_code]];
        }

        $this->addData([
            'status_list' => $status_list,
            'status' => $status+1,
            'page' => $page,
            'limit' => $limit,
        ]);

        // Handle non-ajax request
        if (! $this->input->is_ajax_request() ) {
            $this->validateLogin();
            $this->addMetaTitle('Reports');
            $this->addBreadCrumb(
                [current_url(), 'Reports']
            );
            $this->setSidebarActiveMenu('reports');
            $this->addAssets([
                'header' => [
                    'vendor/order_report_header_assets',
                ],
                'footer' => [
                    'vendor/order_report_footer_assets',
                ]
            ]);

            $this->render('vendor/order_report');

        // Handle ajax request
        } else {
            $order_start_date = $this->input->post('search_start_date', true);
            if (! empty($order_start_date) ) {
                list($t_day, $t_month, $t_year) = explode('/', $order_start_date);
                $order_start_date = date('Y/m/d', mktime(0, 0, 0, $t_month, $t_day, $t_year));
            }
            $order_end_date = $this->input->post('search_end_date', true);
            if (! empty($order_end_date) ) {
                list($t_day, $t_month, $t_year) = explode('/', $order_end_date);
                $order_end_date = date('Y/m/d', mktime(0, 0, 0, $t_month, $t_day, $t_year));
            }
            $search_params = [
                'vendor_id' => $this->vendor_user->user_id,
                'order_start_date' => $order_start_date,
                'order_end_date' => $order_end_date,
                'order_status' => $this->input->post('search_order_status', true),
            ];

            $data['order_list'] = $this->M_vendor->getSalesHistory($search_params, NULL, NULL);

            $data['page'] = $page;
            $data['limit'] = $limit;
            $this->data['html'] = $this->load->view('vendor/order_report_accordion', $data, TRUE);
            $this->render('json');
        }
    }

    public function bookingList( $status=0, $page=1 )
    {
        $status = ( !$status ) ? -1 : $status-1;
        $page = ( !$page || $page < 0 ) ? 1 : $page;
        $limit = $this->input->post('search_limit', true) ?? 10;

        $order_delivery_statuses = $this->config->item('order_delivery_statuses', 'app');
        $status_list = [];
        foreach ($order_delivery_statuses as $status_key => $status_label) {
            $status_list[] = [$status_key, $status_label[$this->lang_code]];
        }
        $status_list = [
            [0, 'Pending'],
            [1, 'Accepted'],
            [4, 'Completed'],
            [10, 'Cancelled']
        ];
        $this->addData([
            'footer_section' => 'booking_listing',
            'status_list' => $status_list,
            'status' => $status+1,
            'page' => $page,
            'limit' => $limit,
        ]);

        // Handle non-ajax request
        if (! $this->input->is_ajax_request() ) {

            $this->validateLogin();
            $this->addMetaTitle('My Bookings');
            $this->addBreadCrumb(
                [current_url(), 'My Bookings']
            );
            $this->setSidebarActiveMenu('booking_history');
            $this->addAssets([
                'header' => [
                    'vendor/booking_history_header_assets',
                ],
                'footer' => [
                    'vendor/booking_history_footer_assets',
                ]
            ]);

            $this->render('vendor/booking_history');

        // Handle ajax request
        } else {
    
            $order_start_date = $this->input->post('search_start_date', true);
            if (! empty($order_start_date) ) {
                list($t_day, $t_month, $t_year) = explode('/', $order_start_date);
                $order_start_date = date('Y/m/d', mktime(0, 0, 0, $t_month, $t_day, $t_year));
            }
            $order_end_date = $this->input->post('search_end_date', true);
            if (! empty($order_end_date) ) {
                list($t_day, $t_month, $t_year) = explode('/', $order_end_date);
                $order_end_date = date('Y/m/d', mktime(0, 0, 0, $t_month, $t_day, $t_year));
            }
            $search_params = [
                'vendor_id' => $this->vendor_user->user_id,
                'search_key' => $this->input->post('search_key', true),
                'order_start_date' => $order_start_date,
                'order_end_date' => $order_end_date,
                'order_status' => $this->input->post('search_order_status', true),
            ];
            $offset = ($page - 1) * $limit;

            $order_count = $this->V_product->get_service_booking_list($this->vendor_user->user_id,$search_params,$lang=1)->num_rows();

            if ( $order_count > 0 ) {
                $order_list = $this->V_product->get_service_booking_list($this->vendor_user->user_id,$search_params,$lang=1, $limit, $offset)->result();
            } else {
                $order_list = [];
            }
            $data = compact('order_count', 'order_list', 'limit');

            // Pagination Starts
            $this->load->library('pagination');

            $config['base_url'] = current_url();
            $config['total_rows'] = $order_count;
            $config['per_page'] = $limit;
            $config['num_links'] = 3;
            $config["uri_segment"] = 4;
            $config['use_page_numbers'] = true;
            $config['reuse_query_string'] = true;
            $config['attributes'] = ['class' => 'page-link'];

            $config['full_tag_open'] = '<ul class="pagination">';
            $config['full_tag_close'] = '</ul>';

            $config['first_link'] = $this->lang->line('first');
            $config['first_tag_open'] = '<li class="page-item">';
            $config['first_tag_close'] = '</li>';

            $config['last_link'] = $this->lang->line('last');
            $config['last_tag_open'] = '<li class="page-item">';
            $config['last_tag_close'] = '</li>';

            $config['next_link'] = '&gt;';
            $config['next_tag_open'] = '<li class="page-item">';
            $config['next_tag_close'] = '</li>';

            $config['prev_link'] = '&lt;';
            $config['prev_tag_open'] = '<li class="page-item">';
            $config['prev_tag_close'] = '</li>';

            $config['cur_tag_open'] = '<li class="page-item active"><span class="page-link">';
            $config['cur_tag_close'] = '</span></li>';

            $config['num_tag_open'] = '<li class="page-item">';
            $config['num_tag_close'] = '</li>';

            $this->pagination->initialize($config);

            $data["pagination_links"] = $this->pagination->create_links();
            // Pagination Ends

            $this->addData([
                'order_count' => $data['order_count'],
                'html' => $this->load->view('vendor/booking_list', $data, true),
            ]);
            $this->render('json');
        }
    }

    public function orderList( $status=0, $page=1 )
    {
        $status = ( !$status ) ? -1 : $status-1;
        $page = ( !$page || $page < 0 ) ? 1 : $page;
        $limit = $this->input->post('search_limit', true) ?? 10;

        $order_delivery_statuses = $this->config->item('order_delivery_statuses', 'app');
        $status_list = [];
        foreach ($order_delivery_statuses as $status_key => $status_label) {
            $status_list[] = [$status_key, $status_label[$this->lang_code]];
        }
        $this->addData([
            'footer_section' => 'order_listing',
            'status_list' => $status_list,
            'status' => $status+1,
            'page' => $page,
            'limit' => $limit,
        ]);

        // Handle non-ajax request
        if (! $this->input->is_ajax_request() ) {

            $this->validateLogin();
            $this->addMetaTitle('My Orders');
            $this->addBreadCrumb(
                [current_url(), 'My Orders']
            );
            $this->setSidebarActiveMenu('my_orders');
            $this->addAssets([
                'header' => [
                    'vendor/my_orders_header_assets',
                ],
                'footer' => [
                    'vendor/my_orders_footer_assets',
                ]
            ]);

            $this->render('vendor/my_orders');

        // Handle ajax request
        } else {
    
            $order_start_date = $this->input->post('search_start_date', true);
            if (! empty($order_start_date) ) {
                list($t_day, $t_month, $t_year) = explode('/', $order_start_date);
                $order_start_date = date('Y/m/d', mktime(0, 0, 0, $t_month, $t_day, $t_year));
            }
            $order_end_date = $this->input->post('search_end_date', true);
            if (! empty($order_end_date) ) {
                list($t_day, $t_month, $t_year) = explode('/', $order_end_date);
                $order_end_date = date('Y/m/d', mktime(0, 0, 0, $t_month, $t_day, $t_year));
            }
            $search_params = [
                'vendor_id' => $this->vendor_user->user_id,
                'search_key' => $this->input->post('search_key', true),
                'order_start_date' => $order_start_date,
                'order_end_date' => $order_end_date,
                'order_status' => $this->input->post('search_order_status', true),
            ];
            $offset = ($page - 1) * $limit;

            $order_count = $this->V_product->getVendorOrderHistoryCount($search_params);
            if ( $order_count > 0 ) {
                $order_list = $this->V_product->getVendorOrderHistory($search_params, $limit, $offset);
            } else {
                $order_list = [];
            }

            $data = compact('order_count', 'order_list', 'limit');

            // Pagination Starts
            $this->load->library('pagination');

            $config['base_url'] = current_url();
            $config['total_rows'] = $order_count;
            $config['per_page'] = $limit;
            $config['num_links'] = 3;
            $config["uri_segment"] = 4;
            $config['use_page_numbers'] = true;
            $config['reuse_query_string'] = true;
            $config['attributes'] = ['class' => 'page-link'];

            $config['full_tag_open'] = '<ul class="pagination">';
            $config['full_tag_close'] = '</ul>';

            $config['first_link'] = $this->lang->line('first');
            $config['first_tag_open'] = '<li class="page-item">';
            $config['first_tag_close'] = '</li>';

            $config['last_link'] = $this->lang->line('last');
            $config['last_tag_open'] = '<li class="page-item">';
            $config['last_tag_close'] = '</li>';

            $config['next_link'] = '&gt;';
            $config['next_tag_open'] = '<li class="page-item">';
            $config['next_tag_close'] = '</li>';

            $config['prev_link'] = '&lt;';
            $config['prev_tag_open'] = '<li class="page-item">';
            $config['prev_tag_close'] = '</li>';

            $config['cur_tag_open'] = '<li class="page-item active"><span class="page-link">';
            $config['cur_tag_close'] = '</span></li>';

            $config['num_tag_open'] = '<li class="page-item">';
            $config['num_tag_close'] = '</li>';

            $this->pagination->initialize($config);

            $data["pagination_links"] = $this->pagination->create_links();
            // Pagination Ends

            $this->addData([
                'order_count' => $data['order_count'],
                'html' => $this->load->view('vendor/my_orders_list', $data, true),
            ]);
            $this->render('json');
        }
    }

    public function orderDetails( $encrypted_id=null,$type=FALSE )
    {
        $this->validateLogin();

        if (! $encrypted_id ) {
            redirect( site_url('vendor/my_orders'), 'refresh' );
        }
        $order_block_id = $this->M_product->decryptId($encrypted_id);
        $order_record = $this->V_product->getVendorOrder($this->vendor_user->user_id,$order_block_id,$this->lang_code,$type);
        if ( empty($order_record) ) {
            show_404();
        }

        $this->addMetaTitle('My Orders | #'. $order_record->order_no."-".$order_record->history_id);
        $this->addBreadCrumb([
            [site_url("vendor/my_orders"), 'My Orders'],
            //[current_url(), 'Order #'. $order_record->order_no."-".$order_record->history_id],
            [current_url(), 'Order #'. $order_record->order_no],
        ]);
        //$this->setSidebarActiveMenu('my_orders');

        //$order_record->products = $this->V_product->getVendorOrderProducts($order_block_id, $this->vendor_user->user_id);
        $order_record->product_count = count($order_record->products);

        $product_vendor_ids = [];

        $total_ship_charge = 0;

        foreach ($order_record->products as $k => $product) {
            $product_images = explode(",", $product->image);
            $product_image  = (count($product_images) > 0) ? $product_images[0] : $product->image;

            if ( file_exists("uploads/products/". $product_image) && is_file("uploads/products/". $product_image) ) {
                $order_record->products[$k]->image = base_url()."uploads/products/". $product_image;
            } else {
                $order_record->products[$k]->image = base_url()."uploads/products/dummy.png";
            }

            if (! in_array($product->product_vender_id, $product_vendor_ids) ){
               $product_vendor_ids[] = $product->product_vender_id;
               $total_ship_charge = $total_ship_charge + $product->product_total_shipping_charge;
            }
        }
        foreach ($order_record->services as $k => $service) {
            $order_record->services[$k]->service_image = get_image("services",$service->service_image);
        }
        //printr($order_record);
        $order_record->order_shipping_charge_total = $total_ship_charge;

        $order_record->issues_reported = $this->M_admin->getOrderIssuesReported($order_record->history_id, ['pod_issue.store_id' => $this->vendor_user->user_id]);

        $this->addData([
            'footer_section' => 'order_detail',
            'order_record' => $order_record
        ]);
        $this->addAssets([
            'header' => [
                'vendor/my_orders_header_assets',
            ],
            'footer' => [
                'vendor/my_orders_footer_assets',
            ]
        ]);
        $this->render('vendor/order_details');
    }

    public function loadOrderDeliveryStatus()
    {
        $this->validateLogin();

        if (! $this->input->is_ajax_request() ) {
            show_404();
        }

        $history_id = (int) $this->input->post('order_id', true);

        $order = $this->V_product->getVendorOrderById($history_id, $this->vendor_user->user_id);
        if ( $order ) {
            $status = '1';
            $message = '';
            $status_history = $this->V_product->getOrderDeliveryStatusHistory($history_id, $this->vendor_user->user_id);
            $this->data['modal'] = $this->load->view('vendor/order_delivery_status_modal', compact('order', 'status_history'), TRUE);

        } else {
            $status     = '0';
            $message    = 'Order Not Found';
        }

        $this->addData(compact('status', 'message'));
        $this->render('json');
    }

    public function changeOrderDeliveryStatus()
    {
        $this->validateLogin();

        $params = [
            'deliverydate' => $this->input->post('delivery_date', true),
            'product_attribute_id' => $this->input->post('product_attribute_id', true),
            'blockId' => $this->input->post('order_block_id', true),
            'txt_status' => $this->input->post('order_status', true),
            'txt_delivery_note' => $this->input->post('delivery_note', true),
        ];
        $this->addData([
            'status' => $this->M_product->changeDeliveryStatus($params),
            'delivery_status' => $params['txt_status'],
        ]);
        $this->render('json');
    }

    public function loadProductAttributeValues()
    {
        $this->validateLogin();

        $mode = $this->input->post('mode', true);
        $orderId = $this->input->post('oid', true);
        $productVariantId = $this->input->post('pid', true);

        if (! empty($orderId) && !empty($productVariantId) ) {
            $products = $this->M_product->getVendorOrderProducts($orderId, $this->vendor_user->user_id);
            $product = [];
            foreach ( $products as $row ) {
                if ( $row->product_variant_id == $productVariantId ) {
                    $product = $row;
                    break;
                }
            }
            if (! empty($product) ) {
                $this->addData(compact('mode', 'product'));
                echo $this->load->view('vendor/order_detail_modal', $this->data, true);
            }
        }
    }

    public function orderAccept()
    {
        $this->validateLogin();

        $status = "0";
        $message = "";

        $history_id = $this->input->post('oid', true);
        $method  = $this->input->post("method");
        if($method == "service_order_accept"){
            if (! empty($history_id) ) { 
                    $is_done = $this->M_vendor->setVendorServiceAccepted($this->vendor_user->user_id, $history_id);
                    if ( $is_done ) {
                        $status = '1';
                        $message = 'Booking has been accepted.';

                        $this->send_service_notification_user($order, ORDER_STATUS_ACCEPTED);

                    } else {
                        $status = '0';
                        $message = 'Unable to accept the booking. Please try again.';
                    }
            }
        }else{

            if (! empty($history_id) ) {
                $order = $this->V_product->getVendorOrderById($history_id, $this->vendor_user->user_id);
                if ( $order ) {
                    $is_done = $this->M_vendor->acceptVendorOrder($this->vendor_user->user_id, $history_id, $order->order_block_id);
                    if ( $is_done ) {
                        $status = '1';
                        $message = 'Order has been accepted.';

                        $this->send_notification_user($order, ORDER_STATUS_ACCEPTED);

                    } else {
                        $status = '0';
                        $message = 'Unable to accept the order. Please try again.';
                    }
                } else {
                    $message = 'Order Not Found.';
                }
            }
        }

        $this->addData(compact('status', 'message'));
        $this->render('json');
    }
    

    public function orderReadyToDeliver()
    {
        $this->validateLogin();

        $status = "0";
        $message = "";

        $order_id       = (int) $this->input->post('oid', true);
        $order_line_id  = $this->input->post('order_line_id', true);
        $driver_id      = $this->input->post('driver_id', true);
        
        $order = $this->V_product->getVendorOrderByOrderId($order_id, $this->vendor_user->user_id);
        if ( $order ) {
            if ( empty($driver_id) ) {
                $message = 'Missing Driver. You have to select a driver to proceed.';
            } else {
                $is_done = $this->M_vendor->setVendorOrderReadyForDelivery($this->vendor_user->user_id, $order_line_id, $order->order_block_id, NULL, $driver_id);
                if ( $is_done ) {

                    $this->send_notification_user($order, ORDER_STATUS_READY);
                    $this->send_notification_drivers($order, $order_line_id);

                    $status     = '1';
                    $message    = 'Your order is ready for delivery.';
                } else {
                    $message    = 'Unable to process the order. Please try again.';
                }
            }
        } else {
            $message = 'Order Not Found.';
        }

        $this->addData(compact('status', 'message'));
        $this->render('json');
    }

    public function orderStartJourney()
    {
        $this->validateLogin();

        $status = "0";
        $message = "";

        $history_id = $this->input->post('oid', true);

        if (! empty($history_id) ) {
            $order = $this->V_product->getVendorOrderById($history_id, $this->vendor_user->user_id);
            if ( $order ) {
                if ( $order->deliver_status == ORDER_STATUS_READY ) {
                    $is_done = $this->M_vendor->setVendorOrderStartJourney($this->vendor_user->user_id, $history_id,$order->order_block_id);
                    if ( $is_done ) {

                        $this->send_notification_user($order,ORDER_STATUS_DISPATCHED);

                        $status     = '1';
                        $message    = 'Order is picked up for delivery.';
                    } else {
                        $message    = 'Unable to process the order. Please try again.';
                    }
                } else {                    
                    if ( $order->deliver_status == ORDER_STATUS_PENDING ) {
                        $message = 'Order is not accepted yet.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_ACCEPTED ) {
                        $message = 'Order is not ready for delivery.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_DISPATCHED ) {
                        $message = 'Order is already picked up for delivery.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_DELIVERED ) {
                        $message = 'Order is already delivered.';
                    } elseif ( $order->deliver_status == ORDER_STATUS_CANCEL ) {
                        $message = 'Order is already cancelled.';
                    } else {
                        $message = 'Unable to process the order. Please try again.';
                    }
                }
            } else {
                $message = 'Order Not Found.';
            }
        }

        $this->addData(compact('status', 'message'));
        $this->render('json');
    }

    public function orderDeliver()
    {
        $this->validateLogin();

        $status = "0";
        $message = "";

        $history_id = $this->input->post('oid', true);
        $method  = $this->input->post("method");
        if($method == "service_order_deliver"){
            $is_done = $this->M_vendor->completeBooking($this->vendor_user->user_id, $history_id);
            if ( $is_done ) {
                $status = '1';
                $message = 'Booking has been completed.';

                $this->send_service_notification_user($order, ORDER_STATUS_DELIVERED);

            } else {
                $status = '0';
                $message = 'Unable to complete the booking. Please try again.';
            }
        }else{ 

            if (! empty($history_id) ) {
                $order = $this->V_product->getVendorOrderById($history_id,$this->vendor_user->user_id);
                if ( $order ) { 
                    if ( $order->deliver_status == ORDER_STATUS_ACCEPTED ) {
                        $is_done = $this->M_vendor->setVendorOrderDelivered($this->vendor_user->user_id, $history_id,$order->order_block_id);
                        if ( $is_done ) {

                           $this->send_notification_user($order,ORDER_STATUS_DELIVERED); 

                            $status     = '1';
                            $message    = 'You\'ve delivered the order.';
                        } else {
                            $message    = 'Unable to deliver the order. Please try again.';
                        }
                    } else {                    
                        if ( $order->deliver_status == ORDER_STATUS_PENDING ) {
                            $message = 'Order is not accepted yet.';
                        } 
                        // elseif ( $order->deliver_status == ORDER_STATUS_ACCEPTED ) {
                        //     $message = 'Order is not ready for delivery.';
                        // } 
                        elseif ( $order->deliver_status == ORDER_STATUS_READY ) {
                            $message = 'Order is not picked up for delivery.';
                        } elseif ( $order->deliver_status == ORDER_STATUS_DELIVERED ) {
                            $message = 'Order is already delivered.';
                        } elseif ( $order->deliver_status == ORDER_STATUS_CANCEL ) {
                            $message = 'Order is already cancelled.';
                        } else {
                            $message = 'Unable to process the order. Please try again.';
                        }
                    }
                } else {
                    $message = 'Order Not Found.';
                }
            }
        }
        $this->addData(compact('status', 'message'));
        $this->render('json');
    }

    public function orderCancel()
    {
        $this->validateLogin();

        $status = "1";
        $message = "";

        $history_id = $this->input->post('oid', true);
        $method  = $this->input->post("method");
        if($method == "service_order_cancel"){
            $is_done = $this->M_vendor->cancelVendorBooking($this->vendor_user->user_id, $history_id);
            if ( $is_done ) {
                $status = '1';
                $message = 'Booking has been cancelled.';

                $this->send_service_notification_user($order, ORDER_STATUS_CANCEL);

            } else {
                $status = '0';
                $message = 'Unable to cancel the booking. Please try again.';
            }
        }else{ 
            if (! empty($history_id) ) {
                $order = $this->V_product->getVendorOrderById($history_id, $this->vendor_user->user_id);
                if ( $order ) {
                    if ( $order->deliver_status == ORDER_STATUS_PENDING ) {
                        $is_done = $this->M_vendor->cancelVendorOrder($this->vendor_user->user_id, $history_id,$order->order_block_id);

                        if ( $is_done ) {
                            $status = '1';
                            $message = 'Order has been rejected.';

                            $this->send_notification_user($order, ORDER_STATUS_CANCEL);

                        } else {
                            $status = '0';
                            $message = 'Unable to reject the order. Please try again.';
                        }
                    } else {
                        $status = '0';
                        if ( $order->deliver_status == ORDER_STATUS_ACCEPTED ) {
                            $message = 'Order is already accepted.';
                        } elseif ( $order->deliver_status == ORDER_STATUS_READY ) {
                            $message = 'Order is already ready to deliver.';
                        } elseif ( $order->deliver_status == ORDER_STATUS_DISPATCHED ) {
                            $message = 'Order is already dispatched.';
                        } else if ( $order->deliver_status == ORDER_STATUS_DELIVERED ) {
                            $message = 'Order is already delivered.';
                        } else if ( $order->deliver_status == ORDER_STATUS_CANCEL ) {
                            $message = 'Order is already rejected.';
                        } else {
                            $message = 'Unable to cancel the order. Please try again.';
                        }
                    }
                } else {
                    $message = 'Order Not Found.';
                }
            }
        }
        $this->addData(compact('status', 'message'));
        $this->render('json');
    }

    public function send_notification_drivers( $order, $order_line_id )
    {
        if ( $order && !empty($order_line_id) ) {
            $order_line = $this->M_vendor->get_order_lines($order_line_id)->row();
            
            $driver_id = 0;
            $picking_id = "";
            if (! empty($order_line) ) {
                $driver_id = $order_line->driver_id;
                $picking_id = $order_line->picking_id;
            }

            $driver_users = $this->M_vendor->get_user_driver($driver_id);
            if ( $driver_users ) {
                $this->load->library("FCM_Notification");

                $device_tokens = [];
                foreach ( $driver_users as $temp_user ) {
                    $notification_id = time();

                    $title              = "New Order Received";
                    $description        = "You have received a new order!";
                    $ntype              = "order-received";

                    if ( !empty($temp_user->firebase_user_key) ) {
                        $notification_data["Notifications/".$temp_user->firebase_user_key."/".$notification_id] = [
                            "title" => $title,
                            "description" => $description,
                            "notificationType" => $ntype,
                            "createdAt" => gmdate("d-m-Y H:i:s", $notification_id),
                            "orderID" => (string) $order->order_block_id,
                            "pickingID" => (string) $picking_id,
                            "url" => (string) $this->vendor_user->user_id,
                            "imageURL" => "",
                            "read" => "0",
                            "seen" => "0"
                        ];

                        $fb_database = get_firebase_refrence();
                        $fb_database->getReference()->update($notification_data);
                    }

                    if (! empty($temp_user->user_device_token) ) {
                        $device_tokens[] = $temp_user->user_device_token;
                    }
                }
                if (! empty($device_tokens) ) {
                    $device_token_chunk = array_chunk($device_tokens, 1000);
                    foreach( $device_token_chunk as $token_chunk ) {
                        $this->fcm_notification->send_multicast_notification($token_chunk,
                            [
                                "title" => $title,
                                "body" => $description,
                                "icon"=> 'myicon',
                                "sound" => 'default',
                                "url" => (string) $this->vendor_user->user_id,
                                "click_action" => "Driver"
                            ],
                            [
                                "type" => $ntype,
                                "notificationID" => $notification_id,
                                "orderID" => (string) $order->order_block_id,
                                "pickingID" => (string) $picking_id,
                                "url" => (string) $this->vendor_user->user_id,
                                "imageURL" => ""
                            ]
                        );
                    }
                }
            }
        }
    }

    public function send_notification_user( $order, $order_status=NULL )
    {
        $msg='';
        if ( $order ) {
            $get_order_data=$this->V_product->getVendorOrderById2($order->history_id,$this->vendor_user->user_id);
            //echo "<pre>hre"; var_dump($get_order_data); echo "</pre>"; exit();
            $user = $this->M_vendor->getUserById($order->user_id);
            
            $seller_user = $this->M_vendor->getSellerByUserId($this->vendor_user->user_id);
            if ( $user && $seller_user ) {
                $this->load->library("FCM_Notification");

                $notification_id    = time();
                $ntype              = "";
                $msg_title = "";
                if ( $order_status == ORDER_STATUS_ACCEPTED ) {
                    $ntype              = "order-accepted";
                   $msg_title = $title              = "Order Accepted";
                    
                    $msg = "Hi {$user->user_first_name}, your purchase order #{$order->order_no} has been accepted by {$seller_user->store_name}.";
                    $description        = "Hi {$user->user_first_name}, your purchase order #{$order->order_no} has been accepted by {$seller_user->store_name}.";
                } elseif ( $order_status == ORDER_STATUS_CANCEL ) {
                    $ntype              = "order-cancel";
                    $msg_title =$title              = "Order Rejected";
                    $description        = "Hi {$user->user_first_name}, your purchase order #{$order->order_no} has been rejected by {$seller_user->store_name}.";
                    $msg = "Hi {$user->user_first_name}, your purchase order #{$order->order_no} has been rejected by {$seller_user->store_name}.";
                }elseif ( $order_status == ORDER_STATUS_DISPATCHED ) {
                    $msg_title =$title              = "Order Dispatched";
                    $msg = "Hi {$user->user_first_name}, your purchase order #{$order->order_no} has been dispatched by {$seller_user->store_name}.";
                }elseif ( $order_status == ORDER_STATUS_DELIVERED ) {
                    $msg_title =$title              = "Order Delivered";
                    $msg = "Hi {$user->user_first_name}, your purchase order #{$order->order_no} has been delivered by {$seller_user->store_name}.";
                }elseif ( $order_status == ORDER_STATUS_READY ) {
                    $msg_title =$title              = "Order Ready to Ship";
                    $msg = "Hi {$user->user_first_name}, your purchase order #{$order->order_no}  has ready to ship by {$seller_user->store_name}.";
                }
                
                
                $this->load->model("website/product_model", "model_product");
                $product_data = $this->model_product->get_product($get_order_data->product_id,$order->user_id);
          //  echo "<pre>hre"; var_dump($product_data); echo "</pre>"; 
                $product_images = explode(",", $product_data->product_image); 
                $product_image  = (count($product_images) > 0) ? $product_images[0] : $product_data->product_image;


                if(file_exists("uploads/products/". $product_image) && is_file("uploads/products/". $product_image))
                    $product_image = base_url()."uploads/products/". $product_image;
                else
                    $product_image = base_url()."uploads/products/dummy.png";
                

                $email_purchased_products[] = (object) ["product_name" => $product_data->product_name, 
                                                        "product_image" => $product_image,
                                                        "cloth_type" => $product_data->p_cloth_type, 
                                                        "dress_type" => $product_data->p_dress_type,
                                                        "quantity" => $get_order_data->product_count,

                                                        "unit_price" => $get_order_data->unit_price_uc,
                                                        "unit_shipping_charge" => $get_order_data->unit_shipping_charge_uc,
                                                        "product_sub_price" =>  $get_order_data->product_sub_price_uc,
                                                        "product_total_tax" =>  $get_order_data->product_total_tax_uc,
                                                        "product_total" => $get_order_data->order_sub_total,
                                                        "signle_cash_point_value" => $this->single_point_bc_value,	
                                                        
                                                        ];
                $email_message =  $this->load->view("email_templates/order_status_change", [
                                                "product_list" => $email_purchased_products, 
                                                "order_details" => (object) $get_order_data,
                                                "message"=>$msg,
                                                "subject"=>$msg_title
                                                ], true); 
                  //echo "<pre>hre"; var_dump($email_purchased_products); echo "</pre>"; exit();
                $subject    = $msg_title;
                $to         = $user->user_email_id;

                //$to         = "rejeesh.a2solution@gmail.com";

                $this->load->library("Mail_function");
                $ret=$this->mail_function->SendEmail($email_message, $subject, $to);
                //var_dump($ret);
                //echo "<pre>hre"; var_dump($product_data); echo "</pre>"; exit();
                
                if ( empty($ntype) ) {
                    return TRUE;
                }

                if ( !empty($user->firebase_user_key) ) {
                    $notification_data["Notifications/".$user->firebase_user_key."/".$notification_id] = [
                        "title" => $title,
                        "description" => $description,
                        "notificationType" => $ntype,
                        "createdAt" => gmdate("d-m-Y H:i:s", $notification_id),
                        "orderID" => (string) $order->order_block_id,
                        "url" => "",
                        "imageURL" => "",
                        "read" => "0",
                        "seen" => "0"
                    ];

                    $fb_database = get_firebase_refrence();
                    $fb_database->getReference()->update($notification_data);

                }

                if (! empty($user->user_device_token) ) {
                    $this->fcm_notification->send_single_notification($user->user_device_token,
                        [
                            "title" => $title,
                            "body" => $description,
                            "icon"=>'myicon',
                            "sound" =>'default',
                            "click_action" => "EcomNotification"
                        ],
                        [
                            "type" => $ntype,
                            "notificationID" => $notification_id,
                            "orderID" => (string) $order->order_block_id,
                            "imageURL" => ""
                        ]
                    );
                }
                
                
            }
        }
    }
    public function send_service_notification_user( $order, $order_status=NULL )
    {
        if ( $order ) {
            $user = $this->model_user->get_user_by_id($order->user_id);
            $seller_user = $this->model_user->getSellerByUserId($this->user->user_id);
            if ( $user && $seller_user ) {
                $this->load->library("FCM_Notification");

                $notification_id    = time();
                $ntype              = "";
                if ( $order_status == ORDER_STATUS_ACCEPTED ) {
                    $ntype              = "booking-accepted";
                    $title              = "Booking Accepted";
                    $description        = "Hi {$user->user_first_name}, your service booking #{$order->order_no} has been accepted by {$seller_user->store_name}.";
                } elseif ( $order_status == ORDER_STATUS_CANCEL ) {
                    $ntype              = "booking-cancel";
                    $title              = "Booking Rejected";
                    $description        = "Hi {$user->user_first_name}, your service booking #{$order->order_no} has been rejected by {$seller_user->store_name}.";
                } else if($order_status == ORDER_STATUS_DISPATCHED){
                     $ntype              = "booking-accepted";
                    $title              = "Booking Dispactched";
                    $description        = "Hi {$user->user_first_name}, your service booking #{$order->order_no} has been Dispactched by {$seller_user->store_name}.";
                } elseif ( $order_status == ORDER_STATUS_READY ) {
                     $ntype              = "booking-accepted";
                    $title              = "Booking Picked Up";
                    $description        = "Hi {$user->user_first_name}, your service booking #{$order->order_no} has been  picked up for delivery by {$seller_user->store_name}.";
                }

                

                if ( empty($ntype) ) {
                    return TRUE;
                }

                if ( !empty($user->firebase_user_key) ) {
                    $notification_data["Notifications/".$user->firebase_user_key."/".$notification_id] = [
                        "title" => $title,
                        "description" => $description,
                        "notificationType" => $ntype,
                        "createdAt" => gmdate("d-m-Y H:i:s", $notification_id),
                        "orderID" => (string) $order->order_block_id,
                        "url" => "",
                        "imageURL" => "",
                        "read" => "0",
                        "seen" => "0"
                    ];

                    $fb_database = get_firebase_refrence();
                    $fb_database->getReference()->update($notification_data);

                }

                if (! empty($user->user_device_token) ) {                        
                    $this->fcm_notification->send_single_notification($user->user_device_token,
                        [
                            "title" => $title,
                            "body" => $description,
                            "icon"=> 'myicon',
                            "sound" => 'default',
                            "click_action" => "EcomNotification"
                        ],
                        [
                            "type" => $ntype,
                            "notificationID" => $notification_id,
                            "orderID" => (string) $order->order_block_id,
                            "imageURL" => ""
                        ]
                    );
                }
            }
        }
    }
    public function myProfile()
    {
        $this->validateLogin();
        $this->addMetaTitle('My Profile');
        $this->addBreadCrumb(
            [current_url(), 'My Profile']
        );

        $this->setSidebarActiveMenu('my_profile');
        if ( $this->session->userdata('user_id') !== null) {
            $userid = $this->session->userdata('user_id');
        }else{
            $userid = '';
        }
         $this->addAssets([
            'footer' => [
                'vendor/my_profile_footer_assets'
            ]
        ]);

        $data['user_data'] = $this->M_product->getUserDetails($userid);        

        if ( $data['user_data']->is_kandora_seller == 1 ) {
            $data['kandora_product_prices'] = $this->M_admin->getVendorKandoraPrices($userid);
            $data['kandora_cash_points'] = $this->M_admin->getVendorKandoraCashPoints($userid);
        }

        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition = array('country_language_code' => $language, 'country_status' => 1);
        $country_list = $this->M_admin->getCountriesCondition($condition);

        $select_country = $data['user_data']->user_country_id ?? 0;
        $condition = array('city_language_code' => $language, 'city_status' => 1, 'city_country_id' => $select_country);
        $city_list = $this->M_admin->getCitiesCondition($condition);

        $bank_list = $this->M_admin->getBankList();
        if ( $language == "2" || 1 ) {
            foreach ($bank_list as $b_id => $b_row) {
                $bank_list[$b_id]->bank_name = $b_row->bank_name_arabic;
            }
        }

        $latitude = $data['user_data']->latitude ?? 25.204819;
        $longitude = $data['user_data']->longitude ?? 55.270931;

        $document_name = $data['user_data']->doument_name ?? "";
        if (! empty($document_name) && file_exists($this->config->item('upload_path').$this->config->item('vendor_image_upload_dir') . $document_name) ) {
            $document_name = getUploadedImageUrl($document_name, 'vendor_image_upload_dir');
        }

        $this->addData(compact('country_list', 'city_list', 'bank_list', 'latitude', 'longitude', 'document_name'));
        $this->render('vendor/my_profile', $data);
    }

    public function kandoraProducts()
    {
        $this->validateLogin();
        $this->addMetaTitle('Kandora Products');
        $this->addBreadCrumb(
            [current_url(), 'Kandora Products']
        );

        $this->setSidebarActiveMenu('kandora_products');
        if ( $this->session->userdata('user_id') !== null) {
            $userid = $this->session->userdata('user_id');
        }else{
            $userid = '';
        }
        $this->addAssets([
            'footer' => [
                'vendor/kandora_products_footer_assets'
            ]
        ]);

        $data['user_data'] = $this->M_product->getUserDetails($userid);

        if ( $data['user_data']->is_kandora_seller == 1 ) {
            $data['kandora_product_prices'] = $this->M_admin->getVendorKandoraPrices($userid);
            $data['kandora_cash_points'] = $this->M_admin->getVendorKandoraCashPoints($userid);
        }

        $this->render('vendor/kandora_products', $data);
    }

    public function validate_kandora_seller( $is_kandora_seller )
    {
        $is_kandora_seller = (int) $is_kandora_seller;
        if ( $is_kandora_seller ) {
            $status = $this->M_vendor->isFabricNamesConfigured($this->vendor_user->user_id);
            if ( $status == 0 ) {
                $this->form_validation->set_message('validate_kandora_seller', 'You must configure Fabric Names for Emirati, Kuwaiti and Saudi.');
                return FALSE;
            }
        }

        return TRUE;
    }

    public function valid_max_delivery_days( $max_days )
    {
        $min_days = (int) $this->input->post('delivery_time_min');
        $max_days = (int) $max_days;
        if ( $min_days >= $max_days ) {
            $this->form_validation->set_message("valid_max_delivery_days", "Enter a value greater than {$min_days}");
            return FALSE;
        }
        return TRUE;
    }

    public function saveVendorProfile()
    {
        $this->validateLogin();
        if ( $this->input->is_ajax_request() ) {
            $status = 1;

            $this->form_validation->set_error_delimiters('', '');
            $this->form_validation->set_message('required', 'This field is required');

            $this->form_validation->set_rules('store_name', 'store name', 'required|trim|max_length[100]');
            $this->form_validation->set_rules('store_name_arabic', 'Store Name (Arabic)', 'trim|required|max_length[300]');
            $this->form_validation->set_rules('first_name', 'first Name', 'required|trim|max_length[100]');
            $this->form_validation->set_rules('last_name', 'last Name', 'required|trim|max_length[100]');
            // $this->form_validation->set_rules('email_id', 'email', 'required|trim|max_length[100]|valid_email');

            // $this->form_validation->set_rules('mobile_no', 'mobile number', 'required|trim|max_length[15]|numeric');
            $this->form_validation->set_rules('country_id', 'Country', 'trim|required');
            $this->form_validation->set_rules('city_id', 'city', 'trim|required');
            // $this->form_validation->set_rules('bank_id', 'bank', 'trim|required');
            // $this->form_validation->set_rules('bank_account_number', 'Account Number', 'trim|required|numeric|max_length[50]');
            // $this->form_validation->set_rules('bank_ifsc_code', 'IFSC code', 'trim|required|max_length[50]');
            // $this->form_validation->set_rules('bank_swift_code', 'swift code', 'trim|required|max_length[50]');
            $this->form_validation->set_rules('about_seller_desc', 'about store', 'required|trim|min_length[10]|max_length[500]');
            $this->form_validation->set_rules('about_seller_desc_arabic', 'about store (arabic)', 'trim|required|min_length[10]|max_length[500]');
            $this->form_validation->set_rules('street_name', 'street name', 'trim|required|max_length[100]');
            $this->form_validation->set_rules('building_no', 'building number', 'required|trim|max_length[50]');
            $this->form_validation->set_rules('account_type', 'account type', 'trim|required');
            $this->form_validation->set_rules('land_phone', 'land phone', 'trim|required');
            // $this->form_validation->set_rules('delivery_time_min', 'delivery time', 'required|trim|numeric');
            // $this->form_validation->set_rules('delivery_time_max', 'delivery time', 'required|trim|numeric|callback_valid_max_delivery_days');
            $this->form_validation->set_rules('document_type', 'document type', 'trim|required');
            $this->form_validation->set_rules('document_number', 'document number', 'trim|required|max_length[50]');            

            if ( $this->form_validation->run() == FALSE ) {
                $status = 0;
                $this->addData([
                    'errors' => [
                        'store_name' => form_error('store_name'),
                        'store_name_arabic' => form_error('store_name_arabic'),
                        'first_name' => form_error('first_name'),
                        'last_name' => form_error('last_name'),
                        // 'email_id' => form_error('email_id'),
                        'country_id' => form_error('country_id'),
                        'city_id' => form_error('city_id'),
                        'bank_id' => form_error('bank_id'),
                        'bank_account_number' => form_error('bank_account_number'),
                        'bank_ifsc_code' => form_error('bank_ifsc_code'),
                        'bank_swift_code' => form_error('bank_swift_code'),
                        'about_seller_desc' => form_error('about_seller_desc'),
                        'about_seller_desc_arabic' => form_error('about_seller_desc_arabic'),
                        'street_name' => form_error('street_name'),
                        'building_no' => form_error('building_no'),
                        'account_type' => form_error('account_type'),
                        'land_phone' => form_error('land_phone'),
                        // 'mobile_no' => form_error('mobile_no'),
                        'delivery_time_min' => form_error('delivery_time_min'),
                        'delivery_time_max' => form_error('delivery_time_max'),
                        'document_type' => form_error('document_type'),
                        'document_number' => form_error('document_number'),
                    ]
                ]);
            } else {
                $_POST = $this->security->xss_clean($_POST);
                if (count($_POST) > 0) {
                    $file_error    = 0;
                    $file_uploaded = 1;
                    $this->load->library('upload');
                    
                    if ( !empty($_FILES['thumbnail']) && ($_FILES['thumbnail']['error'] == UPLOAD_ERR_OK) ) {
                        $config                     = [];
                        $config['upload_path']      = $this->config->item('upload_path') . $this->config->item('vendor_image_upload_dir');
                        $config['allowed_types']    = 'gif|jpg|png|jpeg';
                        $config['max_size']         = 1024;
                        $config['max_width']        = 640;
                        $config['max_height']       = 415;
                        $config['min_width']        = 500;
                        $config['min_height']       = 330;
                        $config['encrypt_name']     = TRUE;

                        $this->upload->initialize($config);
                        if ($this->upload->do_upload('thumbnail')) {
                            $file_data                      = $this->upload->data();
                            $_POST['seller_default_image']  = $file_data["file_name"];
                            $file_uploaded                  = 1;
                        } else {
                            $status = 0;
                            $file_error = 1;
                            $this->addData([
                                'errors' => [
                                    'thumbnail' => $this->upload->display_errors('', ''),
                                ]
                            ]);
                        }
                    }

                    if (! $file_error ) {
                        if ( !empty($_FILES['document_file']) && ($_FILES['document_file']['error'] == UPLOAD_ERR_OK) ) {
                            $config                     = [];
                            $config['upload_path']      = $this->config->item('upload_path') . $this->config->item('vendor_image_upload_dir');
                            $config['allowed_types']    = 'gif|jpg|png|pdf|doc|jpeg';
                            $config['encrypt_name']     = TRUE;

                            $this->upload->initialize($config);
                            if ($this->upload->do_upload('document_file')) {
                                $file_data              = $this->upload->data();
                                $_POST['document_name'] = $file_data["file_name"];
                                $file_uploaded          = 1;
                            } else {
                                $status = 0;
                                $file_error = 1;
                                $this->addData([
                                    'errors' => [
                                        'document_file' => $this->upload->display_errors('', ''),
                                    ]
                                ]);
                            }
                        }
                    }

                    if ( !$file_error && $file_uploaded ) {
                        $_POST['phone_verified'] = 1;
                        if ( empty($_POST['latitude']) ) {
                            $_POST['latitude'] = 25.204819;
                        }
                        if ( empty($_POST['longitude']) ) {
                            $_POST['longitude'] = 55.270931;
                        }
                        $status = $this->M_vendor->updateVendorProfile($this->vendor_user->user_id, $_POST);
                        if ( !$status ) {
                            if ( isset($_POST['seller_default_image']) && !empty($_POST['seller_default_image']) ) {
                                @unlink( $this->config->item('upload_path') . $this->config->item('vendor_image_upload_dir') . $_POST['seller_default_image']);
                            }
                            if ( isset($_POST['doument_name']) && !empty($_POST['doument_name']) ) {
                                @unlink( $this->config->item('upload_path') . $this->config->item('vendor_image_upload_dir') . $_POST['doument_name']);
                            }
                        }
                    }
                } else {
                    $status = 0;
                }
            }

            $this->addData(compact('status'));
            $this->render('json');
        }

        show_404();
    }

    public function saveKandoraProfile()
    {
        $this->validateLogin();
        if ( $this->input->is_ajax_request() ) {
            $status = 1;

            $this->form_validation->set_rules('is_kandora_seller', 'kandora seller', 'callback_validate_kandora_seller');
            $is_kandora_seller = (int) $this->input->post('is_kandora_seller', true);
            /*if ( $is_kandora_seller ) {
                $this->form_validation->set_rules('kandora_price[EMIRATI]', 'price', 'trim|required|greater_than[0]');
                $this->form_validation->set_rules('kandora_price[KUWAITI]', 'price', 'trim|required|greater_than[0]');
                $this->form_validation->set_rules('kandora_price[SAUDI]', 'price', 'trim|required|greater_than[0]');

                $this->form_validation->set_rules('kandora_cash_point[EMIRATI]', 'Emirati Cash Point', 'trim|numeric');
                $this->form_validation->set_rules('kandora_cash_point[KUWAITI]', 'Kuwaiti Cash Point', 'trim|numeric');
                $this->form_validation->set_rules('kandora_cash_point[SAUDI]', 'Saudi Cash Point', 'trim|numeric');
            }*/

            if ( $this->form_validation->run() == FALSE ) {
                $status = 0;
                $this->addData([
                    'errors' => [
                        'is_kandora_seller' => form_error('is_kandora_seller'),
                        'kandora_price[EMIRATI]' => form_error('kandora_price[EMIRATI]'),
                        'kandora_price[KUWAITI]' => form_error('kandora_price[KUWAITI]'),
                        'kandora_price[SAUDI]' => form_error('kandora_price[SAUDI]'),
                        'kandora_cash_point[EMIRATI]' => form_error('kandora_cash_point[EMIRATI]'),
                        'kandora_cash_point[KUWAITI]' => form_error('kandora_cash_point[KUWAITI]'),
                        'kandora_cash_point[SAUDI]' => form_error('kandora_cash_point[SAUDI]'),
                    ]
                ]);
            } else {
                $_POST = $this->security->xss_clean($_POST);
                if (count($_POST) > 0) {
                    $status = $this->M_vendor->updateKandoraProfile($this->vendor_user->user_id, $_POST);
                } else {
                    $status = 0;
                }
            }

            $this->addData(compact('status'));
            $this->render('json');
        }

        show_404();
    }

    public function uploadVendorImage()
    {
        if ( $this->input->is_ajax_request() ) {
            $status = 1;
            $message = "";

            if ( $_FILES["profile_image"]["name"] != "" ) {
                $digits   =  6;
                $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

                $filename = $_FILES["profile_image"]["name"];
                $file_ext = pathinfo($filename, PATHINFO_EXTENSION);

                $config['upload_path']          =  $this->config->item('upload_path'). $this->config->item('vendor_image_upload_dir');
                $config['allowed_types']        =  'gif|jpg|jpeg|png|jfif';
                $config['max_size']             =  1000;
                $config['max_width']            =  1024;
                $config['max_height']           =  768;
                $config['file_name']            =  $randomNo.".".$file_ext;

                $this->load->library('upload', $config);

                if (! $this->upload->do_upload('profile_image') ) {
                    $status = 0;
                    $message = $this->upload->display_errors();
                } else {
                    $status = $this->M_vendor->updateSellerData($this->vendor_user->user_id, ['seller_logo' => $config['file_name']]);
                }
            }

            if ( $_FILES["cover_image"]["name"] != "" ) {
                $digits   =  6;
                $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

                $filename = $_FILES["cover_image"]["name"];
                $file_ext = pathinfo($filename, PATHINFO_EXTENSION);

                $config['upload_path']          =  $this->config->item('upload_path'). $this->config->item('vendor_image_upload_dir');
                $config['allowed_types']        =  'gif|jpg|jpeg|png|jfif';
                $config['max_size']             =  2000;
                $config['max_width']            =  3000;
                $config['max_height']           =  1000;
                $config['file_name']            =  $randomNo.".".$file_ext;

                $this->load->library('upload', $config);

                if (! $this->upload->do_upload('cover_image') ) {
                    $status = 0;
                    $message = $this->upload->display_errors();
                } else {
                    $status = $this->M_vendor->updateSellerData($this->vendor_user->user_id, ['seller_cover_image' => $config['file_name']]);
                }
            }

            $this->addData(compact('status', 'message'));
            $this->render('json');
        }

        show_404();
    }

    public function loadKandoraColorModal()
    {
        $this->validateLogin();
        if ( $this->input->is_ajax_request() ) {
            $category_uid = (string) $this->input->post('category', true);
            $category_uid = strtoupper($category_uid);
            $colors = $this->M_vendor->getSellerKandoraColors($this->vendor_user->user_id, $category_uid, $this->lang_code);
            $data = compact('category_uid', 'colors');
            echo $this->load->view('vendor/kandora_color_modal', $data, true);
            exit;
        }
    }

    public function saveKandoraColor()
    {
        $this->validateLogin();
        if ( $this->input->is_ajax_request() ) {
            $category_uid = (string) $this->input->post('category', true);
            $category_uid = strtoupper($category_uid);
            $selected_values = $this->input->post('selected_values', true);
            $colors = $this->M_vendor->getSellerKandoraColors($this->vendor_user->user_id, $category_uid, $this->lang_code);

            $status = 0;
            if (! empty($colors) ) {
                $all_colors = array_column($colors, 'cat_attribute_value_id');
                $store_colors = [];
                foreach ($all_colors as $cat_attribute_value_id) {
                    $store_colors[] = [
                        'cat_attribute_val_id' => $cat_attribute_value_id,
                        'cat_attribute_store_id' => $this->vendor_user->user_id,
                        'cat_attribute_val_store_status' => in_array($cat_attribute_value_id, $selected_values) ? 1 : 0,
                    ];
                }

                $status = $this->M_vendor->saveSellerKandoraColor($this->vendor_user->user_id, $all_colors, $store_colors);
            }

            echo $status;
        }
    }

    public function loadNewFabricNameInput()
    {
        $this->validateLogin();
        if ( $this->input->is_ajax_request() ) {
            $index = (int) $this->input->post('id', true);
            $category_uid = (string) $this->input->post('category', true);
            $category_uid = strtoupper($category_uid);

            $fabric_name = $this->M_vendor->getFabricName($category_uid);
            $colors      = $this->M_vendor->getKandoraCategoryColors($category_uid);
            $kandora_product_prices = $this->M_admin->getVendorKandoraPrices($this->vendor_user->user_id);
            $product_base_price = $kandora_product_prices[$category_uid] ?? 0;

            echo $this->load->view('vendor/kandora_fabric_name_input_field', compact('index', 'fabric_name', 'colors', 'product_base_price'), true);
            exit;
        }
    }

    public function loadKandoraFabricNameModal()
    {
        $this->validateLogin();
        if ( $this->input->is_ajax_request() ) {
            $category_uid = (string) $this->input->post('category', true);
            $category_uid = strtoupper($category_uid);

            $fabric_name = $this->M_vendor->getFabricName($category_uid);
            $colors      = $this->M_vendor->getKandoraCategoryColors($category_uid);
            $seller_fabric_names = $this->M_vendor->getSellerFabricNames($this->vendor_user->user_id, $category_uid, $this->lang_code);
            $kandora_product_prices = $this->M_admin->getVendorKandoraPrices($this->vendor_user->user_id);
            $product_base_price = $kandora_product_prices[$category_uid] ?? 0;

            $data = compact('category_uid', 'fabric_name', 'colors', 'seller_fabric_names', 'product_base_price');
            echo $this->load->view('vendor/kandora_fabric_name_modal', $data, true);
            exit;
        }
    }

    public function saveKandoraFabricName()
    {
        $this->validateLogin();
        if ( $this->input->is_ajax_request() ) {
            $status       = "0";
            $error        = "";
            $category_uid = (string) $this->input->post('category', true);
            $category_uid = strtoupper($category_uid);
            $cat_attribute_id = (int) $this->input->post('cat_attribute_id', true);
            $seller_fabric_data = $this->input->post('fabric_name', true);

            $fabric_name = $this->M_vendor->getFabricName($category_uid);

            $save_data = [];
            $sort_order = 1;
            $base_price = 0;
            if (! empty($seller_fabric_data) ) {
                $fabric_prices = array_column($seller_fabric_data, 'regular_price');
                $base_price    = min($fabric_prices);
            }
            foreach ($seller_fabric_data as $cat_attribute_value_id => $row) {
                if ( empty($row['attribute_value_name']) ) {
                    continue;
                }
                $cat_fabric_types  = $row['fabric_type'] ?? [];
                $cat_fabric_colors = $row['fabric_color'] ?? [];
                $regular_price     = $row['regular_price'] ?? 0;

                if ( empty($regular_price) && $regular_price != 0 ) {
                    $status = "2";
                    $error  = "Please enter price for {$row['attribute_value_name']}";
                } elseif ( empty($cat_fabric_types) ) {
                    $status = "2";
                    $error  = "Please choose fabric type for {$row['attribute_value_name']}";
                } elseif ( empty($cat_fabric_colors) ) {
                    $status = "2";
                    $error  = "Please choose colors for {$row['attribute_value_name']}";
                } else {
                    $save_data[$cat_attribute_value_id] = [
                        'cat_attribute_id' => $fabric_name->cat_attribute_id,
                        'cat_attribute_val_value' => $row['attribute_value_name'],
                        'cat_attribute_val_value_arabic' => $row['attribute_value_name'],
                        'cat_attribute_val_status' => $row['status'] ?? 0,
                        'cat_attribute_val_sort_order' => $sort_order,
                        'cat_attribute_val_extra_price' => ($regular_price - $base_price),
                        'cat_attribute_val_type_id' => $fabric_name->cat_attribute_type,
                        'cat_attribute_val_store_id' => $this->vendor_user->user_id,
                        'cat_fabric_types' => array_keys($cat_fabric_types),
                        'cat_fabric_colors' => array_values($cat_fabric_colors),
                        'is_new' => $row['is_new'] ?? 1,
                    ];
                    $sort_order++;
                }
            }

            if ( $status == "0" && !empty($save_data) ) {                
                $status = $this->M_vendor->saveSellerFabricNames($save_data, $this->vendor_user->user_id, $category_uid, $base_price);
            }

            header('Content-Type: application/json');
            echo json_encode(compact('status', 'error'));
            exit;
        }
    }

    public function fileimage($filename){
        $actualimage = '';
        $digits   =  6;
         $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);
                        $randomNo3 = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

                        $filename2 = $_FILES["$filename"]["name"];
                         // $filename3 = $_FILES["profileimage"]["name"];

                        $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);
                        // $file_ext3 = pathinfo($filename3, PATHINFO_EXTENSION);

                        $config2['upload_path']          =  $this->config->item('upload_path').'vendor_images/';
                         // $config3['upload_path']          =  $this->config->item('upload_path').'vendor_images/';
                        $config2['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
                        // $config3['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
                        $config2['max_size']             =  1000;
                         // $config3['max_size']             =  1000;
                        //$config2['max_width']            =  1024;
                        //$config2['max_height']           =  768;
                        $config2['file_name']            =  $randomNo.".".$file_ext2;
                        // $config3['file_name']            =  $randomNo3.".".$file_ext3;
                        //$this->load->library('upload', $config2);
                         $this->load->library('upload', $config2);

                if (! $this->upload->do_upload($filename)) {
                    // $data['status'] = 0;
                    $status = 0;
                    $data['errors'] = array(
                    'txt_doc' => "File upload failed",
                    );

                    // exit();
                } else {
                    $status = 1;
                    $actualimage  =    $config2['file_name'];
                }
                return $actualimage;
    }
    public function profileimage(){

       $actualimage = '';
        $digits   =  6;
         $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);


                        $filename2 = $_FILES['profileimages']["name"];
                         // $filename3 = $_FILES["profileimage"]["name"];

                        $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);
                        // $file_ext3 = pathinfo($filename3, PATHINFO_EXTENSION);

                        $config2['upload_path']          =  $this->config->item('upload_path').'vendor_images/';
                         // $config3['upload_path']          =  $this->config->item('upload_path').'vendor_images/';
                        $config2['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
                        // $config3['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
                        // $config2['max_size']             =  1000;
                         // $config3['max_size']             =  1000;
                        //$config2['max_width']            =  1024;
                        //$config2['max_height']           =  768;
                        $config2['file_name']            =  $randomNo.".".$file_ext2;
                        // $config3['file_name']            =  $randomNo3.".".$file_ext3;
                        //$this->load->library('upload', $config2);
                         $this->load->library('upload', $config2);
                         // $this->load->library('upload', $config3);
                        // $this->upload->initialize($config2);

                if (! $this->upload->do_upload('profileimages')) {
                    // $data['status'] = 0;
                    $status = 0;
                    $data['errors'] = array(
                    'txt_doc' => "File upload failed",
                    );

                    // exit();
                } else {
                    $status = 1;
                    $actualimage  =    $config2['file_name'];
                }
         if ( $this->session->userdata('user_id') !== null) {
            $userid = $this->session->userdata('user_id');
        }else{
            $userid = '';
        }
        $dataseller = array('seller_logo' => $actualimage);
        $seller_data = $this->M_product->updateSellerDetails($dataseller,$userid);

        if($seller_data > 0){
        $storename='';
           $storename= base_url('uploads/vendor_images/'.$actualimage);
           echo $storename ;
       }
       else{
         echo $storename = '';
       }


    }
    public function coverimage(){

       $actualimage = '';
        $digits   =  6;
         $randomNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);


                        $filename2 = $_FILES['coverimage']["name"];
                         // $filename3 = $_FILES["profileimage"]["name"];

                        $file_ext2 = pathinfo($filename2, PATHINFO_EXTENSION);
                        // $file_ext3 = pathinfo($filename3, PATHINFO_EXTENSION);

                        $config2['upload_path']          =  $this->config->item('upload_path').'vendor_images/';
                         // $config3['upload_path']          =  $this->config->item('upload_path').'vendor_images/';
                        $config2['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
                        // $config3['allowed_types']        =  'gif|jpg|png|pdf|doc|jpeg';
                        // $config2['max_size']             =  2000;
                         // $config3['max_size']             =  1000;
                        //$config2['max_width']            =  1024;
                        //$config2['max_height']           =  768;
                        $config2['file_name']            =  $randomNo.".".$file_ext2;
                        // $config3['file_name']            =  $randomNo3.".".$file_ext3;
                        //$this->load->library('upload', $config2);
                         $this->load->library('upload', $config2);
                         // $this->load->library('upload', $config3);
                        // $this->upload->initialize($config2);

                if (! $this->upload->do_upload('coverimage')) {
                    // $data['status'] = 0;
                    $status = 0;
                    $data['errors'] = array(
                    'txt_doc' => "File upload failed",
                    );

                    // exit();
                } else {
                    $status = 1;
                    $actualimage  =    $config2['file_name'];
                }
         if ( $this->session->userdata('user_id') !== null) {
            $userid = $this->session->userdata('user_id');
        }else{
            $userid = '';
        }
        $dataseller = array('seller_default_image' => $actualimage);
        $seller_data = $this->M_product->updateSellerDetails($dataseller,$userid);
        $storename='';
        if($seller_data > 0){

           $storename= base_url('uploads/vendor_images/'.$actualimage);
           echo $storename ;
       }else{
         echo  $storename = '';
       }


    }
    //   public function saveprofile(){
    //     $first = $this->input->post('first');
    //     $last = $this->input->post('last');
    //     $emails = $this->input->post('emails');



    //      $mobilecode = $this->input->post('mobilcode');
    //     $streetname = $this->input->post('streetname');
    //     $buildingno = $this->input->post('buildingno');
    //     $mobileno = $this->input->post('mobileno');
    //     $description = $this->input->post('descriptions');

    //     // new one start
    //     $this->form_validation->set_rules('streetname', 'Required', 'trim|required');
    //     $this->form_validation->set_rules('buildingno', 'Required', 'trim|required');
    //     $this->form_validation->set_rules('mobileno', 'Required', 'trim|required');
    //     $this->form_validation->set_rules('descriptions', 'Required', 'trim|required');

    //     $this->form_validation->set_rules('first', 'Required', 'trim|required');
    //     $this->form_validation->set_rules('last', 'Required', 'trim|required');
    //     $this->form_validation->set_rules('emails', 'Required', 'trim|required');
    //     if ($this->form_validation->run() == FALSE) {
    //         $data['status'] = 0;

    //         echo json_encode($data);
    //         exit();
    //     }
    //     else{
    //     // new one end
    //     if ( $this->session->userdata('user_id') !== null) {
    //         $userid = $this->session->userdata('user_id');
    //     }else{
    //         $userid = '';
    //     }
    //     $dataseller = array('street_name' => $streetname,'building_no' => $buildingno,'mobile_no'=>$mobilecode.$mobileno,'about_seller_desc'=>$description);
    //     $seller_data = $this->M_product->updateSellerDetails($dataseller,$userid);


    //     $data = array('user_id'=>$userid,'user_first_name'=>$first,'user_last_name'=>$last,'user_email_id'=>$emails);

    //     $user_data2 = $this->M_product->updateUserDetails($data);

    //     $user_data = $this->M_product->getUserDetails($userid);

    //      $mobno = $user_data->mobile_no;
    //      $expmobno = explode("-",$mobno);
    //      if($user_data2 == 1 || $seller_data == 1){
    //         $status = 1;
    //      }else{
    //         $status = 0;
    //      }
    //     $datas = array('status'=>$status,'first'=>$user_data->user_first_name,'last'=>$user_data->user_last_name,'emails'=>$user_data->user_email_id,'streetname' => $user_data->street_name,'buildingno' => $user_data->building_no,'mobileno'=>$expmobno[1],'descriptions'=>$user_data->about_seller_desc);
    //     echo json_encode($datas);
    //     }

    // }
    function Shipping()
    {
        $vendorid  = $this->session->userdata("user_id");
        $param2                        =    array("user_id" => $vendorid);
        $records2                      =    $this->M_admin->getSellerDetails($param2);
        $data['vender_deatils']        =    $records2[0];
        $data['shipping_class_id'] = $records2[0]->shipping_class_id;

        $data['getShippingWeight'] = $this->M_vendor->getSellerShippingWeight($vendorid);
        //     print_r($data['getShippingWeight']);
        //       echo "hai".$records2[0]->shipping_class_id;
        //  exit;

        $this->load->view("vendor/add_products_scripts");
        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("vendor/shipping", $data);
        $this->load->view("vendor/footer");
    }

    //save shipping method
    function saveShippingMethod()
    {

        $vendorid  = $this->session->userdata("user_id");
        $data['shipping_class_id'] = $_POST['inline-radios'];
        //update shipping class
        $result = $this->M_vendor->updateShippingMethod($vendorid, $data);
        $data['status'] = $result;
        echo json_encode($data);
    }

    function Policy()
    {
        $vendorid  = $this->session->userdata("user_id");
        $param2                        =    array("user_id" => $vendorid);
        $records2                      =    $this->M_admin->getSellerDetails($param2);
        $data['vender_deatils']        =    $records2[0];

        $this->load->view("vendor/add_products_scripts");
        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("vendor/policies", $data);
        $this->load->view("vendor/footer");
    }
    function Store()
    {

        $vendorid  = $this->session->userdata("user_id");
        if ($vendorid <= 0) {
            redirect(base_url());
        }

        $language   =  ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition =   array('country_language_code' => $language, 'country_status' => 1);
        $data["country_list"]        =   $this->M_admin->getCountriesCondition($condition);

        $condition2 =   array('mall_language_code' => $language, 'mall_status' => 1);
        $data["mall_list"]        =   $this->M_admin->getMallsCondition($condition2);
        $this->load->view("vendor/add_products_scripts");
        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("vendor/store", $data);
        $this->load->view("vendor/footer");
    }
    function loadAddProductForm()
    {

        $language   =  ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition =   array('category_language_code' => $language, 'category_status' => 1);
        $data["category_list"]        =   $this->M_product->getCategoriesCondition($condition);
        $condition2 =   array('attribute_status' => 1);
        $data["attr_list"]        =   $this->M_product->getAttributesCondition($condition2);
        $condition3 =   array('brand_language_code' => $language, 'brand_status' => 1);
        $data["brand_list"]        =   $this->M_product->getBrandsCondition($condition3);


        $data['clothTypes']        =   $this->M_product->getClothTypes();
        $data['dressTypes']        =   $this->M_product->getDressTypes();


        $this->load->view("vendor/add_products_scripts");
        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("admin/add_edit_product", $data);
        $this->load->view("vendor/footer");
    }
    function loadEditProductForm()
    {
        error_reporting(E_ERROR | E_PARSE);
        $id              =  $this->uri->segment(2);
        if ($id) {
            $language   =  ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
            $condition =   array('category_language_code' => $language, 'category_status' => 1);
            $data["category_list"]        =   $this->M_product->getCategoriesCondition($condition);
            $condition2   =   array('attribute_status' => 1);
            $data["attr_list"]        =   $this->M_product->getAttributesCondition($condition2);

            $data["product_basic_list"]        =   $this->M_product->getProductBasicListById($id);
            $data["product_category"]          =   $this->M_product->getCategoriesByProductId($id);
            $data["product_aatribute"]         =   $this->M_product->getAttributeDetailsByProductId($id, $data["product_basic_list"][0]->product_type);

            $data["product_aatribute2"]         =   $this->M_product->AttributeDetailsByProductId2($id, $data["product_basic_list"][0]->product_type, $data["product_basic_list"][0]->product_type);


            $condition3 =   array('brand_language_code' => $language, 'brand_status' => 1);
            $data["brand_list"]        =   $this->M_product->getBrandsCondition($condition3);
            $data['clothTypes'] = $this->M_product->getClothTypes();
            $data['dressTypes'] = $this->M_product->getDressTypes();

            // echo "<pre>";
            //print_r($data["product_aatribute"]);

            $this->load->view("vendor/add_products_scripts");
            $this->load->view("vendor/header");
            $this->load->view("vendor/sidebar");
            $this->load->view("admin/edit_product", $data);
            $this->load->view("vendor/footer");
        }
    }
    function orderReport()
    {
        $condition                    =    array("user_type" => "U");
        $data["user_list"]        =   $this->M_admin->getUsersCondition($condition);

        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("admin/order_report", $data);
        // $this->load->view("admin/footer");
        $this->load->view("vendor/footer");
    }
    function salesReport()
    {
        $condition                    =    array("user_type" => "V");
        $data["user_list"]        =   $this->M_admin->getVenderCondition();
        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("admin/sales_report", $data);
        $this->load->view("vendor/footer");
    }
    function withdarwalReport()
    {
        $condition                    =    array("user_type" => "V");
        //$data["user_list"]        =   $this->M_admin->getVenderCondition();
        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("admin/withdrawal_report", $data);
        $this->load->view("vendor/footer");
    }
    /**
     * [custom_minlength_check description]
     * @param   string $field_value [description]
     * @return  [type]              [description]
     * @author Jitin Joseph <jitin.a2solution@gmail.com>
     * @created on     2018-09-28
     */
    public function custom_minlength_check($field_value = "")
    {
        $field_value = strip_tags($field_value);
        if (strlen($field_value) < 10) {
            $this->form_validation->set_message('custom_minlength_check', "Please enter atleast 10 characters");
            return FALSE;
        } else {
            return TRUE;
        }
    }
    //-----------------------------
    function saveStoreFront()
    {

        $data = array();

        $this->form_validation->set_rules('txt_store_name', 'Store name', 'trim|required|max_length[100]|callback_check_inavlid_char');
        $this->form_validation->set_rules('txt_store_name_arabic', 'Store name Arabic', 'trim|required|max_length[100]|callback_check_inavlid_char');
        $this->form_validation->set_rules('txt_owner_first_name', 'Owner First Name', 'trim|required|max_length[100]|xss_clean|alpha');
        $this->form_validation->set_rules('txt_owner_last_name', 'Owner Last Name', 'trim|required|max_length[100]|xss_clean|alpha');
        $this->form_validation->set_rules('txt_location', 'Location', 'trim|required|max_length[150]');
        $this->form_validation->set_rules('select_country', 'Country', 'trim|required');
        $this->form_validation->set_rules('select_city', 'City', 'trim|required');
        $this->form_validation->set_rules('txt_street', 'Street', 'trim|required|max_length[150]|callback_check_inavlid_char');
        $this->form_validation->set_rules('txt_building', 'Building', 'trim|required|max_length[50]|callback_check_inavlid_char');
        $this->form_validation->set_rules('txt_Phone', 'Phone', 'trim|required|numeric|min_length[5]|max_length[10]|xss_clean');
        $this->form_validation->set_rules('txt_store_desc', 'Store Description English', 'trim|required');
        $this->form_validation->set_rules('txt_msg_tobuyres', 'Store Description Arabic', 'trim|required|callback_custom_minlength_check');

        if ($this->form_validation->run() == FALSE) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_store_name' => form_error('txt_store_name'),
                'txt_store_name_arabic' => form_error('txt_store_name_arabic'),
                'txt_owner_first_name' => form_error('txt_owner_first_name'),
                'txt_owner_last_name' => form_error('txt_owner_last_name'),
                'txt_location' => form_error('txt_location'),
                'select_country' => form_error('select_country'),
                'select_city' => form_error('select_city'),
                'txt_street' => form_error('txt_street'),
                'txt_building' => form_error('txt_building'),
                'txt_Phone' => form_error('txt_Phone'),
                'txt_store_desc' => form_error('txt_store_desc'),
                'txt_msg_tobuyres' => form_error('txt_msg_tobuyres'),
            );
            echo json_encode($data);
            exit();
        }

        $_POST = $this->security->xss_clean($_POST);
        $_FILES = $this->security->xss_clean($_FILES);



        $result =   $this->M_product->saveStoreFront($_POST, $_FILES);
        $data['status'] = $result;
        echo json_encode($data);
    }
    function saveStoreSocialMedia()
    {
        /**
         * changes by jitin on 29 sep 18 for server side validation
         */

        $data = array();

        $this->form_validation->set_rules('txt_facebook', 'Facebook', 'trim|required');
        $this->form_validation->set_rules('txt_twitter', 'Twitter', 'trim|required');
        $this->form_validation->set_rules('txt_instagarm', 'Instagram', 'trim|required');
        $this->form_validation->set_rules('txt_snapchat', 'Snapchat', 'trim|required');
        $this->form_validation->set_rules('txt_telegram', 'Telegram', 'trim|required');
        if ($this->form_validation->run() == FALSE) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_facebook' => form_error('txt_facebook'),
                'txt_twitter' => form_error('txt_twitter'),
                'txt_instagarm' => form_error('txt_instagarm'),
                'txt_snapchat' => form_error('txt_snapchat'),
                'txt_telegram' => form_error('txt_telegram'),
            );
            echo json_encode($data);
            exit();
        }

        // print_r($_POST);
        $_POST = $this->security->xss_clean($_POST);
        $result =   $this->M_product->saveStoreSocialMedia($_POST);
        $data['status'] = $result;
        echo json_encode($data);
    }
    function savePolicy()
    {
        /**
         * changes by jitin on 29 sep 18 for server side validation
         */

        $data = array();
        $this->form_validation->set_rules('txt_shipping_policy', 'Shipping Policy English', 'trim|required|callback_custom_minlength_check');
        $this->form_validation->set_rules('txt_shipping_policy_arb', 'Shipping Policy Arabic', 'trim|required|callback_custom_minlength_check');
        $this->form_validation->set_rules('txt_refund_policy', 'Refund Policy English', 'trim|required|callback_custom_minlength_check');
        $this->form_validation->set_rules('txt_refund_policy_arb', 'Refund Policy Arabic', 'trim|required|callback_custom_minlength_check');
        $this->form_validation->set_rules('txt_exchange_policy', 'Exchange Policy English', 'trim|required|callback_custom_minlength_check');
        $this->form_validation->set_rules('txt_exchange_policy_arb', 'Exchange Policy Arabic', 'trim|required|callback_custom_minlength_check');
        if ($this->form_validation->run() == FALSE) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_shipping_policy' => form_error('txt_shipping_policy'),
                'txt_shipping_policy_arb' => form_error('txt_shipping_policy_arb'),
                'txt_refund_policy' => form_error('txt_refund_policy'),
                'txt_refund_policy_arb' => form_error('txt_refund_policy_arb'),
                'txt_exchange_policy' => form_error('txt_exchange_policy'),
                'txt_exchange_policy_arb' => form_error('txt_exchange_policy_arb'),
            );
            echo json_encode($data);
            exit();
        }

        $_POST = $this->security->xss_clean($_POST);
        $result =    $this->M_product->savePolicy($_POST);
        $data['status'] = $result;
        echo json_encode($data);
    }
    //shipping

    function addShipping()
    {

        $data = array(

            'ship_method_name' => $this->input->post('shipmethod[]'),
            'min_weight' => $this->input->post('minweight[]'),
            'max_weight' => $this->input->post('maxweight[]'),
            'ship_cost' => $this->input->post('cost[]'),

        );
        $result = $this->M_vendor->insertShipping($data);
        $data['status'] = $result;
        echo json_encode($data);
    }
    function loadVendorOrderHistory()
    {
        $userId     =     $this->session->userdata("user_id");
        $data       =  array();
        // $data["order_list"]        =   $this->M_product->getOrderHistoryForVendor($userId);

        //print_r($data["order_list"]);exit;
        $this->load->view("vendor/add_products_scripts");
        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("vendor/order_history_vendor", $data);
        $this->load->view("vendor/footer");
    }


    function loadOrderStatus()
    {
        $data = array();
        $data["product_list"]        =   $this->M_product->getAllProducts();
        //print_r($data["product_list"]);

        $this->load->view("vendor/add_products_scripts");
        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("admin/order_status", $data);
        $this->load->view("vendor/footer");
    }


    function loadStockReport()
    {
        $data = array();
        $data["product_list"]        =   $this->M_product->getAllProducts();
        $this->load->view("vendor/add_products_scripts");
        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("admin/stock_report", $data);
        $this->load->view("vendor/footer");
    }
    function addCoupon()
    {
        $language   =  ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $condition =   array('category_language_code' => $language, 'category_status' => 1);
        $data["category_list"]        =   $this->M_product->getCategoriesCondition($condition);

        $param    =  array('user_id' => $this->session->userdata('user_id'));
        $data["productList"]           =   $this->M_product->getProductNameId($param);

        //print_r( $data["productList"]);


        $this->load->view("vendor/add_products_scripts");
        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("vendor/add_coupon", $data);
        $this->load->view("vendor/footer");
    }

    public function listCoupon()
    {

        $param    =  array('user_id' > $this->session->userdata('user_id'));
        $data['coupon_list']     =  $this->M_product->getCouponDetails($param);

        //  print_r($data['coupon_list']);
        $this->load->view("vendor/add_products_scripts");
        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("vendor/list_coupon", $data);
        $this->load->view("vendor/footer");
    }

    function driverDetails()
    {
        error_reporting(E_ALL & ~E_WARNING);

        $id                           =      $_POST['id'];
        // $param                      =   array("user_id"=>$id);
        $records1                     =   $this->M_admin->getDriverFulDetails($id);
        $data['user_deatail']          =     $records1;
        // exit;
        $this->load->view('admin/driver_detail_view.php', $data);
    }

    public function driverList($status=null, $page=1)
    {
        $this->validateLogin();
        $status = ( is_null($status) ) ? -1 : $status;
        $page = ( !$page || $page < 0 ) ? 1 : $page;
        $limit = $this->input->post('search_limit', true) ?? 20;
        
        $this->addData([
            'module_name' => 'my_products',
            'header_section' => 'product_listing',
            'footer_section' => 'product_listing',
            'status_list' => [                
                [1, 'Published'],
                [0, 'Not Published'],
                [2, 'Waiting Approval'],
            ],
            'status' => $status,
            'page' => $page,
            'limit' => $limit,
        ]);
        
        if ( $status > 2 ) {
            show_404();
        }
        
        
        if ($this->input->is_ajax_request() ) {
            
            $this->validateLogin();
            $this->setSidebarActiveMenu('driver_list');
            $this->addMetaTitle('Drivers List');
            $this->addBreadCrumb(
                [current_url(), 'Drivers List']
            );
            
            $driver_list    = $this->M_vendor->getDriverList();
            echo "<pre>";
            print_r($driver_list);exit;
            
        }else{
            $this->setSidebarActiveMenu('driver_list');
            $this->addMetaTitle('Drivers List');
            
            $this->addAssets([
            'footer' => [
                'vendor/driver_footer_assets',
                ]
            ]);
            
            $this->addData([
                'driver_list' => $this->M_vendor->getDriverList(),
            ]);
    
            $this->render('vendor/driver_list');
            
        }
        
        // echo $page;exit;
        
        //$data["driver_list"]        = $this->M_admin->getSellerDriverCondition($seller_id);
    }

    public function addVendorDriver()
    {

        $language   =  ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $this->setSidebarActiveMenu('driver_list');
        $condition =   array('country_language_code' => $language, 'country_status' => 1);
        
        $this->addData([
                    'country_list'  => $this->M_admin->getCountriesCondition($condition),
                    'bank_list'       => $this->M_admin->getBankList(),
                    'action'        =>'add'
                ]);
                
        $this->addAssets([
            'footer' => [
                'vendor/driver_footer_assets',
            ]
        ]);
        
        $this->render('vendor/add_driver');
    }
    
    public function saveDriver(){
        $data = array();

        $id = $this->input->post('id', true);

        $this->form_validation->set_rules('txt_first_name', 'First name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_last_name', 'Last name', 'trim|required|max_length[100]|xss_clean|alpha_space');
        $this->form_validation->set_rules('txt_email', 'Email Address', 'required|valid_email|max_length[100]');
        // $this->form_validation->set_rules('radio_gender', 'Gender', 'trim|required');
        $this->form_validation->set_rules('select_country', 'Country', 'trim|required');
        if (! isset($id) ) {
            $this->form_validation->set_rules('txt_password', 'Password', 'trim|required|min_length[8]|max_length[20]|valid_password');
            //$this->form_validation->set_rules('txt_user_id', 'User id', 'trim|required|max_length[50]|min_length[8]|xss_clean|alpha_numeric');
        } else {
            $pw = $this->input->post('txt_password', true);
            if ( $pw == 'nopassword' ) {
                $_POST['txt_password'] = '';
            }
            if ( !empty($pw) && ($pw != 'nopassword') ) {
                $this->form_validation->set_rules('txt_password', 'Password', 'min_length[8]|max_length[20]|valid_password');
            }
        }
        $this->form_validation->set_rules('select_city', 'City', 'trim|required');
        $this->form_validation->set_rules('txt_Phone', 'Phone', 'trim|required|numeric|min_length[5]|max_length[10]|xss_clean');
        // $this->form_validation->set_rules('txt_Land_Phone[]', 'Land Phone', 'trim|numeric|max_length[15]');
        // $this->form_validation->set_rules('txt_location[]', 'Location', 'trim|required|max_length[150]');
        $this->form_validation->set_rules('txt_street', 'Street Name', 'trim|required|max_length[100]|check_inavlid_char');
        // $this->form_validation->set_rules('txt_building[]', 'Building Number', 'trim|required|max_length[50]|check_inavlid_char');
        // $this->form_validation->set_rules('txt_License[]', 'License No', 'trim|required|max_length[50]|check_inavlid_char');
        $this->form_validation->set_rules('txt_veh_no', 'Vehicle No', 'trim|required|max_length[50]|check_inavlid_char');

        if (! isset($id) ) {
            if (empty($_FILES['txt_doc']['name'])) {
                $this->form_validation->set_rules('txt_doc', 'Upload Document', 'trim|required');
            }
            if (empty($_FILES['txt_doc2']['name'])) {
                $this->form_validation->set_rules('txt_doc2', 'Upload Document', 'trim|required');
            }
        }

        $this->form_validation->set_rules('driver_bank_id', 'Bank', 'trim|required');
        $this->form_validation->set_rules('driver_bank_account_number', 'Bank Account No.', 'trim|required|numeric|max_length[50]|xss_clean');
        // $this->form_validation->set_rules('driver_bank_ifsc_code', 'IFSC Code', 'trim|required|max_length[50]');
        $this->form_validation->set_rules('driver_bank_swift_code', 'Swift Code', 'trim|required|max_length[50]');

        if ($this->form_validation->run() == false) {
            $data['status'] = 0;            
            $data['errors'] = array(
                'txt_first_name' => form_error('txt_first_name'),
                'txt_last_name' => form_error('txt_last_name'),
                'txt_email' => form_error('txt_email'),
               // 'txt_user_id' => form_error('txt_user_id'),
                'radio_gender' => form_error('radio_gender'),
                'select_country' => form_error('select_country'),
                'txt_password' => form_error('txt_password'),
                'select_city' => form_error('select_city'),
                'txt_Phone' => form_error('txt_Phone'),
                //'txt_Land_Phone[]' => form_error('txt_Land_Phone[]'),
                'txt_location[]' => form_error('txt_location[]'),
                'txt_street' => form_error('txt_street'),
                'txt_building[]' => form_error('txt_building[]'),
                'txt_License[]' => form_error('txt_License[]'),
                'txt_veh_no' => form_error('txt_veh_no'),
                'txt_emirates_id[]' => form_error('txt_emirates_id[]'),
                // 'select_doc_type[]' => form_error('select_doc_type[]'),
                // 'txt_doc' => form_error('txt_doc'),
                'txt_doc2' => form_error('txt_doc2'),
                'txt_doc3' => form_error('txt_doc3'),
                'driver_bank_id' => form_error('driver_bank_id'),
                'driver_bank_account_number' => form_error('driver_bank_account_number'),
                'driver_bank_ifsc_code' => form_error('driver_bank_ifsc_code'),
                'driver_bank_swift_code' => form_error('driver_bank_swift_code'),
            );
            echo json_encode($data);
            exit();
        }
        $_POST = $this->security->xss_clean($_POST);
        
        // echo json_encode($this->config->item('upload_path').$this->config->item('user_profile_image_upload_dir'));exit;

        if ( count($_POST) > 0 ) {
            $result = 1;
            /**
             * There is no need to verify phone number, since it is added by Admin.
             * Otherwise the driver will be blocked from being login using mobile app
             * because of OTP verification.
             */
            $_POST['phone_verified'] = 1;
            if ( $id > 0 ) {
                $result = $this->M_vendor->updateDriver($_POST);
            } else {
                $result = $this->M_vendor->saveDriver($_POST);
            }
        } else {
            $result = 0;
        }
        $data['status'] = $result;

        echo json_encode($data);
        exit;
    }

    public function editVendorDriver($driverId=NULL)
    {
        $id =  $this->M_product->decryptId($driverId);
        $driver_record = $this->M_admin->getDriverCondition(['u.user_id' => $id]);
        if (! empty($driver_record) ) {
            $driver_record = $driver_record[0];
        } else {
            show_404();
        }

        $language   =  ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $this->setSidebarActiveMenu('driver_list');
        $condition =   array('country_language_code' => $language, 'country_status' => 1);

        $city_list = [];
        if (! empty($driver_record->user_country_id) ) {
            $city_list = $this->M_admin->getCitiesCondition([
                'city_country_id' => $driver_record->user_country_id,
                'city_language_code' => $language,
            ]);
        }
        
        $this->addData([
            'driver_record' => $driver_record,
            'country_list'  => $this->M_admin->getCountriesCondition($condition),
            'city_list'     => $city_list,
            'bank_list'     => $this->M_admin->getBankList(),
            'action'        => 'edit'
        ]);
                
        $this->addAssets([
            'footer' => [
                'vendor/driver_footer_assets',
            ]
        ]);

        $this->render('vendor/edit_driver');
    }

    public function saveVendorDriver()
    {

        $data = array();

        $this->form_validation->set_rules('txt_first_name', 'First name', 'trim|required|max_length[100]|xss_clean|callback_alpha_space');
        $this->form_validation->set_rules('txt_last_name', 'Last name', 'trim|required|max_length[100]|xss_clean|callback_alpha_space');
        $this->form_validation->set_rules('txt_email', 'Email Address', 'trim|required|valid_email|max_length[100]');
        // $this->form_validation->set_rules('radio_gender', 'Gender', 'trim|required');
        $this->form_validation->set_rules('select_country', 'Country', 'trim|required');
        $this->form_validation->set_rules('txt_password', 'Password', 'trim|required|min_length[8]|max_length[20]|callback_valid_password');
        $this->form_validation->set_rules('select_city', 'City', 'trim|required');
        $this->form_validation->set_rules('txt_Phone', 'Phone', 'trim|required|numeric|min_length[5]|max_length[10]|xss_clean');

        $this->form_validation->set_rules('txt_location', 'Location', 'trim|required|max_length[150]');
        $this->form_validation->set_rules('txt_street', 'Street Name', 'trim|required|max_length[150]|callback_check_inavlid_char');
        $this->form_validation->set_rules('txt_building', 'Building Name', 'trim|required|max_length[50]|callback_check_inavlid_char');
        //$this->form_validation->set_rules('txt_Store','Store name','trim|required|max_length[100]|callback_check_inavlid_char');
        $this->form_validation->set_rules('txt_vehicle_no', 'Vehicle number', 'trim|required|max_length[50]|callback_check_inavlid_char');
        $this->form_validation->set_rules('select_vehicle_type', 'Vehicle type', 'trim|required');

        if (empty($_FILES['txt_doc_mulkiya']['name'])) {
            $this->form_validation->set_rules('txt_doc_mulkiya', 'Upload Document', 'trim|required');
        }

        if (empty($_FILES['txt_driving_doc']['name'])) {
            $this->form_validation->set_rules('txt_driving_doc', 'Upload Document', 'trim|required');
        }


        if ($this->form_validation->run() == FALSE) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_first_name' => form_error('txt_first_name'),
                'txt_last_name' => form_error('txt_last_name'),
                'txt_email' => form_error('txt_email'),
                //'txt_user_id' => form_error('txt_user_id'),
                // 'radio_gender' => form_error('radio_gender'),
                'select_country' => form_error('select_country'),
                'txt_password' => form_error('txt_password'),
                'select_city' => form_error('select_city'),
                'txt_Phone' => form_error('txt_Phone'),
                'txt_Land_Phone' => form_error('txt_Land_Phone'),
                'txt_location' => form_error('txt_location'),
                'txt_street' => form_error('txt_street'),
                'txt_building' => form_error('txt_building'),
                //'txt_Store' => form_error('txt_Store'),
                'txt_vehicle_no' => form_error('txt_vehicle_no'),
                'select_doc_type' => form_error('select_doc_type'),
                'txt_driving_doc' => form_error('txt_driving_doc'),
                'txt_doc_mulkiya' => form_error('txt_doc_mulkiya'),
            );
            echo json_encode($data);
            exit();
        }

        $_POST = $this->security->xss_clean($_POST);


        if (count($_POST) > 0) {
            $result         =   $this->M_admin->saveDriverDetails($_POST);
        } else {
            $result =  0;
        }

        $data['status'] = $result;
        echo json_encode($data);
    }

    public function updateVendorDriver()
    {

        $data = array();

        $this->form_validation->set_rules('txt_first_name', 'First name', 'trim|required|max_length[100]|xss_clean|callback_alpha_space');
        $this->form_validation->set_rules('txt_last_name', 'Last name', 'trim|required|max_length[100]|xss_clean|callback_alpha_space');
        $this->form_validation->set_rules('txt_email', 'Email Address', 'trim|required|valid_email|max_length[100]');
        $this->form_validation->set_rules('radio_gender', 'Gender', 'trim|required');
        $this->form_validation->set_rules('select_country', 'Country', 'trim|required');
        //$this->form_validation->set_rules('txt_password', 'Password', 'trim|required|min_length[8]|max_length[20]|callback_valid_password');
        $this->form_validation->set_rules('select_city', 'City', 'trim|required');
        $this->form_validation->set_rules('txt_Phone', 'Phone', 'trim|required|numeric|min_length[5]|max_length[10]|xss_clean');

        $this->form_validation->set_rules('txt_location', 'Location', 'trim|required|max_length[150]');
        $this->form_validation->set_rules('txt_street', 'Street Name', 'trim|required|max_length[150]|callback_check_inavlid_char');
        $this->form_validation->set_rules('txt_building', 'Building Name', 'trim|required|max_length[50]|callback_check_inavlid_char');
        //$this->form_validation->set_rules('txt_Store','Store name','trim|required|max_length[100]|callback_check_inavlid_char');
        $this->form_validation->set_rules('txt_vehicle_no', 'Vehicle number', 'trim|required|max_length[50]|callback_check_inavlid_char');
        $this->form_validation->set_rules('select_vehicle_type', 'Vehicle type', 'trim|required');

        // if(empty($_FILES['txt_doc_mulkiya']['name'])) {
        //     $this->form_validation->set_rules('txt_doc_mulkiya','Upload Document','trim|required');
        // }

        // if(empty($_FILES['txt_driving_doc']['name'])) {
        //     $this->form_validation->set_rules('txt_driving_doc','Upload Document','trim|required');
        // }


        if ($this->form_validation->run() == FALSE) {
            $data['status'] = 0;
            $data['errors'] = array(
                'txt_first_name' => form_error('txt_first_name'),
                'txt_last_name' => form_error('txt_last_name'),
                'txt_email' => form_error('txt_email'),
                //'txt_user_id' => form_error('txt_user_id'),
                'radio_gender' => form_error('radio_gender'),
                'select_country' => form_error('select_country'),
                'txt_password' => form_error('txt_password'),
                'select_city' => form_error('select_city'),
                'txt_Phone' => form_error('txt_Phone'),
                'txt_Land_Phone' => form_error('txt_Land_Phone'),
                'txt_location' => form_error('txt_location'),
                'txt_street' => form_error('txt_street'),
                'txt_building' => form_error('txt_building'),
                //'txt_Store' => form_error('txt_Store'),
                'txt_vehicle_no' => form_error('txt_vehicle_no'),
                'select_doc_type' => form_error('select_doc_type'),
                //'txt_driving_doc' => form_error('txt_driving_doc'),
                //'txt_doc_mulkiya' => form_error('txt_doc_mulkiya'),
            );
            echo json_encode($data);
            exit();
        }

        $_POST = $this->security->xss_clean($_POST);


        if (count($_POST) > 0) {
            $result         =   $this->M_admin->saveDriverDetails($_POST);
        } else {
            $result =  0;
        }

        $data['status'] = $result;
        echo json_encode($data);
    }


    function addEditArabicProduct()
    {

        $id   =   (int) $this->M_product->decryptId($this->uri->segment(2));

        $data["basic_list"]           =   $this->M_product->getProductBasicListById($id);
        $this->load->view("vendor/add_products_scripts");
        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("admin/add_edit_product_arabic", $data);
        $this->load->view("vendor/footer");
    }
    function loadThankuReport()
    {
        $condition                    =    array("user_type" => "U");
        $data["thank_list"]           =   $this->M_admin->thankuReport($condition);

        $this->load->view("vendor/add_products_scripts");
        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("admin/thanku_report", $data);
        $this->load->view("vendor/footer");
    }
    function loadPromotReport()
    {
        $condition                    =    array("user_type" => "U");
        $data["thank_list"]           =   $this->M_admin->promotedCommissionReport($condition);

        $this->load->view("vendor/add_products_scripts");
        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("admin/promo_commission_report", $data);
        $this->load->view("vendor/footer");
    }
    function loadCelebrityPerc()
    {
        $data   =  array();
        $val    =  array();
        $this->load->model('M_user');
        $resultSearch   =    $this->M_user->getCelibrityUsers($val);
        $param    =  array('user_id' => $this->session->userdata('user_id'));
        $data["productList"]           =   $this->M_product->getProductNameId($param);
        $data["celebrityList"]         =   $resultSearch;

        $id = $this->uri->segment(2);

        //exit;
        if ($id > 0) {
            $data["activePerc"]            =   $this->M_product->getCelibrityPerc($id);
        } else {
            $data["activePerc"]            = array();
        }


        // print_r($data["activePerc"]);

        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("vendor/celebrity_percentage", $data);
        $this->load->view("vendor/footer");
    }
    function saveCelebriyPerc()
    {
        $this->form_validation->set_rules('celebrity_combo[]', 'Celebrity', 'trim|required');
        $this->form_validation->set_rules('product_combo[]', 'Product', 'trim|required');
        $this->form_validation->set_rules('txt_sale_datefrom', 'Date from', 'trim|required');
        $this->form_validation->set_rules('txt_sale_dateto', 'Date to', 'trim|required');
        $this->form_validation->set_rules('txt_perc', 'Percentage', 'trim|required');
        if ($this->form_validation->run() == FALSE) {
            $data['status'] = 0;
            $data['errors'] = array(
                'celebrity_combo[]' => form_error('celebrity_combo[]'),
                'product_combo[]' => form_error('product_combo[]'),
                'txt_sale_datefrom' => form_error('txt_sale_datefrom'),
                'txt_sale_dateto' => form_error('txt_sale_dateto'),
                'txt_perc' => form_error('txt_perc')
            );
            echo json_encode($data);
            exit();
        }

        $_POST = $this->security->xss_clean($_POST);
        $result =    $this->M_product->saveCelebriyPerc($_POST);

        // print_r($result);
        if ($result->perc_id > 0) {
            $data['status']  = 3;
            $data['message'] = "Active percentage already exists for product " . $result->product_name . " and celebrity " . $result->user_first_name . " " . $result->user_last_name;
        } else {
            $data['status'] = $result;
        }

        //print_r($result);

        echo json_encode($data);
    }
    function loadCelebrityPercList()
    {

        $data = array();

        //$data['result']  = $this->M_admin->getAllCelebrityPerc();

        $this->load->view("vendor/header");
        $this->load->view("vendor/sidebar");
        $this->load->view("vendor/celebrity_perc_list", $data);
        $this->load->view("vendor/footer");
    }
    function listCelebrityPercAjax()
    {



        // print_r($_POST);

        $this->load->library('pagination');




        $limit_per_page             =    $_POST['limit_per_page'] > 0 ? $_POST['limit_per_page'] : 10;
        $start_index                 =     ($this->uri->segment(4) > 0 ? ($this->uri->segment(4) - 1) * $limit_per_page : 0);
        $records                     =     $this->M_admin->getAllCelebrityPercCount($_POST);
        $total_records                =    $records->count;

        if ($total_records > 0) {

            $data['result']  =   $this->M_admin->getAllCelebrityPerc($_POST, $limit_per_page, $start_index);

            $config['base_url']         =     base_url() . 'vendor/C_vendor/listCelebrityPercAjax';
            $config['total_rows']         =     $total_records;
            $config['per_page']         =     $limit_per_page;
            $config["uri_segment"]         =     4;

            // custom paging configuration
            $config['num_links']             =     2;
            $config['use_page_numbers']     =     TRUE;
            $config['reuse_query_string']     =     TRUE;

            $config['full_tag_open']         =     '<ul class="pagination">';
            $config['full_tag_close']         =     '</ul>';

            $config['first_link']             =     $this->lang->line('first');
            $config['first_tag_open']         =     '<li>';
            $config['first_tag_close']         =     '</li>';

            $config['last_link']             =     $this->lang->line('last');
            $config['last_tag_open']         =     '<li>';
            $config['last_tag_close']         =     '</li>';

            $config['next_link']             =     '&gt;';
            $config['next_tag_open']         =     '<li>';
            $config['next_tag_close']         =     '</li>';

            $config['prev_link']             =     '&lt;';
            $config['prev_tag_open']         =     '<li>';
            $config['prev_tag_close']         =     '</li>';

            $config['cur_tag_open']         =     '<li class="active"><span>';
            $config['cur_tag_close']         =     '</span></li>';

            $config['num_tag_open']         =     '<li>';
            $config['num_tag_close']         =     '</li>';
            $config["num_links"]                        =     6;

            $this->pagination->initialize($config);


            $data["links"] = $this->pagination->create_links();
        }



        $this->load->view("vendor/celebrity_perc_list_ajax", $data);
    }
    public  function check_inavlid_char($string = "")
    {
        $regex_special = '/[!@#$%^&*()\=+{};:<.>§~]/';


        if (preg_match_all($regex_special, $string) > 0) {
            $this->form_validation->set_message('check_inavlid_char', 'The {field} field contains invalid characters.');
            return FALSE;
        }
        return TRUE;
    }
    function valid_url($url)
    {
        $pattern = "/^((ht|f)tp(s?)\:\/\/|~/|/)?([w]{2}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?/";
        if (!preg_match($pattern, $url)) {
            return FALSE;
        }

        return TRUE;
    }
    function alpha_space($fullname)
    {
        if (!preg_match('/^[a-zA-Z\s]+$/', $fullname)) {
            $this->form_validation->set_message('alpha_space', 'The %s field may only contain alpha characters & White spaces');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    /**
     * My Earnings
     */
    public function earningsList( $page=1 )
    {
        $page = ( !$page || $page < 0 ) ? 1 : $page;
        $limit = $this->input->post('search_limit', true) ?? 10;

        $this->addData([
            'header_section' => 'earnings_listing',
            'footer_section' => 'earnings_listing',
            'page' => $page,
            'limit' => $limit,
        ]);

        $this->validateLogin();
        $this->addMetaTitle('My Earnings');
        $this->addBreadCrumb(
            [current_url(), 'My Earnings']
        );
        $this->setSidebarActiveMenu('my_earnings');
        $this->addAssets([
            'footer' => [
                'vendor/my_earnings_footer_assets',
            ]
        ]);

        $start_date = $this->input->get('sdate', true);
        $end_date = $this->input->get('edate', true);
        $condition = compact('start_date', 'end_date');

        $earnings = $this->M_product->getVendorEarnings($this->vendor_user->user_id, NULL, $condition);

        $total_sales = 0;
        $total_earnings = 0;
        $total_paid = 0;

        foreach ($earnings as $row) {
            $total_sales += $row->total_sale;
            $total_earnings += $row->earning;
            if ( $row->vendor_commission_paid ) {
                $total_paid += $row->earning;
            }
        }

        $this->addData(compact('total_sales', 'total_paid', 'total_earnings', 'earnings', 'start_date', 'end_date'));

        $this->render('vendor/my_earnings');
    }

    public function vendorEarningsDownload()
    {
        $this->validateLogin();

        $start_date = $this->input->get('sdate', true);
        $end_date = $this->input->get('edate', true);
        $condition = compact('start_date', 'end_date');

        $earnings = $this->M_product->getVendorEarnings($this->vendor_user->user_id, NULL, $condition);

        $fileName = 'My Earnings.xls';

        // headers for download
        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/vnd.ms-excel");

        function filterData(&$str)
        {
            $str = preg_replace("/\t/", "\\t", $str);
            $str = preg_replace("/\r?\n/", "\\n", $str);
            if (strstr($str, '"')) {
                $str = '"' . str_replace('"', '""', $str) . '"';
            }
        }

        $flag = false;
        $i = 1;

        foreach ($earnings as $row) {
            if (!$flag) {
                // display column names as first row
                echo implode("\t", array('#', 'Order No', 'Order Date', 'Total Sales', 'Earnings', SITE_NAME .' Commission', 'Earned Date', 'Status', 'Requested On', 'Paid On')) . "\n";
                $flag = true;
            }
            // filter data
            array_walk($row, 'filterData');

            $earnedDate = get_date_in_timezone("Asia/Dubai", $row->earned_date, "F j, Y, g:i a");
            $requestedDate = "";
            if (! empty($row->vendor_commission_request_withdrawal_date) ) {
                $requestedDate = get_date_in_timezone("Asia/Dubai", $row->vendor_commission_request_withdrawal_date, "F j, Y, g:i a");
            }
            $paidDate = "";
            if (! empty($row->vendor_commission_paid_date) ) {
                $paidDate = get_date_in_timezone("Asia/Dubai", $row->vendor_commission_paid_date, "F j, Y, g:i a");
            }
            $orderDate = get_date_in_timezone('Asia/Dubai', $row->order_placed_date, 'j M Y');

            $status = 'Pending';
            if ( $row->vendor_commission_paid ) {
                $status = 'Paid';
            } elseif ($row->vendor_commission_request_withdrawal) {
                $status = 'Requested to Withdraw';
            }
            
            echo implode("\t", array($i, $row->order_no, $orderDate, number_format($row->total_sale, 2), number_format($row->earning, 2, '.', ','), number_format($row->khiat_commission, 2, '.', ','), $earnedDate, $status, $requestedDate, $paidDate)) . "\n";

            $i++;
        }

        exit;
    }

    public function requestEarningsWithdrawal()
    {
        $order_block_id = (int) $this->input->post('order_block_id', true);
        $status = "0";
        $message = "";

        $earning = $this->M_product->getVendorEarnings($this->vendor_user->user_id, $order_block_id);
        if ( $earning ) {
            $earning = $earning[0];

            if ( $earning->vendor_commission_paid ) {
                $message = "Already paid";
            } elseif ( $earning->vendor_commission_request_withdrawal ) {
                $message = "Already requested";
            } else {
                $status = $this->M_product->requestVendorEarningsWithdrawal($this->vendor_user->user_id, $order_block_id);
            }
        }

        $this->addData(compact('status', 'message'));

        $this->render('json');
    }
    public function vendor_stores()
    {
        $this->validateLogin();
        $this->addMetaTitle('Stores');
        $this->addBreadCrumb(
            [current_url(), 'Stores']
        );
        $this->setSidebarActiveMenu('stores');
        $list = $this->Common->get_contents('vendor_stores',array('vendor_user_id'=>$this->vendor_user->user_id));
        
        $sidebar_active_parent_menu = "vendor_stores";
        $this->addData(compact('sidebar_active_parent_menu'));
        $this->addData([
            'footer_section' => 'vendor_dashboard',
            'list'      =>  $list
        ]);

        $this->addAssets([
            'footer' => [
                'vendor/stores_footer_assets',
            ]
        ]);

        $this->render('vendor/stores');
    }
    public function create_store($id='')
    {
        $this->validateLogin();
        $this->addMetaTitle('Stores');
        $this->addBreadCrumb(
            [current_url(), 'Stores']
        );
        $this->setSidebarActiveMenu('stores');

        $page_heading = "Add New Store";
        $store_name     =   "";
        $store_name_arabic      =   "";
        $user_email     =   "";
        $dial_code      =   "";
        $mobile_no      =   "";
        $about_store_english        =   "";
        $about_store_arabic     =   "";
        $location       =   "";
        $latitude       =   "";
        $longitude      =   "";
        $vendor_store_id=   "";
        $address        =   "";
        $street_name    =   "";
        $building   =   "";
        if($id){
            $page_heading = "Edit Store";
            $single = $this->Common->get_all_by_need('vendor_stores',array('*'),array('vendor_store_id'=>$id));
            $store_name     =   $single->store_name_english;
            $store_name_arabic       =   $single->store_name_arabic;
            $user_email     =   $single->email;
            $dial_code       =   $single->dial_code;
            $mobile_no       =   $single->phone;
            $about_store_english           =   $single->about_store_english;
            $about_store_arabic     =   $single->about_store_arabic;
            $location         =   $single->location;
            $latitude         =   $single->latitude;
            $longitude       =   $single->longitude;
            $vendor_store_id   =  $single->vendor_store_id;
            $address            =   $single->address;
            $street_name    =  $single->street;
            $building   =   $single->building;
        }
        $this->addData(compact(
            'store_name',
            'store_name_arabic',
            'user_email',
            'dial_code',
            'mobile_no',
            'about_store_english',
            'about_store_arabic',
            'location',
            'latitude',
            'longitude',
            'vendor_store_id',
            'address',
            'street_name',
            'building'
        ));
        $this->addData([
            'footer_section' => 'vendor_dashboard',
            'page_heading'   => $page_heading
        ]);
        $sidebar_active_parent_menu = "vendor_stores";
        $this->addData(compact('sidebar_active_parent_menu'));
        $this->addAssets([
            'footer' => [
                'vendor/stores_footer_assets',
            ]
        ]);

        $this->render('vendor/create_stores');
    }
    public function does_phone_exists( $phone_number )
    {
        if (! empty($phone_number) ) {
            $id             = (int) $this->input->post('id', true);
            $dial_code      = trim($this->input->post("dial_code", true));
            $phone_number   = trim($this->input->post("mobile_no", true));

            
            $user_phone_row = $this->Common->get_all_by_need('vendor_stores',array('*'),array('vendor_store_id !='=>$id,'dial_code'=>$dial_code,'phone'=>$phone_number));
            if ( $user_phone_row ) {
                $this->form_validation->set_message('does_phone_exists', 'Phone number already registered.');
                return FALSE;
            }
        }

        return TRUE;
    }
    public function does_email_exists( $email_id )
    {
        if (! empty($email_id) ) {
            $id             = (int) $this->input->post('id', true);
            $email_id   = trim($this->input->post("email_id", true));

            
            $user_phone_row = $this->Common->get_all_by_need('vendor_stores',array('*'),array('vendor_store_id !='=>$id,'email'=>$email_id));
            if ( $user_phone_row ) {
                $this->form_validation->set_message('does_email_exists', 'Email Id already registered.');
                return FALSE;
            }
        }

        return TRUE;
    }
    public function add_store(){
        if($this->input->is_ajax_request()){
            $status  = "0";
            $message = "";  
            $this->form_validation->set_error_delimiters('', '');
            $this->form_validation->set_message('required', 'This field is required');

            $this->form_validation->set_rules('store_name', 'Store Name', 'trim|required|max_length[150]');
            $this->form_validation->set_rules('email_id', 'Email Id', 'trim|required|valid_email|max_length[100]|callback_does_email_exists');
            $this->form_validation->set_rules('mobile_no', 'Phone Number', 'trim|required|numeric|min_length[5]|max_length[10]|callback_does_phone_exists');
            //$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
            //$this->form_validation->set_rules('country', 'Country', 'trim|required');
           // $this->form_validation->set_rules('city', 'City', 'trim|required');
            //$this->form_validation->set_rules('user_type', 'User Type', 'trim|required');
            $this->form_validation->set_rules('location', 'Location', 'trim|required');
            

            if ($this->form_validation->run() == FALSE ) {
                $status = "0";
                $errors = [
                    'store_name'          => form_error('store_name'),
                    'email_id'                 => form_error('email_id'),
                    'mobile_no'          => form_error('mobile_no'),
                    'location'              => form_error('location')
                ];
                $message = "Please Fill all required fields";
                $this->addData(compact('errors'));

            } else {
                $id             = (int) $this->input->post('id', true);
                $email_id     = $this->input->post('email_id', true);
                $store_name   = $this->input->post("store_name");
                $store_name_arabic = $this->input->post("store_name_arabic");
                $dial_code    = $this->input->post("dial_code");
                $mobile_no    = $this->input->post("mobile_no");
                $about_store_english = $this->input->post("about_store_english");
                $about_store_arabic  = $this->input->post("about_store_arabic");
                $location     = $this->input->post("location");
                $latitude     = $this->input->post("latitude");
                $longitude    = $this->input->post("longitude");
                $street_name  = $this->input->post("street_name");
                $building_no  = $this->input->post("building_no");
                $address      = $this->input->post("address");

                $ins          = array(
                    'vendor_user_id'        =>      $this->vendor_user->user_id,
                    'store_name_english'    =>      $store_name,
                    'store_name_arabic'     =>      $store_name_arabic,
                    'email'                 =>      $email_id,
                    'dial_code'             =>      $dial_code,
                    'phone'                 =>      $mobile_no,
                    'address'               =>      $address,
                    'location'              =>      $location,
                    'latitude'              =>      $latitude,
                    'longitude'             =>      $longitude,
                    'street'                =>      $street_name,
                    'about_store_arabic'    =>      $about_store_arabic,
                    'about_store_english'   =>      $about_store_english,
                    'building'              =>      $building_no,
                    'updated_at'            =>      date('Y-m-d H:i:s')
                );
                if($id){
                    $this->db->trans_start();
                        $this->Common->update('vendor_stores',$ins,array('vendor_store_id'=>$id));
                    $this->db->trans_complete();
                    if ($this->db->trans_status() === false) {
                        $this->db->trans_rollback();
                        $message  = "Something went wrong Please try again after sometimes";
                    }else{
                        $status="1";
                        $message = "Store Updated successfully";
                    }
                }else{
                    $this->db->trans_start();
                        $ins['created_at']=date("Y-m-d H:i:s");
                        $this->Common->insert('vendor_stores',$ins);
                    $this->db->trans_complete();
                    if ($this->db->trans_status() === false) {
                        $this->db->trans_rollback();
                        $message  = "Something went wrong Please try again after sometimes";
                    }else{
                        $status="1";
                        $message = "Store added successfully";
                    }
                }
            }
            $this->addData(compact('status', 'message'));
            $this->render('json');
        }else{
            redirect('vendor/vendor_stores','refresh');
        }
    }
    public function delete_store(){
        echo $id= $this->input->post("store_id");
        $ret=$this->Common->delete('vendor_stores',array('vendor_store_id'=>$id,'vendor_user_id'=>$this->vendor_user->user_id));
        if($ret){
            echo "1";
        }else{
            echo "0";
        }
    }
    
    public function getCitysByCountry(){
        $language = ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $select_country = $this->input->post('select_country');
        $condition = array('city_language_code' => $language, 'city_status' => 1, 'city_country_id' => $select_country);
        $city_list = $this->M_admin->getCitiesCondition($condition);
        echo json_encode($city_list);
    }


    public function timeSlot()
    {
        $this->validateLogin();
        $this->addMetaTitle('Time Slot');

        $this->addBreadCrumb([current_url(), 'Time Slot']);

        $this->setSidebarActiveMenu('my_timeslot');

        $timeSlotList = $this->M_admin->getStoreTimeSlots(['store_id'=>$this->vendor_user->user_id])->result();

        $this->addAssets([
            'footer' => [
                'vendor/timeslot_footer_assets'
            ]
        ]);

        $this->addData(['timeSlotList' => $timeSlotList]);
        $this->render('vendor/store_time_slot');
    }

    public function addEditTimeslot()
    {
        $language   =  ($this->session->userdata('language') ? $this->session->userdata('language') : 1);
        $this->setSidebarActiveMenu('my_timeslot');

        $this->addAssets([
            'footer' => [
                'vendor/timeslot_footer_assets'
            ]
        ]);

        $this->render('vendor/add_edit_time_slot');
    }

    public function saveTimeslot()
    {
        $status = 0;
        $this->form_validation->set_rules('day_id', 'Day Name', 'trim|required');
        $this->form_validation->set_rules('time_slot', 'Time Slot', 'trim|required|callback_is_unique_time_slot');
        
        if ($this->form_validation->run() == false)
        {
            $data['status'] = 0;
            $data['errors'] = array(
                'day_id' => form_error('day_id'),
                'time_slot' => form_error('time_slot')
            );
            echo json_encode($data);
            exit();
        }
        else
        {
            $_POST['store_id'] = (int)$this->vendor_user->user_id;
            $result = $this->M_admin->saveTimeslot($_POST);

            if($result)
                $status = 1;
        }

        echo json_encode(['status'=>$status]);
    }

    public function is_unique_time_slot( $store_id )
    {
        if (! empty($store_id) ) {
            $id = (int)$this->input->post('id', true);
            
            $condition = [
                'store_id'=>(int)$this->vendor_user->user_id,
                'day_id'=>(int)$this->input->post('day_id', true),
                'time_slot'=>(string)$this->input->post('time_slot', true)
            ];
            
            if(!empty($id))
            {
                $condition['slot_id !='] = $id;
            }

            $isExists = $this->M_admin->getStoreTimeSlots($condition)->row();
            if ( $isExists ) {
                $this->form_validation->set_message('is_unique_time_slot', 'This time slot already added for the this store.');
                return FALSE;
            }
        }
        return TRUE;
    }
}
