<?php

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

class User extends MY_Controller {

    var $cats;
    var $thispage;

    public function __construct() {
        parent::__construct();
        $this->load->model('booking');
        // $this->load->helper('site_helper');
        $this->operator_id = $this->session->userdata('operator_id');
        // if (get_ap('student', $this->operator_id) == 1) {} else {
        //     redirect("", "refresh");
        // }
        $this->thispage = "user";
    }

    function show_absent($id) {
        $query = $this->db->get_where('gyab', array(
            'user_id' => $id
        ));
        $data['all_groups'] = $query->row_array();
        $data['title'] = $this->lang->line('absent');
        $data['thispage'] = $this->thispage;
        $this->load->view('site/' . $this->thispage . '/show_absent', $data);
    }

    function absent() {

        if (!get_ap('attendance_add', $this->operator_id)) {
            redirect("", "refresh");
        }
        if ($this->input->post()) {
            $data = $this->input->post('absent');
            $date = $this->input->post('date');
            $product = $this->input->post('product'); // add date column in view file
            foreach ($data as $key => $value) {
                $new_data = array(
                    'user_id' => $key,
                    'present' => $value,
                    'date' => $date,
                    'product_id' => $product,
                    'create_on' => date('m-d-Y h:m:sa')
                );
                $exist = $this->db->get_where('gyab', array(
                            'date' => $date,
                            'product_id' => $product,
                            'user_id' => $key
                        ))->row();
                if ($exist) {
                    $this->db->update('gyab', $new_data, array(
                        'sno' => $exist->sno
                    ));
                } else {
                    $this->db->insert('gyab', $new_data);
                }
            }

            $this->session->set_flashdata('success', 1);
            redirect(base_url('User/absent'));
        } else {
            if ($this->session->userdata('teacher_id')) {
                $this->db->where('teacher_id', $this->session->userdata('teacher_id'));
            }
            $data['products'] = $this->db->get_where('bills_producer', array(
                        'active' => 1
                    ))->result();
            $data['title'] = $this->lang->line('absent');
            $data['thispage'] = $this->thispage;
            $this->load->view('site/' . $this->thispage . '/add_absent', $data);
        }
    }

    function get_active_users() {
        $product_id = $this->input->post('product');
        $date = date('Y-m-d', strtotime($this->input->post('date')));

        $this->db->select('distinct(id_user),name');
        $res = $this->db->get_where('bills_orders', array(
                    'id_producer' => $product_id,
                    'start_date <=' => $date,
                    'expiry_date >=' => $date
                ))->result();
        echo json_encode($res);
    }

    function absent_show() {

        if (!get_ap('show_attendance', $this->operator_id)) {
            redirect("", "refresh");
        }
        if ($this->input->post()) {
            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(
                    'gyab.date >=' => $from,
                    'gyab.date <=' => $to
                ));
            }
            if (!empty($this->input->post('username'))) {
                $this->db->where_in('bills_user.username', $this->input->post('username'));
            }
            if (!empty($this->input->post('products'))) {
                $this->db->where_in('bills_producer.name', $this->input->post('products'));
            }
            if (!empty($this->input->post('attend_status'))) {
                $attend_arr = array();
                $attend_status_arr = array(
                    $this->lang->line('absent'),
                    $this->lang->line('present'),
                    $this->lang->line('late')
                );
                foreach ($this->input->post('attend_status') as $attend_s) {
                    $index = array_search($attend_s, $attend_status_arr);
                    if ($index !== FALSE) {
                        $attend_arr[] = $index;
                    }
                }
                if (!empty($attend_arr)) {
                    $this->db->where_in('gyab.present', $attend_arr);
                }
            }
        }
        $this->db->join('bills_producer', 'bills_producer.id=gyab.product_id');
        $this->db->join('bills_user', 'bills_user.id=gyab.user_id');
        if ($this->session->userdata('teacher_id')) {
            $this->db->where('bills_producer.teacher_id', $this->session->userdata('teacher_id'));
        }
        $query = $this->db->get('gyab');
        $data['all_groups'] = $query->result();
        $this->db->select('username');
        $data['username'] = $this->db->get_where('bills_user', array(
                    'approve_status' => 1
                ))->result();
        $this->db->select('id,name');
        if ($this->session->userdata('teacher_id')) {
            $this->db->where('bills_producer.teacher_id', $this->session->userdata('teacher_id'));
        }
        $data['products'] = $this->db->get_where('bills_producer')->result();
        $data['title'] = $this->lang->line('absent');
        $data['thispage'] = $this->thispage;
        $this->load->view('site/absent/attendance_list', $data);
    }

    public function index($cats = 1) {
        if (!(get_ap('student', $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'";

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

        $this->db->from('bills_user');
        $this->db->where(array(
            'approve_status' => 1
        ));
        $this->db->order_by('id', 'desc');
        if ($whr)
            $this->db->where($whr);

        // $this->db->limit($max, ($max * $page) - $max);
        if ($this->input->server('REQUEST_METHOD') == "POST") {
            $username = $this->input->post('username');
            $cid_no = $this->input->post('civil_id');
            $nationality = $this->input->post('nationality');
            $region = $this->input->post('region');
            $status = $this->input->post('status');
            $sex = $this->input->post('sex');
            if ($username) {
                $this->db->where_in('username', $username);
            }
            if ($cid_no) {
                $this->db->where_in('cid_user', $cid_no);
            }
            if ($nationality) {
                $this->db->where_in('nationality', $nationality);
            }
            if ($region) {
                $this->db->where_in('region', $region);
            }
            if ($sex) {
                $this->db->where_in('sex', $sex);
            }
            if ($status) {
                $this->db->where_in('block', $status);
            }
            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('since_time_register >=' => strtotime($from), 'since_time_register <=' => strtotime($to)));
            }
            $data['all_groups'] = $this->db->get()->result_array();
            // echo $this->db->last_query();die;
        } else {
            $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_user where ' . $whr);
            $data['all_count'] = 0;
            $whr = '';
            $data['all_groups'] = $query->result_array();
            $data['all_count'] = count($data['all_groups']);
            // echo ' <pre>'; print_r($data['all_groups']);echo '<pre>';die();
        }
        foreach ($data['all_groups'] as $row) {
            // $data['all_groups']['allcat']=$this->db->from('cat')->where("parentcatid=".$row['catid'])->count_all_results();
        }

        /*
         * if($this->input->server('REQUEST_METHOD') =="POST"){
         * $name = $this->input->post('name');
         * $civil_no = $this->input->post('civil_no');
         * $nationality = $this->input->post('nationality');
         * $region = $this->input->post('region');
         * if($name){
         * $this->db->like('username', $name, 'both');
         * }
         * if($civil_no){
         * $this->db->like('cid_user', $civil_no, 'both');
         * }
         * if($nationality){
         * $this->db->like('city', $nationality, 'both');
         * }
         * if($region){
         * $this->db->like('city2', $region, 'both');
         * }
         * $data['all_groups'] = $this->db->get('bills_user')->result_array();
         * }
         */
        $data['username'] = $this->db->get('bills_user')->result();

        $this->db->where('lable', 'nationality');
        $data['nationality'] = $this->db->get('datas')->result();

        $this->db->where('lable', 'region');
        $data['region'] = $this->db->get('datas')->result();

        $this->db->select('cid_user');
        $data['civil_no'] = $this->db->get('bills_user')->result();

        $this->db->select('customer_fields,show_customer_fields');
        $sett = $this->db->get('setting')->row();
        $data['show_fields'] = explode(',', $sett->show_customer_fields);

        $data['title'] = $this->lang->line('students');
        // $data['view'] = '../controllers/views/' . $this->thispage . '/all';
        $data['thispage'] = $this->thispage;
        $this->load->view('site/' . $this->thispage . '/all', $data);
    }

    public function add($cats = 1) {
        $add = FALSE;
        $this->cats = $cats;
        $this->db->select('customer_fields,show_customer_fields');
        $sett = $this->db->get('setting')->row();
        $required_fields = explode(',', $sett->customer_fields);
        if ($this->input->post('submit')) {
            $fields_arr = array(
                'username' => $this->lang->line('name'),
//                'name' => $this->lang->line('name'),
                'cid_user' => $this->lang->line('civil-no'),
                'email' => $this->lang->line('e-mail'),
                'password' => $this->lang->line('password'),
                'phone' => $this->lang->line('students') . ' ' . $this->lang->line('mobile'),
                'phone_father' => $this->lang->line('guardian') . ' ' . $this->lang->line('mobile'),
                'country' => $this->lang->line('nationality'),
                'city' => $this->lang->line('region'),
                'blocks' => $this->lang->line('block'),
                'street' => $this->lang->line('street'),
                'jadah' => $this->lang->line('jadah'),
                'floor' => $this->lang->line('floor'),
                'door_no' => $this->lang->line('door-number'),
                'address_link' => $this->lang->line('address-link'),
                'title' => $this->lang->line('title'),
                'age' => $this->lang->line('date-of-birth'),
                'sex' => $this->lang->line('sex'),
                'father_work' => $this->lang->line('father_work'),
                'mother_work' => $this->lang->line('mother_work'),
                'social_status' => $this->lang->line('social_status'),
                'note' => $this->lang->line('note')
            );
//            $this->form_validation->set_rules('password', $this->lang->line('password'), 'trim|required');

            foreach ($fields_arr as $key => $val) {
                if (in_array($key, $required_fields)) {
                    $this->form_validation->set_rules($key, $val, 'trim|required');
                }
            }
            if ($this->input->post('email')) {
                $this->form_validation->set_rules('email', $this->lang->line('email'), 'trim|is_unique[bills_user.email]');
            }
//            if ($this->input->post('username')) {
//                $this->form_validation->set_rules('username', $this->lang->line('username'), 'trim|is_unique[bills_user.username]');
//            }
            if ($this->input->post('phone')) {
                $this->form_validation->set_rules('phone', $this->lang->line('phone'), 'trim|is_unique[bills_user.phone]');
            }
            // $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 {
                // $imageuser = '';
                // $fieldname = 'imageuser';
                /*
                 * if ($_FILES[$fieldname]['name'] != "") {
                 * $upload_data = $this->booking->upload_many_photos($fieldname, $this->input->post('cid_user') . '1');
                 * $imageuser = "upload/" . $upload_data["file_name"];
                 * }
                 */
                $add = TRUE;
                $data = array(
                    'cid_user' => $this->input->post('cid_user'),
                    'username' => $this->input->post('username'),
                    'name' => $this->input->post('name'),
                    'email' => $this->input->post('email'),
                    'pass' => $this->input->post('password') ? md5(md5($this->input->post('password'))) : '',
                    'phone_code' => $this->input->post('countryCode'),
                    'phone' => $this->input->post('phone'),
                    'phone_father' => $this->input->post('phone_father'),
                    'nationality' => $this->input->post('country'),
                    //'city3' => $this->input->post('city3'),
                    'age' => $this->input->post('age'),
                    'sex' => $this->input->post('sex'),
                    'note' => $this->input->post('note'),
                    'create_on' => date('m-d-Y m:h:sa'),
                    // 'imageuser' => $imageuser,
                    'since_time_register' => $this->booking->tissme_now(),
                    'stop' => '0',
                    'approve_status' => 1,
                    'father_job' => $this->input->post('father_work'),
                    'mother_job' => $this->input->post('mother_work'),
                    'social_status' => $this->input->post('social_status'),
                    'student_tags' => $this->input->post('student_tags') ? implode(',', $this->input->post('student_tags')) : '',
                    'block' => 0
                );
                $data = $this->security->xss_clean($data);
                $this->db->insert('bills_user', $data);
                $result = $this->db->insert_id(); // =====================================================
                //insert address
                for ($i = 0; $i < $this->input->post('address_count'); $i++) {
                    $data = array('region' => isset($this->input->post('city')[$i]) ? $this->input->post('city')[$i] : '',
                        'blocks' => isset($this->input->post('blocks')[$i]) ? $this->input->post('blocks')[$i] : '',
                        'floor' => isset($this->input->post('floor')[$i]) ? $this->input->post('floor')[$i] : '',
                        'jadah' => isset($this->input->post('jadah')[$i]) ? $this->input->post('jadah')[$i] : '',
                        'street' => isset($this->input->post('street')[$i]) ? $this->input->post('street')[$i] : '',
                        'door_no' => isset($this->input->post('door_no')[$i]) ? $this->input->post('door_no')[$i] : '',
                        'building_num' => isset($this->input->post('building_num')[$i]) ? $this->input->post('building_num')[$i] : '',
                        'address_link' => isset($this->input->post('address_link')[$i]) ? $this->input->post('address_link')[$i] : '',
                        'user_id' => $result
                    );
                    $this->db->insert('addresses', $data);
                }
                //=====
                $this->load->library('upload');
                $dataInfo = array();
                $files = $_FILES;
                if (isset($_FILES['profile'])) {
                    if ($_FILES['profile']['name']) {
                        $_FILES['userfile']['name'] = $files['profile']['name'];
                        $_FILES['userfile']['type'] = $files['profile']['type'];
                        $_FILES['userfile']['tmp_name'] = $files['profile']['tmp_name'];
                        $_FILES['userfile']['error'] = $files['profile']['error'];
                        $_FILES['userfile']['size'] = $files['profile']['size'];
                        $this->upload->initialize($this->set_upload_options());
                        $this->upload->do_upload();
                        $dataInfo = $this->upload->data();
                        $profile_image_name = $dataInfo['file_name'];
                        $this->db->insert('user_image', array(
                            'image' => $profile_image_name,
                            'user_id' => $result,
                            'profile_pic' => 1
                        ));
                    }
                }
                if (isset($_FILES['imageuser'])) {
                    $cpt = count($_FILES['imageuser']['name']);
                    for ($i = 0; $i < $cpt; $i ++) {
                        $_FILES['userfile']['name'] = $files['imageuser']['name'][$i];
                        $_FILES['userfile']['type'] = $files['imageuser']['type'][$i];
                        $_FILES['userfile']['tmp_name'] = $files['imageuser']['tmp_name'][$i];
                        $_FILES['userfile']['error'] = $files['imageuser']['error'][$i];
                        $_FILES['userfile']['size'] = $files['imageuser']['size'][$i];
                        $this->upload->initialize($this->set_upload_options());
                        $this->upload->do_upload();
                        $dataInfo[] = $this->upload->data();
                    }
                    for ($i = 0; $i < $cpt; $i ++) {
                        $datas[] = $dataInfo[$i]['file_name'];
                    }
                    $datass['image'] = implode(',', $datas);
                    $datass['user_id'] = $result;
                    $datass['create_on'] = date("m-d-Y h:m:sa");
                    $this->db->insert('user_image', $datass);
                }
                // ===================================================
                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->db->where('lable', 'nationality');
            $data['nationality'] = $this->db->get('datas')->result();
            $this->db->where('lable', 'region');
            $data['region'] = $this->db->get('datas')->result();
            $data['lang'] = $this->session->userdata("language");
            $this->load->model('points/Tag_Model');
            $data['student_tags'] = $this->Tag_Model->get_tag(2);
            $data['req_fields'] = $required_fields;
            $data['show_fields'] = explode(',', $sett->show_customer_fields);
            $this->load->view('site/' . $this->thispage . '/add', $data);
        }
    }

    private function set_upload_options() {
        // upload an image options
        $config = array();
        $config['upload_path'] = './public/upload/userimage/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '0';
        $config['overwrite'] = FALSE;
        return $config;
    }

    public function show($id, $success = '') {
        if (!get_ap('student_profile', $this->operator_id)) {
            redirect("", "refresh");
        }
        $this->db->select('bills_user.*,user_image.image as image');
        $this->db->join('user_image', 'user_image.user_id=bills_user.id and user_image.profile_pic = 1', 'left');
        $query = $this->db->get_where('bills_user', array(
            'id' => $id
        ));
        $data['show'] = $query->row_array();
        $whr = " id_user=" . $data['show']['id'];
        $this->db->from('bills_orders');
        $this->db->order_by('id', 'desc');
        $this->db->where($whr);
        $data['bills_orders'] = $this->db->get()->result_array();
        $data['title'] = 'الطلاب';

        $this->db->select('bills_orders.*,sum(bills_orders.discount_remainder) as total_price');
        $this->db->from('bills_orders');
        $this->db->order_by('id', 'desc');
        $this->db->group_by('id_orders');
        $this->db->where(array(
            'id_user' => $id
        ));
        $data['invoices'] = $this->db->get()->result_array();

        $this->db->select('bills_orders.*');
        $this->db->from('bills_orders');
        $this->db->order_by('bills_orders.id', 'desc');
        $this->db->join('bills_producer', 'bills_producer.id=bills_orders.id_producer and bills_producer.type=2');
        $this->db->where(array(
            'id_user' => $id
        ));
        $data['membership'] = $this->db->get()->result_array();

        $this->db->select('bills_producer.name,gyab.product_id,count(gyab.sno) as total_days');
        $this->db->select('SUM(CASE WHEN gyab.present = 1 THEN 1 ELSE 0 END) AS present');
        $this->db->select('SUM(CASE WHEN gyab.present = 0 THEN 1 ELSE 0 END) AS absent');
        $this->db->select('SUM(CASE WHEN gyab.present = 2 THEN 1 ELSE 0 END) AS late');
        $this->db->group_by('gyab.product_id,bills_producer.name');
        $this->db->join('bills_producer', 'bills_producer.id=gyab.product_id');
        $query = $this->db->get_where('gyab', array(
            'gyab.user_id' => $id
        ));
        $data['attendance'] = $query->result();

        $data['attachments'] = $this->db->get_where('user_image', array(
                    'user_id' => $id,
                    'profile_pic' => 0
                ))->row();

        $this->load->model('points/Student_Model');
        $data['history'] = $this->Student_Model->get_student_history_id($id);

        $data['user_id'] = $id;
        $data['thispage'] = $this->thispage;
        $data['success'] = $success;

        $this->db->select('customer_fields,show_customer_fields');
        $sett = $this->db->get('setting')->row();
        $data['show_fields'] = explode(',', $sett->show_customer_fields);

        // $data['view'] = '../controllers/views/' . $this->thispage . '/show';
        $this->load->view('site/' . $this->thispage . '/profile', $data);
    }

    public function del($id) {

        $this->db->where('id', $id);
        $result = $this->db->delete('bills_user');
        //if (count($result) > 0) {
        $this->session->set_flashdata('msg', 'تم حذف الطالب بنجاح');
        redirect(base_url('user/index/'));
        //}
    }

    public function block() {
        $id = $this->input->post('user_id');
        $this->db->update('bills_user', array(
            'block' => 1,
            'block_reason' => $this->input->post('block_reason')
                ), array(
            'id' => $id
        ));
        $this->session->set_flashdata('msg', 'تم حظر الطالب بنجاح');
        redirect(base_url('user/index/'));
    }

    public function unblock($id) {
        $this->db->update('bills_user', array(
            'block' => 0,
            'block_reason' => ''
                ), array(
            'id' => $id
        ));
        $this->session->set_flashdata('msg', 'تم ازالة حظر الطالب بنجاح');
        redirect(base_url('user/index/'));
    }

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

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

        $data['edit']['checked'][$data['edit']['sex']] = 'checked';
        $add = FALSE;
        $this->db->select('customer_fields,show_customer_fields');
        $sett = $this->db->get('setting')->row();
        $required_fields = explode(',', $sett->customer_fields);
        if ($this->input->post('submit')) {

            $fields_arr = array(
                'username' => $this->lang->line('name'),
                // 'name' => $this->lang->line('username'),
                'cid_user' => $this->lang->line('civil-no'),
                'email' => $this->lang->line('e-mail'),
                'password' => $this->lang->line('password'),
                'phone' => $this->lang->line('students') . ' ' . $this->lang->line('mobile'),
                'phone_father' => $this->lang->line('guardian') . ' ' . $this->lang->line('mobile'),
                'country' => $this->lang->line('nationality'),
                'city' => $this->lang->line('region'),
                'blocks' => $this->lang->line('block'),
                'street' => $this->lang->line('street'),
                'jadah' => $this->lang->line('jadah'),
                'floor' => $this->lang->line('floor'),
                'door_no' => $this->lang->line('door-number'),
                'address_link' => $this->lang->line('address-link'),
                'title' => $this->lang->line('title'),
                'age' => $this->lang->line('date-of-birth'),
                'sex' => $this->lang->line('sex'),
                'father_work' => $this->lang->line('father_work'),
                'mother_work' => $this->lang->line('mother_work'),
                'social_status' => $this->lang->line('social_status'),
                'note' => $this->lang->line('note'),
            );


            foreach ($fields_arr as $key => $val) {
                if (in_array($key, $required_fields)) {
                    $this->form_validation->set_rules($key, $val, 'trim|required');
                }
            }

            if ($this->input->post('email') && $data['edit']['email'] != $this->input->post('email')) {
                $this->form_validation->set_rules('email', $this->lang->line('email'), 'trim|is_unique[bills_user.email]');
            }
//            if ($this->input->post('username') && $data['edit']['username'] != $this->input->post('username')) {
//                $this->form_validation->set_rules('username', $this->lang->line('username'), 'trim|is_unique[bills_user.username]');
//            }
            if ($this->input->post('phone') && $data['edit']['phone'] != $this->input->post('phone')) {
                $this->form_validation->set_rules('phone', $this->lang->line('phone'), 'trim|is_unique[bills_user.phone]');
            }

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

                $add = FALSE;
            } else {
                // $imageuser=$data['edit']['imageuser'];
                $fieldname = 'imageuser';
                /*
                 * if ($_FILES[$fieldname]['name'] != "") {
                 * $upload_data = $this->booking->upload_many_photos($fieldname, $this->input->post('cid_user') . '1');
                 * $imageuser = "upload/" . $upload_data["file_name"];
                 * }
                 */
                $add = TRUE;

                $pass = $data['edit']['pass'];
                if ($this->input->post('new_password') != '') {
                    $pass = md5(md5($this->input->post('new_password')));
                }

                $edit_data = array(
                    'cid_user' => $this->input->post('cid_user'),
                    'username' => $this->input->post('username'),
                    'name' => $this->input->post('name'),
                    'email' => $this->input->post('email'),
                    'pass' => $pass,
                    'phone_code' => $this->input->post('countryCode'),
                    'phone' => $this->input->post('phone'),
                    'phone_father' => $this->input->post('phone_father'),
                    'nationality' => $this->input->post('country'),
                    'age' => $this->input->post('age'),
                    'sex' => $this->input->post('sex'),
                    'note' => $this->input->post('note'),
                    'father_job' => $this->input->post('father_work'),
                    'mother_job' => $this->input->post('mother_work'),
                    'social_status' => $this->input->post('social_status'),
                    'student_tags' => $this->input->post('student_tags') ? implode(',', $this->input->post('student_tags')) : '',
                        // 'imageuser' => $imageuser,
                );
                $edit_data = $this->security->xss_clean($edit_data);
                $result = $this->db->where('id', $id)->update('bills_user', $edit_data);
                // =====================================================

                $this->db->delete('addresses', array('user_id' => $id));
                //insert address

                for ($i = 0; $i < $this->input->post('address_count'); $i++) {

                    $data = array('region' => isset($this->input->post('city')[$i]) ? $this->input->post('city')[$i] : '',
                        'blocks' => isset($this->input->post('blocks')[$i]) ? $this->input->post('blocks')[$i] : '',
                        'floor' => isset($this->input->post('floor')[$i]) ? $this->input->post('floor')[$i] : '',
                        'jadah' => isset($this->input->post('jadah')[$i]) ? $this->input->post('jadah')[$i] : '',
                        'street' => isset($this->input->post('street')[$i]) ? $this->input->post('street')[$i] : '',
                        'door_no' => isset($this->input->post('door_no')[$i]) ? $this->input->post('door_no')[$i] : '',
                        'building_num' => isset($this->input->post('building_num')[$i]) ? $this->input->post('building_num')[$i] : '',
                        'address_link' => isset($this->input->post('address_link')[$i]) ? $this->input->post('address_link')[$i] : '',
                        'user_id' => $id
                    );
                    $this->db->insert('addresses', $data);
                }
                //=====


                $this->load->library('upload');
                $files = $_FILES;

                if ($_FILES['profile']['name']) {
                    $_FILES['userfile']['name'] = $files['profile']['name'];
                    $_FILES['userfile']['type'] = $files['profile']['type'];
                    $_FILES['userfile']['tmp_name'] = $files['profile']['tmp_name'];
                    $_FILES['userfile']['error'] = $files['profile']['error'];
                    $_FILES['userfile']['size'] = $files['profile']['size'];
                    $this->upload->initialize($this->set_upload_options());
                    $this->upload->do_upload();
                    $dataInfo = $this->upload->data();
                    $profile_image_name = $dataInfo['file_name'];
                    $gets = $this->db->where(array(
                                'user_id' => $id,
                                'profile_pic' => 1
                            ))
                            ->get('user_image')
                            ->row();
                    if ($gets) {
                        $this->db->where('image_id', $gets->image_id)->update('user_image', array(
                            'image' => $profile_image_name
                        ));
                    } else {
                        $this->db->insert('user_image', array(
                            'image' => $profile_image_name,
                            'user_id' => $id,
                            'profile_pic' => 1
                        ));
                    }
                }

                // $dataInfo = array();
                // $cpt = count($_FILES['imageuser']['name']);
                // for ($i = 0; $i < $cpt; $i++) {
                // $_FILES['userfile']['name'] = $files['imageuser']['name'][$i];
                // $_FILES['userfile']['type'] = $files['imageuser']['type'][$i];
                // $_FILES['userfile']['tmp_name'] = $files['imageuser']['tmp_name'][$i];
                // $_FILES['userfile']['error'] = $files['imageuser']['error'][$i];
                // $_FILES['userfile']['size'] = $files['imageuser']['size'][$i];
                // $this->upload->initialize($this->set_upload_options());
                // $this->upload->do_upload();
                // $dataInfo[] = $this->upload->data();
                // }
                // for ($i = 0; $i < $cpt; $i++) {
                // $datas[] = $dataInfo[$i]['file_name'];
                // }
                // $datass['image'] = implode(',', $datas);
                // $datass['user_id'] = $id;
                // $datass['last_update'] = date("m-d-Y h:m:sa");
                // $gets = $this->db->where(array('user_id' => $id, 'profile_pic' => 0))->get('user_image')->row();
                // if ($gets) {
                // $this->db->where('user_id', $id)->update('user_image', $datass);
                // } else {
                // $this->db->insert('user_image', $datass);
                // }
                if ($result) {
                    $this->session->set_flashdata('msg', 'تم تعديل الطالب بنجاح');
                    redirect(base_url('' . $this->thispage . '/index/'));
                }
            }
        }
        if (!$add) {
            $this->db->where('lable', 'nationality');
            $data['nationality'] = $this->db->get('datas')->result();
            $this->db->where('lable', 'region');
            $data['region'] = $this->db->get('datas')->result();

            $data['title'] = 'تعديل طالب';
            $data['thispage'] = $this->thispage;
            $this->load->model('points/Tag_Model');
            $data['student_tags'] = $this->Tag_Model->get_tag(2);
            $data['req_fields'] = $required_fields;
            $data['show_fields'] = explode(',', $sett->show_customer_fields);
            $data['addresses'] = $this->db->get_where('addresses', array('user_id' => $id))->result_array();
            $data['lang'] = $this->session->userdata("language");
            // $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_user', array(
            'oky' => 'ok',
            'comment' => $this->input->post('comment')
        ));

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

    function report() {
        if ($this->input->server('REQUEST_METHOD') == "POST") {
            $start_expiry = $this->input->post('start_expiry');

            $datearsh11 = explode("-", $start_expiry);

            $datearsh1 = explode("/", trim($datearsh11[0]));
            $first_date = "$datearsh1[2]/$datearsh1[0]/$datearsh1[1]";
            $datearsh1 = explode("/", trim($datearsh11[1]));
            $second_date = "$datearsh1[2]/$datearsh1[0]/$datearsh1[1]";
            $this->db->where('create_on >=', $first_date);
            $this->db->where('create_on <=', $second_date);
            $result = $this->db->get('bills_user')->result();
        } else {
            $result = $this->db->get('bills_user')->result();
        }
        if ($result) {
            $array = array();
            foreach ($result as $key => $result_value) {
                $array[] = array(
                    'user_id' => $result_value->id,
                    'name' => $result_value->username,
                    'email' => $result_value->email,
                    'civil_no' => $result_value->cid_user,
                    'mobile' => $result_value->phone,
                    'father_mobile' => $result_value->phone_father,
                    'city' => $result_value->region,
                    'country' => $result_value->nationality,
                    'note' => $result_value->note,
                    'age' => $result_value->age
                );
            }
        }
        if (!empty($array)) {
            export_csv($array, "user");
        } else {
            redirect(base_url("user/index"));
        }
    }

    function delete_absent_bulk() {
        $deleted = $this->input->post('delete');
        foreach ($deleted as $value => $key) {
            $this->db->delete('gyab', array(
                'sno' => $value
            ));
        }
        $this->session->set_flashdata('success', 1);
        redirect('user/absent_show');
    }

    function fields_settings() {
        if (!get_license_per('data_managment')) {
            redirect("", "refresh");
        }
        if (!get_ap('student_fields', $this->operator_id) == 1) {
            redirect("", "refresh");
        }
        if ($this->input->post()) {

            $this->db->update('setting', array(
                'customer_fields' => is_array($this->input->post('required')) ? implode(',', $this->input->post('required')) : '',
                'student_profile_customer_fields' => is_array($this->input->post('profile')) ? implode(',', $this->input->post('profile')) : '',
                'show_customer_fields' => is_array($this->input->post('show')) ? implode(',', $this->input->post('show')) : '',
                'student_can_edit_customer_fields' => is_array($this->input->post('edit')) ? implode(',', $this->input->post('edit')) : ''
            ));
            $this->session->set_flashdata('success', 'success');
            redirect(base_url($this->thispage . '/fields_settings'));
        }
        $this->db->select('customer_fields,student_profile_customer_fields,show_customer_fields,student_can_edit_customer_fields');
        $data['data'] = $this->db->get('setting')->row();
        $data['title'] = $this->lang->line('setting');
        $data['active'] = 'students_sett';
        $data['thispage'] = $this->thispage;
        $this->load->view('site/' . $this->thispage . '/fields_settings', $data);
    }

    function delete_img($user_id) {
        $img = $this->input->post('img_name');
        $imgs = $this->db->get_where('user_image', array(
                    'user_id' => $user_id,
                    'profile_pic' => 0
                ))->row();
        if ($imgs) {
            $new_imgs_str = str_replace($img . ',', '', $imgs->image);
            if (strpos($new_imgs_str, $img) !== false) {
                $new_imgs_str = str_replace($img, '', $imgs->image);
            }
            unlink('./public/upload/userimage/' . $img);
            $this->db->update('user_image', array(
                'image' => $new_imgs_str
                    ), array(
                'image_id' => $imgs->image_id
            ));
        }
    }

    function add_attachment($user_id) {
        $this->load->library('upload');
        $img_exist = $this->db->get_where('user_image', array(
                    'user_id' => $user_id,
                    'profile_pic' => 0
                ))->row();

        $files = $_FILES;
        $cpt = count($_FILES['imageuser']['name']);
        for ($i = 0; $i < $cpt; $i ++) {
            $_FILES['userfile']['name'] = $files['imageuser']['name'][$i];
            $_FILES['userfile']['type'] = $files['imageuser']['type'][$i];
            $_FILES['userfile']['tmp_name'] = $files['imageuser']['tmp_name'][$i];
            $_FILES['userfile']['error'] = $files['imageuser']['error'][$i];
            $_FILES['userfile']['size'] = $files['imageuser']['size'][$i];
            $this->upload->initialize($this->set_upload_options());
            $this->upload->do_upload();
            $dataInfo[] = $this->upload->data();
        }
        for ($i = 0; $i < $cpt; $i ++) {
            $datas[] = $dataInfo[$i]['file_name'];
        }
        $datass['image'] = implode(',', $datas);
        if ($img_exist) {
            $this->db->update('user_image', array(
                'image' => $img_exist->image . ',' . $datass['image']
                    ), array(
                'image_id' => $img_exist->image_id
            ));
        } else {
            $datass['user_id'] = $user_id;
            $datass['create_on'] = date("m-d-Y h:m:sa");
            $this->db->insert('user_image', $datass);
        }
        redirect(base_url('User/show/' . $user_id . '/success'));
    }

    function logs() {
        if (!get_ap('logs', $this->operator_id)) {
            redirect("", "refresh");
        }
        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('date(date) >=' => $from, 'date(date) <=' => $to));
        }
        $this->db->select('user.name,drivers.name as driver_name,logs.*');
        $this->db->join('user', 'user.id = logs.user_id and user_type = 0', 'left');
        $this->db->join('drivers', 'drivers.id = logs.user_id and user_type = 1', 'left');
        $this->db->order_by('date', 'DESC');
        $data['all_groups'] = $this->db->get('logs')->result();
        $data['title'] = $this->lang->line('logs');
        $data['thispage'] = $this->thispage;
        $this->load->view('site/' . $this->thispage . '/logs', $data);
    }

    function timezones() {
        $this->adjust_timezone('announcement', 'date_added');
        $this->adjust_timezone('bills_orders', 'created_on');
        $this->adjust_timezone('datas', 'create_on');
        $this->adjust_timezone('expense', 'expense_date,create_on');
        $this->adjust_timezone('expense_category', 'create_on');
        $this->adjust_timezone('groups', 'create_on,last_update');
        $this->adjust_timezone('gyab', 'create_on', 'sno');
        $this->adjust_timezone('kw_articles', 'created_at');
        $this->adjust_timezone('kw_categories', 'created_at');
        $this->adjust_timezone('kw_parent_categories', 'created_at');
        $this->adjust_timezone('language', 'create_on,last_update');
        $this->adjust_timezone('logs', 'date');
        $this->adjust_timezone('orders', 'timestamp,payment_time,expected_delivery_time');
        $this->adjust_timezone('payment_orders', 'payment_time,created_at');
        $this->adjust_timezone('pts_award', 'aupdated_on');
        $this->adjust_timezone('pts_award_history', 'h_update_on');
        $this->adjust_timezone('pts_barcode', 'time');
        $this->adjust_timezone('pts_category', 'category_update');
        $this->adjust_timezone('pts_student_history', 'update_on', 'history_id');
        $this->adjust_timezone('pts_tags', 'tagupdated_at', 'tag_id');
        $this->adjust_timezone('quraan_session_students', 'created_at');
        $this->adjust_timezone('quran_tsme3', 'timestamp');
    }

    function adjust_timezone($table, $cols, $id_col = 'id') {
        $this->db->select($id_col);
        $this->db->select($cols);
        $data = $this->db->get($table)->result();
        $cols_arr = explode(',', $cols);
        foreach ($data as $value) {
            $new_timezones = array();
            foreach ($cols_arr as $col) {
                if ($value->$col != '0000-00-00 00:00:00' && $value->$col != null && $value->$col < '2021-10-25 00:00:00')
                    $new_timezones[$col] = adjust_timezone($value->$col);
            }
            if (!empty($new_timezones))
                $this->db->update($table, $new_timezones, array('id' => $value->$id_col));
        }
    }

}

?>