<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Producer extends MY_Controller {

    var $cats;
    var $thispage;

    public function __construct() {
        parent::__construct();
        if (!get_license_per('products') && strtolower($this->router->fetch_method()) != 'clint_blacklist' && strtolower($this->router->fetch_method()) != 'delete_absent') {
            redirect("", "refresh");
        }
        $this->load->model('booking');
        $this->thispage = "producer";
        $this->operator_id = $this->session->userdata('operator_id');
//        if (get_ap('producer', $this->operator_id) == 1) {
//            
//        } else {
//            redirect("", "refresh");
//        }
    }

    public function index($cats = 1) {
        if (!(get_ap('product', $this->operator_id) == 1))
            redirect("", "refresh");

        $this->cats = $cats;
        $this->all($cats, 1);
    }

    public function all($page = 1, $all = '') {

        $searchfor = $this->security->xss_clean($this->input->get('search'));
        $whr = "";
        if (!$this->session->userdata('group'))
            $whr = "cid='ddd'";


        $this->db->from('bills_producer');
        if ($whr)
            $this->db->where($whr);
        $max = 40;

        $data['all_count'] = ceil($this->db->count_all_results() / $max);

        $this->db->from('bills_producer');
        $this->db->order_by('id', 'desc');
        if ($whr)
            $this->db->where($whr);

        // $this->db->limit($max, ($max * $page) - $max);

        $data['all_groups'] = $this->db->get()->result_array();


        if ($searchfor) {
            $this->booking->add_rep_user("  البحث عن    " . $searchfor);
            $split_stemmed = explode(" ", $searchfor);
            $whr = " (";
            while (list($key, $val) = @each($split_stemmed)) {
                if ($val <> " " and strlen($val) > 0) {

                    $whr .= " ( BINARY name LIKE '%" . $val . "%'   ) and";
                }
            }
            $whr = substr($whr, 0, (strLen($whr) - 4));
            $whr .= " )or     cid LIKE '" . $searchfor . "'  OR  mobile = '" . $searchfor . "'";

            if (!$this->session->userdata('group'))
                $whr = " cid LIKE '" . $searchfor . "'  OR  mobile = '" . $searchfor . "'";

            $query = $this->db->query('SELECT * FROM bills_producer where ' . $whr);
            $data['all_count'] = 0;
            $whr = '';
            $data['all_groups'] = $query->result_array();
            $data['all_count'] = count($data['all_groups']);
            // echo print_r($this->db->last_query());
        }
        /// $whr=" cid LIKE '" . $searchfor . "'  OR  mobile = '" . $searchfor . "'";






        $i = 0;
        foreach ($data['all_groups'] as $row) {
            $data['all_groups'][$i]['cat'] = '';
            $cat_exist = $this->db->from('product_categories')->where("id=" . $row['cat_id'])->get()->row();
            if ($cat_exist) {
                $data['all_groups'][$i]['cat'] = $cat_exist->name;
            }
            $i++;
        }
        $data['title'] = $this->lang->line('products');
        // $data['view'] = '../controllers/views/' . $this->thispage . '/all';
        $data['thispage'] = $this->thispage;
        $this->load->view('site/producer/all', $data);
    }

    public function orders() {
        if (!get_license_per('sales')) {
            redirect("", "refresh");
        }
        if (!(get_ap('bill', $this->operator_id) == 1))
            redirect("", "refresh");
        $result = $this->db->update('bills_orders', array('active' => '1'));

        $this->db->from('bills_orders');
        $this->db->order_by('id', 'desc');
        $this->db->where("`start_date_t` < " . (time()) . "  and expiry_date_t >=" . (time()) . "");
        $data['all_groups'] = $this->db->get()->result_array();
        foreach ($data['all_groups'] as $row) {

            $this->db->where('id', $row['id'])->update('bills_orders', array('active' => '0'));
        }


        $searchfor = $this->security->xss_clean($this->input->get('search'));
        $whr = "";



        $this->db->from('bills_producer');
        if ($whr)
            $this->db->where($whr);
        $max = 40;

        $data['all_count'] = ceil($this->db->count_all_results() / $max);

        $this->db->from('bills_producer');
        $this->db->order_by('id', 'ASC');
        if ($whr)
            $this->db->where($whr);

        ///$this->db->limit($max, ($max * $page) - $max);

        $data['all_groups'] = $this->db->get()->result_array();
        $i = 0;
        foreach ($data['all_groups'] as $row) {


            $data['all_groups'][$i]['bills_orders'] = $this->db->from('bills_orders')->where("id_producer='" . $row['id'] . "' and active='0'")->count_all_results();

            $data['all_groups'][$i]['bills_orders2'] = $this->db->from('bills_orders')->where("id_producer='" . $row['id'] . "' and active='1'")->count_all_results();
            $data['all_groups'][$i]['payment'] = $this->sum_bill($row['id']);
            $data['all_groups'][$i]['discount'] = $this->sum_discount($row['id']);

            $data['all_groups'][$i]['discount_remainder'] = $this->sum_discount_remainder($row['id']);


            $i++;
            //$data['all_groups']['allcat']=$this->db->from('cat')->where("parentcatid=".$row['catid'])->count_all_results();
        }
        $data['title'] = $this->lang->line('products');
        // $data['view'] = '../controllers/views/' . $this->thispage . '/orders';
        $data['thispage'] = $this->thispage;
        $this->load->view('site/' . $this->thispage . '/orders', $data);
    }

    function sum_bill($catid, $knet = '') {
        $this->db->select_sum('payment');
        $this->db->where(" id_producer=$catid ");

        $query = $this->db->get('bills_orders')->row_array();
        if (!$query['payment'])
            $query['payment'] = 0;
        return $query['payment'];
    }

    function sum_discount($catid, $knet = '') {
        $this->db->select_sum('discount');
        $this->db->where(" id_producer=$catid ");

        $query = $this->db->get('bills_orders')->row_array();
        if (!$query['discount'])
            $query['discount'] = 0;
        return $query['discount'];
    }

    function sum_discount_remainder($catid, $knet = '') {
        $this->db->select_sum('discount_remainder');
        $this->db->where(" id_producer=$catid ");

        $query = $this->db->get('bills_orders')->row_array();
        if (!$query['discount_remainder'])
            $query['discount_remainder'] = 0;
        return $query['discount_remainder'];
    }

    public function add($cats = 1) {
        if (!(get_ap('product_add', $this->operator_id) == 1))
            redirect("", "refresh");
        $add = FALSE;
        $this->cats = $cats;
        if ($this->input->post('submit')) {
            $this->form_validation->set_rules('valuess', '', 'trim|required');
            $this->form_validation->set_rules('name', '', 'trim|required');
            $this->form_validation->set_rules('category', '', 'trim|required');

            //	$this->form_validation->set_rules('comment', '', 'trim|required'); 
            //	$this->form_validation->set_rules('comm', '', 'trim|required'); 


            if ($this->form_validation->run() === FALSE) {

                $add = FALSE;
            } else {

                $add = TRUE;
                $data = array(
                    'valuess' => $this->input->post('valuess'),
                    'name' => $this->input->post('name'),
                    'arabic_name' => $this->input->post('arabic_name'),
                    'details_eng' => $this->input->post('details_eng'),
                    'details_ar' => $this->input->post('details_ar'),
                    'active' => $this->input->post('active'),
                    'note' => $this->input->post('note'),
                    'cat_id' => $this->input->post('category'),
                    'type' => $this->input->post('type'),
                    'brand' => $this->input->post('brand'),
                    'code' => $this->input->post('code'),
                    'barcode_symbology' => $this->input->post('barcode_symbology')
                );
                $data = $this->security->xss_clean($data);
                $result = $this->db->insert('bills_producer', $data);
                $product_id = $this->db->insert_id();
                // add additions
                if (get_ap('product_additions', $this->operator_id)) {
                    for ($i = 0; $i < count($this->input->post('eng_title[]')); $i++) {
                        $data = array(
                            'product_id' => $product_id,
                            'title_en' => $this->input->post('eng_title')[$i],
                            'title_ar' => $this->input->post('ar_title')[$i],
                            'choice_type' => $this->input->post('choice_type')[$i],
                            'required' => $this->input->post('required')[$i],
                        );
                        $j = 0;
                        foreach ($this->input->post('options') as $option) {
                            if ($i == $j) {
                                $data['options'] = implode(',', $option);
                            }
                            $j++;
                        }
                        $data = $this->security->xss_clean($data);
                        $this->db->insert('product_additions', $data);
                    }
                }
                if ($result) {
                    $this->session->set_flashdata('msg', 'تم اضافةالمنتج بفضل الله!');
                    redirect(base_url('' . $this->thispage . '/index/'));
                }
            }
        }


        if (!$add) {
            $data['title'] = 'اضافة عميل';
            $data['cats'] = $this->cats;
            $data['thispage'] = $this->thispage;
            $data['cats'] = $this->db->get('product_categories')->result();
            $this->db->select('distinct(brand) as brand');
            $data['brands'] = $this->db->get('bills_producer')->result();
            $data['adds'] = $this->db->get_where('additions', array('active' => 1))->result();
            $this->db->select('distinct group_name', FALSE);
            $data['group_name'] = $this->db->get_where('additions', array('active' => 1))->result();
            // $data['view'] = '../controllers/views/' . $this->thispage . '/add';
            $this->load->view('site/' . $this->thispage . '/add', $data);
        }
    }

    public function show($id) {
        if (!(get_ap('product', $this->operator_id) == 1))
            redirect("", "refresh");
        $this->db->select('bills_producer.*,product_categories.name as cat_name', FALSE);
        $this->db->join('product_categories', 'product_categories.id=bills_producer.cat_id', 'left', FALSE);
        $query = $this->db->get_where('bills_producer', array('bills_producer.id' => $id));

        $this->db->select('name,count(id) as invoice_count');
        $this->db->group_by('id_user,name');
        $data['users'] = $this->db->get_where('bills_orders', array('id_producer' => $id))->result();
        $data['show'] = $query->row_array();
        $add = FALSE;
        $data['title'] = $this->lang->line('show') . ' ' . $this->lang->line('products');
        $data['thispage'] = $this->thispage;
        // $data['view'] = '../controllers/views/' . $this->thispage . '/show';
        $this->load->view('site/producer/show', $data);
    }

    public function del($id) {
        if (!(get_ap('product_del', $this->operator_id) == 1))
            redirect("", "refresh");
        $query = $this->db->get_where('bills_producer', array('id' => $id));
        $data['edit'] = $query->row_array();


        $this->db->where('id', $id);
        $result = $this->db->delete('bills_producer');
        if (count($result) > 0) {
            $this->session->set_flashdata('msg', 'تم حذف  القسم بفضل الله!');
            redirect(base_url('producer/index/'));
        }
    }

    public function edit($id) {
        if (!(get_ap('product_edit', $this->operator_id) == 1))
            redirect("", "refresh");
        $query = $this->db->get_where('bills_producer', array('id' => $id));
        $data['edit'] = $query->row_array();

        $data['edit']['checked'] = array('', '', '', '', '', '', '', '', '');


        $data['edit']['checked'][$data['edit']['active']] = 'checked';
        $data['edit']['checked'][$data['edit']['type'] + 3] = 'checked';
        $add = FALSE;
        if ($this->input->post('submit')) {
            $this->form_validation->set_rules('valuess', '', 'trim|required');
            $this->form_validation->set_rules('name', '', 'trim|required');
            $this->form_validation->set_rules('category', '', 'trim|required');
            //	$this->form_validation->set_rules('comment', '', 'trim|required'); 
            //	$this->form_validation->set_rules('comm', '', 'trim|required'); 


            if ($this->form_validation->run() === FALSE) {

                $add = FALSE;
            } else {
                //  print_R($this->input->post());die;
                $add = TRUE;
                $edit_data = array(
                    'valuess' => $this->input->post('valuess'),
                    'name' => $this->input->post('name'),
                    'arabic_name' => $this->input->post('arabic_name'),
                    'details_eng' => $this->input->post('details_eng'),
                    'details_ar' => $this->input->post('details_ar'),
                    'active' => $this->input->post('active'),
                    'note' => $this->input->post('note'),
                    'cat_id' => $this->input->post('category'),
                    'type' => $this->input->post('type'),
                    'brand' => $this->input->post('brand'),
                    'code' => $this->input->post('code'),
                    'barcode_symbology' => $this->input->post('barcode_symbology')
                );
                $edit_data = $this->security->xss_clean($edit_data);
                $result = $this->db->where('id', $id)->update('bills_producer', $edit_data);

                // add additions
                if (get_ap('product_additions', $this->operator_id)) {
                    $this->db->delete('product_additions', array('product_id' => $id));
                    for ($i = 0; $i < count($this->input->post('eng_title[]')); $i++) {
                        if ($this->input->post('eng_title')[$i]) {
                            $data = array(
                                'product_id' => $id,
                                'title_en' => $this->input->post('eng_title')[$i],
                                'title_ar' => $this->input->post('ar_title')[$i],
                                'choice_type' => $this->input->post('choice_type')[$i],
                                'required' => $this->input->post('required')[$i],
                            );
                            $j = 1;
                            foreach ($this->input->post('options') as $option) {
                                if ($i == $j) {
                                    $data['options'] = implode(',', $option);
                                }
                                $j++;
                            }
                            $data = $this->security->xss_clean($data);
                            $this->db->insert('product_additions', $data);
                        }
                    }
                }

                if ($result) {
                    $this->session->set_flashdata('msg', 'تم التعديل المنتج بفضل الله!');
                    redirect(base_url('' . $this->thispage . '/index/'));
                }
            }
        }
        if (!$add) {
            $data['title'] = $this->lang->line('edit') . ' ' . $this->lang->line('products');
            $data['thispage'] = $this->thispage;
            $data['cats'] = $this->db->get('product_categories')->result();
            $this->db->select('distinct(brand) as brand');
            $data['brands'] = $this->db->get('bills_producer')->result();
            $this->load->model('admin/Orders_model');
            $data['product_adds'] = $this->Orders_model->get_product_additions($id);
            $data['adds'] = $this->db->get_where('additions', array('active' => 1))->result();
            $this->db->select('distinct group_name', FALSE);
            $data['group_name'] = $this->db->get_where('additions', array('active' => 1))->result();
            // $data['view'] = '../controllers/views/' . $this->thispage . '/edit';
            $this->load->view('site/' . $this->thispage . '/edit', $data);
        }
    }

    public function clint_blacklist($id) {

        $this->db->where('id', $id)->update('bills_producer', array('oky' => 'ok', 'comment' => $this->input->post('comment')));

        $this->session->set_flashdata('msg', 'تم عمل بلاك لست ');
        redirect(base_url() . 'dashboard');
    }

    public function bill_report() {
        $this->db->from('bills_producer');
        $this->db->order_by('id', 'ASC');
        $result = $this->db->get()->result_array();
        if ($result) {
            $array = array();
            foreach ($result as $key => $row) {
                $array[] = array(
                    'name' => $row['name'],
                    'Current_bills' => $this->db->from('bills_orders')->where("id_producer='" . $row['id'] . "' and active='0'")->count_all_results(),
                    'Invoices_ended' => $this->db->from('bills_orders')->where("id_producer='" . $row['id'] . "' and active='1'")->count_all_results(),
                    'fees' => $row['valuess'],
                    'Total_fees ' => $this->sum_bill($row['id']),
                    'Total_discount' => $this->sum_discount($row['id']),
                    'total' => $this->sum_bill($row['id']) - $this->sum_discount($row['id']),
                    'Paid_up' => $this->sum_discount($row['id']),
                );
            }
        }
        export_csv($array, "bills");
    }

    function delete_absent($id) {
        $this->db->delete('gyab', array('sno' => $id));
        $this->session->set_flashdata('success', 1);
        redirect('user/absent_show');
    }

    function adjust_products() {
        $products = $this->db->get('bills_producer')->result();
        foreach ($products as $product) {
            $old_prod = $this->db->get_where('bills_producer', array('id !=' => $product->id, 'name' => $product->name))->row();
            if ($old_prod) {
                if ($old_prod->id > $product->id) {
                    $new_id = $old_prod->id;
                    $old_id = $product->id;
                } else {
                    $new_id = $product->id;
                    $old_id = $old_prod->id;
                }
                $this->db->update('bills_orders', array('id_producer' => $new_id), array('id_producer' => $old_id));
                $this->db->delete('bills_producer', array('id' => $old_id));
            }
        }
    }

    // ================================================ Additions ================================
    function additions() {
        $data['adds'] = $this->db->get('additions')->result();
        $data['title'] = $this->lang->line('additions');
        $data['thispage'] = $this->thispage;
        $this->load->view('site/additions/all', $data);
    }

    function change_addition_active_status($status, $id) {
        $this->db->update('additions', array('active' => $status), array('id' => $id));
        $this->session->set_flashdata('success', $this->lang->line('op_success'));
        redirect(base_url('producer/additions'));
    }

    function add_addition() {
        if (!(get_ap('additions_add', $this->operator_id) == 1))
            redirect("", "refresh");
        $add = FALSE;
        if ($this->input->post('submit')) {
            $this->form_validation->set_rules('name_en', $this->lang->line('english_name'), 'trim|required');
            $this->form_validation->set_rules('name_ar', $this->lang->line('arabic_name'), 'trim|required');
            $this->form_validation->set_rules('price', $this->lang->line('price'), 'trim|numeric');


            if ($this->form_validation->run() === FALSE) {
                $add = FALSE;
            } else {
                $add = TRUE;

                $data = array(
                    'name_en' => $this->input->post('name_en'),
                    'name_ar' => $this->input->post('name_ar'),
                    'price' => $this->input->post('price'),
                    'group_name' => $this->input->post('group_name'),
                    'active' => 1
                );
                $data = $this->security->xss_clean($data);
                $this->db->insert('additions', $data);
                $this->session->set_flashdata('success', $this->lang->line('op_success'));
                redirect(base_url('' . $this->thispage . '/additions'));
            }
        }

        if (!$add) {
            $data['title'] = $this->lang->line('add') . ' ' . $this->lang->line('addition');
            $data['thispage'] = $this->thispage;
            $this->load->view('site/additions/add', $data);
        }
    }

    function edit_addition($id) {
        if (!(get_ap('additions_edit', $this->operator_id) == 1))
            redirect("", "refresh");
        $add = FALSE;
        if ($this->input->post('submit')) {
            $this->form_validation->set_rules('name_en', $this->lang->line('english_name'), 'trim|required');
            $this->form_validation->set_rules('name_ar', $this->lang->line('arabic_name'), 'trim|required');
            $this->form_validation->set_rules('price', $this->lang->line('price'), 'trim|numeric');


            if ($this->form_validation->run() === FALSE) {
                $add = FALSE;
            } else {
                $add = TRUE;

                $data = array(
                    'name_en' => $this->input->post('name_en'),
                    'name_ar' => $this->input->post('name_ar'),
                    'price' => $this->input->post('price'),
                    'group_name' => $this->input->post('group_name'),
                );
                $data = $this->security->xss_clean($data);
                $this->db->update('additions', $data, array('id' => $id));
                $this->session->set_flashdata('success', $this->lang->line('op_success'));
                redirect(base_url('' . $this->thispage . '/additions'));
            }
        }

        if (!$add) {
            $data['data'] = $this->db->get_where('additions', array('id' => $id))->row();
            $data['title'] = $this->lang->line('edit') . ' ' . $this->lang->line('addition');
            $data['thispage'] = $this->thispage;
            $this->load->view('site/additions/edit', $data);
        }
    }

    function delete_addition($id) {
        $this->db->where('id', $id);
        $this->db->delete('additions');
        $this->session->set_flashdata('success', $this->lang->line('op_succcess'));
        redirect(base_url('producer/additions'));
    }

    function product_additions($product_id) {
        if ($this->input->post('submit')) {
            $this->form_validation->set_rules('eng_title', $this->lang->line('eng_title'), 'trim|required');
            $this->form_validation->set_rules('ar_title', $this->lang->line('ar_title'), 'trim|required');
            $this->form_validation->set_rules('options[]', $this->lang->line('additions'), 'trim|required');

            if ($this->form_validation->run() === FALSE) {
                
            } else {

                $data = array(
                    'product_id' => $product_id,
                    'title_en' => $this->input->post('eng_title'),
                    'title_ar' => $this->input->post('ar_title'),
                    'choice_type' => $this->input->post('choice_type'),
                    'required' => $this->input->post('required'),
                    'options' => implode(',', $this->input->post('options'))
                );
                $data = $this->security->xss_clean($data);
                $this->db->insert('product_additions', $data);
                $this->session->set_flashdata('success', $this->lang->line('op_success'));
                redirect(base_url($this->thispage));
            }
        }
        $this->load->model('admin/Orders_model');
        $data['product_adds'] = $this->Orders_model->get_product_additions($product_id);
        $data['adds'] = $this->db->get_where('additions', array('active' => 1))->result();
        $this->db->select('distinct group_name', FALSE);
        $data['group_name'] = $this->db->get_where('additions', array('active' => 1))->result();
        $data['title'] = $this->lang->line('product_additions');
        $data['thispage'] = $this->thispage;
        $data['product_id'] = $product_id;
        $this->load->view('site/' . $this->thispage . '/product_additions', $data);
    }

    function filter_additions_by_group_name() {
        $group_name = $this->input->post('group_name');
        if ($group_name != 'all') {
            $this->db->where('group_name', $group_name);
        }
        $data = $this->db->get('additions')->result();
        echo json_encode($data);
    }

    function delete_product_addition($id, $product_id) {
        $this->db->where('id', $id);
        $this->db->delete('product_additions');
        $this->session->set_flashdata('success', $this->lang->line('op_succcess'));
        redirect(base_url('producer/product_additions/' . $product_id));
    }

}

?>