<?php

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

class Students extends CI_Controller {

    public $thispage;

    public function __construct() {
        parent::__construct();
        if (!get_system_status()) {
            echo $this->load->view('site/system_off', '', TRUE);
            die();
        }
        set_system_timezone();
        $this->thispage = "students";
        $this->operator_id = $this->session->userdata('operator_id');
        $this->load->model('booking');
        if (!$this->session->userdata('is_student_login')) {
            redirect(base_url("auth/student_login"));
        }
    }

    public function index() {
        $this->db->select('bills_user.*,user_image.image');
        $this->db->join('user_image', 'user_image.user_id=bills_user.id and user_image.profile_pic = 1', 'left');
        $data['one'] = $this->db->get_where('bills_user', array('id' => $this->session->userdata('student_id')))->row();
        $this->db->where('lable', 'region');
        $data['region'] = $this->db->get('datas')->result();
        $this->db->where('lable', 'nationality');
        $data['nationality'] = $this->db->get('datas')->result();
        $data['thispage'] = $this->thispage;
        $data['active'] = 'profile';
        $this->db->select('student_profile_customer_fields,student_can_edit_customer_fields');
        $sett = $this->db->get('setting')->row();
        $data['student_profile_customer_fields'] = explode(',', $sett->student_profile_customer_fields);
        $data['editable'] = explode(',', $sett->student_can_edit_customer_fields);

        $this->load->view('site/students/profile', $data);
    }

    function update_personal_info() {
        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]');
        }
        if ($this->form_validation->run() === FALSE) {
            $this->session->set_flashdata('error', validation_errors());
            redirect(base_url('students'));
        } else {
            $data = array(
                'cid_user' => $this->input->post('cid_user'),
                'username' => $this->input->post('username'),
                'name' => $this->input->post('name'),
                'email' => $this->input->post('email'),
                'phone' => $this->input->post('phone'),
                'phone_father' => $this->input->post('phone_father'),
                'nationality' => $this->input->post('country'),
                'region' => $this->input->post('city'),
                //'city3' => $this->input->post('city3'),
                'age' => $this->input->post('age'),
                'sex' => $this->input->post('sex'),
                'note' => $this->input->post('note'),
                'blocks' => $this->input->post('blocks'),
                'floor' => $this->input->post('floor'),
                'jadah' => $this->input->post('jadah'),
                'street' => $this->input->post('street'),
                'door_no' => $this->input->post('door_no'),
                //'country' => $this->input->post('blocks') . ' ' . $this->input->post('floor') . ' ' . $this->input->post('jadah') . ' ' . $this->input->post('street') . ' ' . $this->input->post('door_no'),
                'address_link' => $this->input->post('address_link'),
                'create_on' => date('m-d-Y m:h:sa'),
                // 'imageuser' => $imageuser,
                'since_time_register' => $this->booking->tissme_now(),
                'father_job' => $this->input->post('father_work'),
                'mother_job' => $this->input->post('mother_work'),
                'social_status' => $this->input->post('social_status'),
            );
            if ($this->input->post('new_password') != '') {
                $data['pass'] = md5(md5($this->input->post('new_password')));
            }
            if ($_FILES['profile_avatar']['name'] != '') {
                $files = $_FILES;
                $_FILES['userfile']['name'] = $files['profile_avatar']['name'];
                $_FILES['userfile']['type'] = $files['profile_avatar']['type'];
                $_FILES['userfile']['tmp_name'] = $files['profile_avatar']['tmp_name'];
                $_FILES['userfile']['error'] = $files['profile_avatar']['error'];
                $_FILES['userfile']['size'] = $files['profile_avatar']['size'];
                $this->load->library('upload');
                $this->upload->initialize($this->set_upload_options());
                if (!$this->upload->do_upload()) {
                    $this->session->set_flashdata('error', $this->upload->display_errors());
                    redirect(base_url('students'));
                }
                $dataInfo = $this->upload->data();
                $image_name = $dataInfo['file_name'];
                $exist = $this->db->get_where('user_image', array('user_id' => $this->session->userdata('student_id')))->row();
                if ($exist) {
                    $this->db->update('user_image', array('image' => $image_name, 'last_update' => date('Y-m-d H:i:s')), array('image_id' => $exist->image_id));
                } else {
                    $this->db->insert('user_image', array('image' => $image_name, 'user_id' => $this->session->userdata('student_id'), 'create_on' => date('Y-m-d H:i:s')));
                }
            }
            $files = $_FILES;
            $cpt = count($_FILES['imageuser']['name']);
            $this->load->library('upload');
            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());
                if (!$this->upload->do_upload()) {
                    $this->session->set_flashdata('error', $this->upload->display_errors());
                    redirect(base_url('students'));
                }
                $dataInfo[] = $this->upload->data();
            }
            for ($i = 0; $i < $cpt; $i ++) {
                $datas[] = $dataInfo[$i]['file_name'];
            }
            if (!empty($datas)) {
                $datass['image'] = implode(',', $datas);
                $datass['user_id'] = $this->session->userdata('student_id');
                $datass['create_on'] = date("m-d-Y h:m:sa");
                $this->db->insert('user_image', $datass);
            }

            $this->db->update('bills_user', $data, array('id' => $this->session->userdata('student_id')));
            $this->session->set_flashdata('success', 'success');
            redirect(base_url('students'));
        }
    }

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

    function attendance() {
        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');
        $this->db->where('gyab.user_id', $this->session->userdata('student_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('distinct(id_producer) as id,name_order as name');
        $data['products'] = $this->db->get_where('bills_orders', array('id_user' => $this->session->userdata('student_id')))->result();
        // $this->db->select('id,name');
        // $data['products'] = $this->db->get_where('bills_producer')->result();
        $data['title'] = $this->lang->line('absent');
        $data['thispage'] = $this->thispage;
        $this->db->select('bills_user.*,user_image.image');
        $this->db->join('user_image', 'user_image.user_id=bills_user.id and user_image.profile_pic = 1', 'left');
        $data['one'] = $this->db->get_where('bills_user', array('id' => $this->session->userdata('student_id')))->row();
        $data['active'] = 'attend';
        $this->load->view('site/students/attendance', $data);
    }

    public function invoices() {
        $id_producer = $this->input->post('products');
        $active = $this->input->post('active');
        $whr = '';
        $data['id_producer'] = $id_producer;
        $data['active'] = $active;
        if (($id_producer))
            $this->db->where_in('id_producer', $id_producer);
        if (($active))
            $whr = "$whr and active=" . str_replace("2", "0", $active);
        if ($whr)
            $this->db->where($whr);

        $this->db->where('id_user', $this->session->userdata('student_id'));
        $this->db->from('bills_orders');
        $this->db->order_by('id', 'desc');
        if ($whr)
            $this->db->where($whr);
        $this->db->select('bills_orders.*,sum(bills_orders.discount_remainder) as total_price');
        $this->db->group_by('id_orders');
        $data['all_groups'] = $this->db->get()->result_array();
        //echo $this->db->last_query();die;
        // $data['view'] = '../controllers/views/' . $this->thispage . '/all';
        $data['thispage'] = $this->thispage;
        $data['active'] = 'invoice';
        $this->db->select('bills_user.*,user_image.image');
        $this->db->join('user_image', 'user_image.user_id=bills_user.id and user_image.profile_pic = 1', 'left');
        $data['one'] = $this->db->get_where('bills_user', array('id' => $this->session->userdata('student_id')))->row();
        // $this->db->select('id,name');
        // $data['products'] = $this->db->get_where('bills_producer')->result();
        $this->db->select('distinct(id_producer) as id,name_order as name');
        $data['products'] = $this->db->get_where('bills_orders', array('id_user' => $this->session->userdata('student_id')))->result();
        $this->load->view('site/' . $this->thispage . '/invoices', $data);
    }

    function membership() {
        $whr = '';
        $id_producer = $this->input->post('products');
        $active = $this->input->post('active');
        if (($id_producer))
            $this->db->where_in('id_producer', $id_producer);
        if (($active))
            $whr = "$whr and active=" . str_replace("2", "0", $active);
        $this->db->from('bills_orders');
        if ($whr)
            $this->db->where($whr);
        $max = 40;
        $this->db->order_by('bills_orders.id', 'desc');
        if ($whr)
            $this->db->where($whr);
        $this->db->select('bills_orders.*');
        $this->db->join('bills_producer', 'bills_producer.id=bills_orders.id_producer and bills_producer.type=2');
        $this->db->where('bills_orders.id_user', $this->session->userdata('student_id'));
        $data['all_groups'] = $this->db->get()->result_array();
        $data['active'] = 'membership';
        $this->db->select('bills_user.*,user_image.image');
        $this->db->join('user_image', 'user_image.user_id=bills_user.id and user_image.profile_pic = 1', 'left');
        $data['one'] = $this->db->get_where('bills_user', array('id' => $this->session->userdata('student_id')))->row();
        $data['thispage'] = $this->thispage;
        //$this->db->select('id,name');
        //$data['products'] = $this->db->get_where('bills_producer')->result();
        $this->db->select('distinct(id_producer) as id,name_order as name');
        $data['products'] = $this->db->get_where('bills_orders', array('id_user' => $this->session->userdata('student_id')))->result();
        $this->load->view('site/' . $this->thispage . '/membership', $data);
    }

    function inbox() {
        if ($this->input->post()) {
            $product = $this->input->post('products');
            $this->db->where_in('product_id', $product);
        }
        $this->db->select('announcement.*,bills_producer.name as product_name');
        $this->db->join('bills_producer', 'bills_producer.id=announcement.product_id');
        $this->db->order_by('announcement.date_added', 'DESC');
        $announcments = $this->db->get_where('announcement', array('announcement.start_date <=' => date('Y-m-d'), 'announcement.end_date >=' => date('Y-m-d'), 'students!=' => ''))->result();
        $ann_arr = array();
        foreach ($announcments as $ann) {
            $students = explode(',', $ann->students);
            if (in_array($this->session->userdata('student_id'), $students)) {
                $ann_arr[] = $ann;
            }
        }
        $data['announcments'] = $ann_arr;
        $this->db->select('bills_user.*,user_image.image');
        $this->db->join('user_image', 'user_image.user_id=bills_user.id and user_image.profile_pic = 1', 'left');
        $data['one'] = $this->db->get_where('bills_user', array('id' => $this->session->userdata('student_id')))->row();
        $data['thispage'] = $this->thispage;
        // $this->db->select('id,name');
        // $data['products'] = $this->db->get_where('bills_producer')->result();
        $this->db->select('distinct(id_producer) as id,name_order as name');
        $data['products'] = $this->db->get_where('bills_orders', array('id_user' => $this->session->userdata('student_id')))->result();
        $data['active'] = 'inbox';
        $this->load->view('site/' . $this->thispage . '/inbox', $data);
    }

    function advs() {
        if ($this->input->post()) {
            $product = $this->input->post('products');
            $this->db->where_in('product_id', $product);
        }
        $this->db->select('announcement.*,bills_producer.name as product_name');
        $this->db->join('bills_producer', 'bills_producer.id=announcement.product_id');
        $this->db->join('bills_orders', 'bills_orders.id_producer = announcement.product_id and bills_orders.id_user = ' . $this->session->userdata('student_id'));
        $this->db->order_by('announcement.date_added', 'DESC');
        $data['announcments'] = $this->db->get_where('announcement', array('announcement.start_date <=' => date('Y-m-d'), 'announcement.end_date >=' => date('Y-m-d'), 'students' => ''))->result();

        $this->db->select('bills_user.*,user_image.image');
        $this->db->join('user_image', 'user_image.user_id=bills_user.id and user_image.profile_pic = 1', 'left');
        $data['one'] = $this->db->get_where('bills_user', array('id' => $this->session->userdata('student_id')))->row();
        $data['thispage'] = $this->thispage;
        // $this->db->select('id,name');
        //$data['products'] = $this->db->get_where('bills_producer')->result();
        $this->db->select('distinct(id_producer) as id,name_order as name');
        $data['products'] = $this->db->get_where('bills_orders', array('id_user' => $this->session->userdata('student_id')))->result();
        $data['active'] = 'advs';
        $this->load->view('site/' . $this->thispage . '/advs', $data);
    }

    function quran_sessions() {

        $this->db->select('quraan_sessions.title as name,quraan_sessions.id as id');
        $this->db->select('SUM(CASE WHEN quran_tsme3.type = 0 THEN quran_tsme3.pages_count ELSE 0 END) AS hfz');
        $this->db->select('SUM(CASE WHEN quran_tsme3.type = 1 THEN quran_tsme3.pages_count ELSE 0 END) AS mrg3a');
        $this->db->select('SUM(CASE WHEN quran_tsme3.type = 2 THEN quran_tsme3.pages_count ELSE 0 END) AS srd');
        $this->db->select('SUM(CASE WHEN quran_tsme3.type = 3 THEN quran_tsme3.pages_count ELSE 0 END) AS tlawa');
        $this->db->select('SUM(CASE WHEN quran_tsme3.type = 4 THEN quran_tsme3.pages_count ELSE 0 END) AS tlken');
        $this->db->select('SUM(CASE WHEN quran_tsme3.type = 5 THEN quran_tsme3.pages_count ELSE 0 END) AS test');
        $this->db->join('quraan_sessions', 'quraan_sessions.id = quraan_session_students.session_id');
        $this->db->join('quran_tsme3', 'quran_tsme3.product_id = quraan_session_students.session_id and quran_tsme3.student=' . $this->session->userdata('student_id'), 'left');
        $this->db->group_by('quraan_session_students.session_id');
        $data['all_groups'] = $this->db->get_where('quraan_session_students', array(
                    'quraan_session_students.student_id' => $this->session->userdata('student_id')
                ))->result_array();
        for ($i = 0; $i < count($data['all_groups']); $i++) {
            $this->db->select('name');
            $this->db->join('teachers', 'teachers.id = quraan_session_teachers.teacher_id');
            $teachers = $this->db->get_where('quraan_session_teachers', array('session_id' => $data['all_groups'][$i]['id']))->result();
            $teachers_name = array();
            foreach ($teachers as $teacher) {
                array_push($teachers_name, $teacher->name);
            }
            $data['all_groups'][$i]['teacher_name'] = implode(',', $teachers_name);
        }

        $data['thispage'] = $this->thispage;


        $data['active'] = 'quran';
        $this->db->select('bills_user.*,user_image.image');
        $this->db->join('user_image', 'user_image.user_id=bills_user.id and user_image.profile_pic = 1', 'left');
        $data['one'] = $this->db->get_where('bills_user', array('id' => $this->session->userdata('student_id')))->row();
        $this->load->view('site/' . $this->thispage . '/quran_sessions', $data);
    }

    function show_detailed_recite($product_id) {
        $student_id = $this->session->userdata('student_id');
        $data['student_name'] = $this->db->get_where('bills_user', array('id' => $student_id))->row()->username;
        $data['product_name'] = $this->db->get_where('bills_producer', array('id' => $product_id))->row()->name;

        $this->db->select('q1.arabic as from_s,q2.arabic as to_s,quran_tsme3.*');
        $this->db->join('quran_surah q2', 'q2.id =  quran_tsme3.to_surah');
        $this->db->join('quran_surah q1', 'q1.id =  quran_tsme3.from_surah');
        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(
                    'quran_tsme3.timestamp >=' => $from,
                    'quran_tsme3.timestamp <=' => $to
                ));
            }
        }
        $data['details'] = $this->db->get_where('quran_tsme3', array('product_id' => $product_id, 'student' => $student_id))->result_array();

        $this->db->select('bills_user.*,user_image.image');
        $this->db->join('user_image', 'user_image.user_id=bills_user.id and user_image.profile_pic = 1', 'left');
        $data['one'] = $this->db->get_where('bills_user', array('id' => $this->session->userdata('student_id')))->row();

        $data['active'] = 'quran';
        $data['thispage'] = $this->thispage;
        $data['title'] = $this->lang->line('quraan_session');
        $this->load->view('site/' . $this->thispage . '/detailed_recite', $data);
    }

    function lang($lang) {
        $this->session->set_userdata("language", $lang);
    }

    function logout() {
        $this->session->sess_destroy();
        redirect(base_url('auth/student_login'));
    }

}
