<?php

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

class Categories 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()) != 'bill_report') {
            redirect("", "refresh");
        }
        $this->load->model('booking');
        $this->thispage = "categories";
        $this->operator_id = $this->session->userdata('operator_id');
        if (get_ap('categories', $this->operator_id) == 1) {
            
        } else {
            redirect("", "refresh");
        }
    }

    public function index($cats = 1) {
        $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('product_categories');
        if ($whr)
            $this->db->where($whr);
        $max = 40;

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

        $this->db->select('product_categories.*,count(bills_producer.id) as products_count');
        $this->db->from('product_categories');
        $this->db->order_by('product_categories.id', 'desc');
        $this->db->join('bills_producer', 'product_categories.id=bills_producer.cat_id and bills_producer.active=1', 'left');
        $this->db->group_by('product_categories.id,product_categories.name');
        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 . "'";
//        foreach ($data['all_groups'] as $row) {
//            
//            //$data['all_groups']['allcat']=$this->db->from('cat')->where("parentcatid=".$row['catid'])->count_all_results();
//        }
        $data['title'] = 'الفئات';
        // $data['view'] = '../controllers/views/' . $this->thispage . '/all';
        $data['thispage'] = $this->thispage;
        $this->load->view('site/categories/all', $data);
    }

    public function add($cats = 1) {
        if (!(get_ap('categories_add', $this->operator_id) == 1))
            redirect("", "refresh");
        $add = FALSE;
        $this->cats = $cats;
        if ($this->input->post('submit')) {
            $this->form_validation->set_rules('name', '', '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(
                    'name' => $this->input->post('name'),
                );
                $data = $this->security->xss_clean($data);
                $result = $this->db->insert('product_categories', $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['view'] = '../controllers/views/' . $this->thispage . '/add';
            $this->load->view('site/' . $this->thispage . '/add', $data);
        }
    }

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


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

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


        $add = FALSE;
        if ($this->input->post('submit')) {
            $this->form_validation->set_rules('name', '', '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;
                $edit_data = array(
                    'name' => $this->input->post('name'),
                );
                $edit_data = $this->security->xss_clean($edit_data);
                $result = $this->db->where('id', $id)->update('product_categories', $edit_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('categories');
            $data['thispage'] = $this->thispage;
            // $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");
    }

}

?>