<?php

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

class Announcement extends MY_Controller {

    var $announcement;
    var $thispage;

    public function __construct() {
        parent::__construct();
        if (!get_license_per('advs_msgs')) {
            redirect("", "refresh");
        }
        $this->load->model('booking');
        $this->thispage = "announcement";
        $this->operator_id = $this->session->userdata('operator_id');
        //if (get_ap('bill', $this->operator_id) == 1) {
            
       // } else {
        //    redirect("", "refresh");
       // }
    }

    public function index($announcement = 1) {
        if (!get_ap('messages', $this->operator_id)) {
            redirect("", "refresh");
        }
        $this->announcement = $announcement;
        $this->all($announcement, 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('announcement');
        if ($whr)
            $this->db->where($whr);
        $max = 40;

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

        $this->db->select('announcement.*,user.name as added_by_name,bills_producer.name as product_name');
        $this->db->from('announcement');
        $this->db->order_by('announcement.id', 'desc');
        if ($whr)
            $this->db->where($whr);

       // $this->db->limit($max, ($max * $page) - $max);
        
        if ($this->input->post('start_expiry')) {
            $date_arr = explode(' - ', $this->input->post('start_expiry'));
            $from = date('Y-m-d', strtotime($date_arr[0]));
            $to = date('Y-m-d', strtotime($date_arr[1]));
            $this->db->where(array('announcement.start_date >=' => $from, 'announcement.start_date <=' => $to));
        }
        if (!empty($this->input->post('products'))) {
            $this->db->where_in('bills_producer.name', $this->input->post('products'));
        }

        $this->db->where('announcement.students !=', '');
        $this->db->join('user', 'user.id = announcement.added_by');
        $this->db->join('bills_producer', 'bills_producer.id = announcement.product_id');
        $res = $this->db->get()->result_array();
        
        $data['all_groups'] = array();
        foreach ($res as $rec){
            if($rec['students'] != ''){
                $students = explode(',', $rec['students']);
                foreach ($students as $student){
                    $this->db->select('username');
                    $st = $this->db->get_where('bills_user',array('id'=>$student))->row();
                    if($st){
                        $rec['students'] = $st->username;
                        $data['all_groups'][] = $rec;
                    }
                }
            }else{
                $data['all_groups'][] = $rec;
            }
        }
        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'] = $this->lang->line('messages');
        // $data['view'] = '../controllers/views/' . $this->thispage . '/all';
        $data['thispage'] = $this->thispage;
        $this->db->select('id,name');
        $data['products'] = $this->db->get_where('bills_producer')->result();
        $data['ann'] = 0;
        $this->load->view('site/announcement/all', $data);
    }

    public function add($ann) {
        $add = FALSE;
        
        if ($this->input->post('submit')) {
            $this->form_validation->set_rules('content', 'content', 'trim|required');
            $this->form_validation->set_rules('start_date', $this->lang->line('start-date'), 'trim|required');
            $this->form_validation->set_rules('end_date', $this->lang->line('end-date'), 'trim|required');
            $this->form_validation->set_rules('product', $this->lang->line('product'), '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 {
                $users = array();
                foreach ($this->input->post('username') as $username) {
                    $row = $this->db->get_where('bills_user', array('username' => $username))->row();
                    if ($row) {
                        $users[] = $row->id;
                    }
                }

                $add = TRUE;
                $data = array(
                    'msg' => $this->input->post('content'),
                    'start_date' => $this->input->post('start_date'),
                    'end_date' => $this->input->post('end_date'),
                    'end_date' => $this->input->post('end_date'),
                    'product_id' => $this->input->post('product'),
                    'added_by' => $this->session->userdata('admin_id')
                );
                if ($ann == 0) {
                   // $data['product_id'] = $this->input->post('product');
                    $data['students'] = empty($users) ? '' : implode(',', $users);
                }
                $data = $this->security->xss_clean($data);
                $result = $this->db->insert('announcement', $data);
                if ($result) {
                    $this->session->set_flashdata('msg', 'تم اضافةالاعلان بفضل الله!');
                    if($ann){
                        redirect(base_url('' . $this->thispage . '/announcment/'));
                    }
                    redirect(base_url('' . $this->thispage . '/index/'));
                }
            }
        }

        if (!$add) {
            $data['title'] = 'اضافة اعلان';
            $data['announcement'] = $this->announcement;
            $data['products'] = $this->db->get_where('bills_producer', array('active' => 1))->result();
            $data['username'] = $this->db->get_where('bills_user', array('approve_status' => 1))->result();
            $data['thispage'] = $this->thispage;
            $data['ann'] = $ann;
            $this->load->view('site/' . $this->thispage . '/add', $data);
        }
    }

    public function del($id,$ann) {
        $this->db->where('id', $id);
        $result = $this->db->delete('announcement');
        if (count($result) > 0) {
            $this->session->set_flashdata('msg', 'تم حذف  الاعلان بفضل الله!');
            if($ann){
                redirect(base_url('' . $this->thispage . '/announcment/'));
            }
            redirect(base_url('' . $this->thispage . '/index/'));
        }
    }

    public function edit($id, $ann) {

        $query = $this->db->get_where('announcement', array('id' => $id));
        $data['edit'] = $query->row_array();

        $add = FALSE;
        if ($this->input->post('submit')) {
            $this->form_validation->set_rules('content', 'content', 'trim|required');
            $this->form_validation->set_rules('start_date', $this->lang->line('start-date'), 'trim|required');
            $this->form_validation->set_rules('end_date', $this->lang->line('end-date'), 'trim|required');
            $this->form_validation->set_rules('product', $this->lang->line('product'), '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;
                $users = array();
                foreach ($this->input->post('username') as $username) {
                    $row = $this->db->get_where('bills_user', array('username' => $username))->row();
                    if ($row) {
                        $users[] = $row->id;
                    }
                }

                $add = TRUE;
                $data = array(
                    'msg' => $this->input->post('content'),
                    'start_date' => $this->input->post('start_date'),
                    'end_date' => $this->input->post('end_date'),
                    'end_date' => $this->input->post('end_date'),
                    'product_id' => $this->input->post('product')
                );
                if ($ann == 0) {
                    //$data['product_id'] = $this->input->post('product');
                    $data['students'] = empty($users) ? '' : implode(',', $users);
                }
                $data = $this->security->xss_clean($data);
                $result = $this->db->where('id', $id)->update('announcement', $data);

                $this->session->set_flashdata('msg', 'تم التعديل الاعلان بفضل الله!');
                if($ann){
                    redirect(base_url('' . $this->thispage . '/announcment/'));
                }
                redirect(base_url('' . $this->thispage . '/index/'));
            }
        }
        if (!$add) {
            $data['title'] = $this->lang->line('edit') . ' ' . $this->lang->line('announcement');
            $data['thispage'] = $this->thispage;
            $data['announcement'] = $this->announcement;
            $data['products'] = $this->db->get_where('bills_producer', array('active' => 1))->result();
            $data['username'] = $this->db->get_where('bills_user', array('approve_status' => 1))->result();
            // $data['view'] = '../controllers/views/' . $this->thispage . '/edit';
            $data['ann'] = $ann;
            $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");
    }
    
    public function announcment($page = 1, $all = '') {
            if (!get_ap('announcement', $this->operator_id)) {
                redirect("", "refresh");
            }
            $searchfor = $this->security->xss_clean($this->input->get('search'));
            $whr = "";
            if (!$this->session->userdata('group'))
                $whr = "cid='ddd'";
                
                
                $this->db->from('announcement');
                if ($whr)
                    $this->db->where($whr);
                    $max = 40;
                    
                    $data['all_count'] = ceil($this->db->count_all_results() / $max);
                    
                    $this->db->select('announcement.*,user.name as added_by_name,bills_producer.name as product_name');
                    $this->db->from('announcement');
                    $this->db->order_by('announcement.id', 'desc');
                    if ($whr)
                        $this->db->where($whr);
                        
                        //$this->db->limit($max, ($max * $page) - $max);
                        
                        if ($this->input->post('start_expiry')) {
                            $date_arr = explode(' - ', $this->input->post('start_expiry'));
                            $from = date('Y-m-d', strtotime($date_arr[0]));
                            $to = date('Y-m-d', strtotime($date_arr[1]));
                            $this->db->where(array('announcement.start_date >=' => $from, 'announcement.start_date <=' => $to));
                        }
                        if (!empty($this->input->post('products'))) {
                            $this->db->where_in('bills_producer.name', $this->input->post('products'));
                        }
                        
                        $this->db->where('announcement.students', '');
                        $this->db->join('user', 'user.id = announcement.added_by');
                        $this->db->join('bills_producer', 'bills_producer.id = announcement.product_id');
                        $res = $this->db->get()->result_array();
                        
                        $data['all_groups'] = array();
                        foreach ($res as $rec){
                            if($rec['students'] != ''){
                                $students = explode(',', $rec['students']);
                                foreach ($students as $student){
                                    $this->db->select('username');
                                    $st = $this->db->get_where('bills_user',array('id'=>$student))->row();
                                    if($st){
                                        $rec['students'] = $st->username;
                                        $data['all_groups'][] = $rec;
                                    }
                                }
                            }else{
                                $data['all_groups'][] = $rec;
                            }
                        }
                        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'] = $this->lang->line('announcement');
                        // $data['view'] = '../controllers/views/' . $this->thispage . '/all';
                        $data['thispage'] = $this->thispage;
                        $this->db->select('id,name');
                        $data['products'] = $this->db->get_where('bills_producer')->result();
                        $data['ann'] = 1;
                        $this->load->view('site/announcement/all', $data);
                        
    }

}

?>