<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Academic extends School 
{
    /*
        Software: EduAppGT PRO - Learning Management System
        Author: GuateApps - Software, Web and Mobile developer.
        Author URI: https://guateapps.app.
        PHP: 5.6+
        Created: 27 September 16.
    */

    private $runningYear = '';
    
    function __construct() 
    {
        parent::__construct();
        $this->load->database();
        $this->load->library('excel');
        $this->runningYear = $this->db->get_where('settings' , array('type' => 'running_year'))->row()->description;
    }
    
    function getLastUpdate($subjectID)
    {
        $ltype = $this->session->userdata('login_type');
        $this->db->where('subject_id', $subjectID);
        $this->db->where('year', $this->runningYear);
        if($ltype == 'student' || $ltype == 'parent'){
            $this->db->where('status',1);    
        }
        $this->db->order_by('order_time', 'DESC');
        $this->db->limit(1);
        $query = $this->db->get('activity');
        if($query->num_rows() > 0){
            return $query->row()->order_time;
        }else{
            return 0;
        }
    }
    
    function getTotalActivities($data){
        $ltype = $this->session->userdata('login_type');

        $in = base64_decode($data);
        $ex = explode('-',$in);
        $this->db->where('class_id', $ex[0]);
        $this->db->where('section_id', $ex[1]);
        $this->db->where('subject_id', $ex[2]);
        $this->db->where('year', $this->runningYear);
        if($ltype == 'student' || $ltype == 'parent'){
            $this->db->where('status',1);    
        }
        return $this->db->get('activity')->num_rows();
    }
    
    function publishExam($activityID)
    {
        $notified = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->notified;
        $uploaderT = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->uploader_role;
        $upladerI = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->uploader_id;
        if($notified == 0)
        { 
            $this->crud->customExamNotify($activityID);
        }
        $data['status'] = 1;
        $data['notified'] = 1;
        $this->db->where('activity_id', $activityID);
        $this->db->update('activity', $data);
    }
    
    public function createOnlineExam()
    {
        $data['date']          = $this->crud->getDateFormat().' '.date('h:i A');
        $data['delivery_date'] = date('Y-m-d',strtotime($this->input->post('exam_date')));
        $data['class_id']      = $this->input->post('class_id');
        $data['certificate']   = $this->input->post('certificate');
        $data['section_id']    = $this->input->post('section_id');
        $data['subject_id']    = $this->input->post('subject_id');
        $data['start_time']    = $this->input->post('time_start');
        $data['end_time']      = $this->input->post('time_end');
        $data['description']   = $this->input->post('instruction');
        $data['title']         = $this->input->post('title');
        $data['isRandom']      = $this->input->post('show_random');
        $data['percentage']    = $this->input->post('minimum_percentage');
        $data['password']      = base64_encode($this->input->post('password'));
        $data['showResults']   = $this->input->post('results');
        if($this->input->post('status') == 1){
            $data['status']    = $this->input->post('status');   
            $data['notified']  = 1; 
        }
        $data['duration']      = strtotime(date('Y-m-d', strtotime($data['delivery_date'])).' '.$data['end_time']) - strtotime(date('Y-m-d', strtotime($data['delivery_date'])).' '.$data['start_time']);
        $data['activity_type'] = 'exam';
        $data['uploader_role'] = $this->session->userdata('login_type');
        $data['uploader_id']   = $this->session->userdata('login_user_id');
        $data['year']          = $this->runningYear;
        $this->db->insert('activity', $data);
        
        if($this->input->post('status') == 1)
        {
            $body = "<strong>".$this->crud->get_name($this->session->userdata('login_type'),$this->session->userdata('login_user_id'))."</strong>". " ". getEduAppGTLang('new_live_class_notify');
            $this->submitNotify($body);   
        }
    }
    
    public function updateOnlineExam($activityID)
    {
        $notified = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->notified;
        $uploaderT = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->uploader_role;
        $upladerI = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->uploader_id;
        if($this->input->post('status') == 1 && $notified == 0)
        { 
            $body = "<strong>".$this->crud->get_name($this->session->userdata('login_type'),$this->session->userdata('login_user_id'))."</strong>". " ". getEduAppGTLang('new_live_class_notify');
            $this->submitNotify($body);   
            $this->crud->send_exam_notify();
        }
        $data['delivery_date'] = date('Y-m-d',strtotime($this->input->post('exam_date')));
        $data['certificate']   = $this->input->post('certificate');
        $data['start_time']    = $this->input->post('time_start');
        $data['end_time']      = $this->input->post('time_end');
        $data['description']   = $this->input->post('instruction');
        $data['title']         = $this->input->post('title');
        $data['isRandom']      = $this->input->post('show_random');
        $data['percentage']    = $this->input->post('minimum_percentage');
        $data['password']      = base64_encode($this->input->post('password'));
        $data['showResults']   = $this->input->post('results');
        if($this->input->post('status') == 1){
            $data['status']    = $this->input->post('status');   
            $data['notified']  = 1; 
        }
        $data['duration']      = strtotime(date('Y-m-d', strtotime($data['delivery_date'])).' '.$data['end_time']) - strtotime(date('Y-m-d', strtotime($data['delivery_date'])).' '.$data['start_time']);
        $data['year']          = $this->runningYear;
        $this->db->where('activity_id', $activityID);
        $this->db->update('activity', $data);
    }
    
    function getHomeworks($data)
    {
        $ltype = $this->session->userdata('login_type');
        $in = base64_decode($data);
        $ex = explode('-',$in);
        $this->db->where('class_id', $ex[0]);
        $this->db->where('section_id', $ex[1]);
        $this->db->where('subject_id', $ex[2]);
        $this->db->where('year', $this->runningYear);
        $this->db->where('activity_type', 'homework');
        if($ltype == 'student' || $ltype == 'parent'){
            $this->db->where('status',1);    
        }
        $this->db->order_by('order_time', 'DESC');
        return $this->db->get('activity')->result_array();
    }
    
    function getOnlineExams($data)
    {
        $ltype = $this->session->userdata('login_type');
        $in = base64_decode($data);
        $ex = explode('-',$in);
        $this->db->where('class_id', $ex[0]);
        $this->db->where('section_id', $ex[1]);
        $this->db->where('subject_id', $ex[2]);
        $this->db->where('year', $this->runningYear);
        $this->db->where('activity_type', 'exam');
        if($ltype == 'student' || $ltype == 'parent'){
            $this->db->where('status',1);    
        }
        $this->db->order_by('order_time', 'DESC');
        return $this->db->get('activity')->result_array();
    }
    
    function deleteHomework($activityID)
    {
        $fileName = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->file;
        unlink("public/uploads/homework/" . $fileName);
        $this->db->where('activity_id', $activityID);
        $this->db->delete('activity');
    }
    
    public function createHomework()
    {
        $fileName = 'file-'.uniqid().'-'.str_replace(" ", "",$_FILES["file_name"]["name"]);
        
        $data['date']          = $this->crud->getDateFormat().' '.date('h:i A');
        $data['delivery_date'] = date('Y-m-d',strtotime($this->input->post('start_date')));
        $data['class_id']      = $this->input->post('class_id');
        $data['section_id']    = $this->input->post('section_id');
        $data['subject_id']    = $this->input->post('subject_id');
        $data['title']         = html_escape($this->input->post('title'));
        $data['description']   = html_escape($this->input->post('description'));
        $data['homework_type'] = $this->input->post('type');
        if($this->input->post('status') == 1){
            $data['status']    = $this->input->post('status');   
            $data['notified']  = 1; 
        }
        if($_FILES["file_name"]["size"] > 0){
            $data['file']      = $fileName;   
            $data['file_size'] = $this->crud->formatBytes($_FILES["file_name"]["size"]);
            $data['real_name'] = $_FILES["file_name"]["name"];   
        }
        $data['end_time']      = html_escape($this->input->post('time_end'));
        $data['delivery_date'] = html_escape(date('Y-m-d',strtotime($this->input->post('date_end'))));
        $data['activity_type'] = 'homework';
        $data['uploader_role'] = $this->session->userdata('login_type');
        $data['uploader_id']   = $this->session->userdata('login_user_id');
        $data['year']          = $this->runningYear;
        $this->db->insert('activity', $data);
        
        if($this->input->post('status') == 1)
        {
            $body = "<strong>".$this->crud->get_name($this->session->userdata('login_type'),$this->session->userdata('login_user_id'))."</strong>". " ". getEduAppGTLang('new_homework_notify') ." <b>".html_escape($this->input->post('title'))."</b>";
            $this->submitNotify($body);
            $this->crud->send_homework_notify();
        }
        move_uploaded_file($_FILES["file_name"]["tmp_name"], "public/uploads/homework/" . $fileName);
    }
    
    public function updateHomework($activityID)
    {
        $fileName = 'file-'.uniqid().'-'.str_replace(" ", "",$_FILES["file_name"]["name"]);
        $notified = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->notified;
        $uploaderT = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->uploader_role;
        $upladerI = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->uploader_id;
        if($this->input->post('status') == 1 && $notified == 0)
        { 
            $body = "<strong>".$this->crud->get_name($this->session->userdata('login_type'),$this->session->userdata('login_user_id'))."</strong>". " ". getEduAppGTLang('new_homework_notify') ." <b>".html_escape($this->input->post('title'))."</b>";
            $this->submitNotify($body);   
            $this->crud->send_homework_notify();
        }
        $data['homework_type'] = $this->input->post('type');
        $data['delivery_date'] = date('Y-m-d',strtotime($this->input->post('date_end')));
        $data['title']         = $this->input->post('title');
        $data['end_time']      = $this->input->post('time_end');
        $data['description']   = $this->input->post('description');
        if($this->input->post('status') == 1)
        {
            $data['status']        = $this->input->post('status');   
            $data['notified']  = 1; 
        }else{
            $data['status']        = 0;   
        }
        if($_FILES["file_name"]["size"] > 0){
            $data['file']      = $fileName;   
            $data['file_size'] = $this->crud->formatBytes($_FILES["file_name"]["size"]);
            $data['real_name'] = $_FILES["file_name"]["name"];   
        }
        $this->db->where('activity_id', $activityID);
        $this->db->update('activity', $data);
        move_uploaded_file($_FILES["file_name"]["tmp_name"], "public/uploads/homework/" . $fileName);
    }
    
    function createLive()
    {
        $data['date']          = $this->crud->getDateFormat().' '.date('h:i A');
        $data['delivery_date'] = date('Y-m-d',strtotime($this->input->post('start_date')));
        $data['class_id']      = $this->input->post('class_id');
        $data['section_id']    = $this->input->post('section_id');
        $data['subject_id']    = $this->input->post('subject_id');
        $data['description']   = $this->input->post('description');
        $data['title']         = $this->input->post('title');
        $data['meet_id']       = $this->input->post('zoom_meeting_id');
        $data['meet_password'] = $this->input->post('zoom_meeting_password');
        $data['url']           = $this->input->post('zoomURL');
        $data['start_time']    = $this->input->post('start_time');
        $data['end_time']      = $this->input->post('end_time');
        if($this->input->post('status') == 1){
            $data['status']    = $this->input->post('status');   
            $data['notified']  = 1; 
        }
        $data['activity_type']  = 'live';
        $data['uploader_role'] = $this->session->userdata('login_type');
        $data['uploader_id']   = $this->session->userdata('login_user_id');
        $data['year']          = $this->runningYear;
        $this->db->insert('activity', $data);
        
        if($this->input->post('status') == 1)
        {
            $body = "<strong>".$this->crud->get_name($this->session->userdata('login_type'),$this->session->userdata('login_user_id'))."</strong>". " ". getEduAppGTLang('new_live_class_notify');
            $this->submitNotify($body);   
        }
    }
    
    function updateLive($activityID)
    {
        $notified = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->notified;
        $uploaderT = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->uploader_role;
        $upladerI = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->uploader_id;
        if($this->input->post('status') == 1 && $notified == 0)
        { 
            $body = "<strong>".$this->crud->get_name($uploaderT,$upladerI)."</strong>". " ". getEduAppGTLang('new_live_class_notify');
            $this->submitNotify($body);   
        }
        $data['delivery_date'] = date('Y-m-d',strtotime($this->input->post('start_date')));
        $data['title']         = $this->input->post('title');
        $data['start_time']    = $this->input->post('start_time');
        $data['end_time']      = $this->input->post('end_time');
        $data['description']   = $this->input->post('description');
        if($this->input->post('status') == 1)
        {
            $data['status']        = $this->input->post('status');   
            $data['notified']  = 1; 
        }else{
            $data['status']        = 0;   
        }
        $this->db->where('activity_id', $activityID);
        $this->db->update('activity', $data);
    }
    
    function finishLive($id)
    {
        $data['isFinished'] = 1;
        $this->db->where('activity_id', $id);
        $this->db->update('activity', $data);
    }
    
    function deleteLive($id)
    {
        $this->db->where('activity_id', $id);
        $this->db->delete('activity');
    }
    
    function deleteVideo($id)
    {
        $this->db->where('activity_id', $id);
        $this->db->delete('activity');
    }
    
    function updateVideo($activityID)
    {
        $notified = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->notified;
        $uploaderT = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->uploader_role;
        $upladerI = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->uploader_id;
        if($this->input->post('status') == 1 && $notified == 0)
        { 
            $body = "<strong>".$this->crud->get_name($uploaderT,$upladerI)."</strong>". " ". getEduAppGTLang('new_video_notify');
            $this->submitNotify($body);   
        }
        if($this->input->post('dur') != '' && $this->input->post('dur') != '00:00'){
            $data['duration']      = $this->input->post('dur');   
            $data['isDuration']      = 1;
        }
        $data['description']   = $this->input->post('description');
        if($this->input->post('status') == 1)
        {
            $data['status']        = $this->input->post('status');   
            $data['notified']  = 1; 
        }else{
            $data['status']        = 0;   
        }
        $this->db->where('activity_id', $activityID);
        $this->db->update('activity', $data);
    }
    
    function createVideo()
    {
        $data['date']          = $this->crud->getDateFormat().' '.date('h:i A');
        $data['class_id']      = $this->input->post('class_id');
        $data['section_id']    = $this->input->post('section_id');
        $data['subject_id']    = $this->input->post('subject_id');
        $data['description']   = $this->input->post('description');
        if($this->input->post('duration') != ''){
            $data['duration']      = gmdate("H:i:s", intval($this->input->post('duration')));   
            $data['isDuration']      = 1;
        }else{
            $data['duration']      = '00:00';
            $data['isDuration']      = 0;
        }
        $data['url']           = $this->input->post('embed');
        if($this->input->post('status') == 1){
            $data['status']    = $this->input->post('status');   
            $data['notified']  = 1; 
        }
        $data['activity_type']  = 'video';
        $data['uploader_role'] = $this->session->userdata('login_type');
        $data['uploader_id']   = $this->session->userdata('login_user_id');
        $data['year']          = $this->runningYear;
        $this->db->insert('activity', $data);
        
        if($this->input->post('status') == 1)
        {
            $body = "<strong>".$this->crud->get_name($this->session->userdata('login_type'),$this->session->userdata('login_user_id'))."</strong>". " ". getEduAppGTLang('new_video_notify');
            $this->submitNotify($body);   
        }
    }
    
    public function updateForum($activityID)
    {
        $notified = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->notified;
        $fileName = 'file-'.uniqid().'-'.str_replace(" ", "",$_FILES["file_name"]["name"]);
        if($this->input->post('status') == 1){
            $data['status']    = $this->input->post('status');   
            $data['notified']  = 1; 
        }
        if($_FILES["file_name"]["size"] > 0)
        {
            $data['file']          = $fileName;
            $data['real_name']     = $_FILES["file_name"]["name"];
            $data['file_size']     = $this->crud->formatBytes($_FILES["file_name"]["size"]);   
        }
        $data['title']         = html_escape($this->input->post('title'));
        $data['description']   = html_escape($this->input->post('description'));
        $this->db->where('activity_id', $activityID);
        $this->db->update('activity', $data);
        move_uploaded_file($_FILES["file_name"]["tmp_name"], "public/uploads/forum/" . $fileName);
        if($this->input->post('status') == 1 && $notified == 0)
        {
            $this->crud->send_forum_notify();
        }
    }
    
    function getAttendanceForChart($days, $subject_id)
    {
        $exp = explode(',',$days);
        $value = '';
        for($i = 0; $i < count($exp); $i++)
        {
            $value .= $this->db->get_where('attendance', array('subject_id' => $subject_id, 'status' => 1,'timestamp' => strtotime(date('d-m-Y',strtotime($exp[$i])))))->num_rows().',';
        }
        return $value;
    }
    
    function getAllAttendance($subject_id)
    {
        $monday = '';
        if(date('D') != 'Mon'){
            $monday = date('Y-m-d',strtotime('last Monday'));    
        }else{
            $monday = date('Y-m-d');
        }
        $tuesday   = date('Y-m-d',strtotime("$monday +1 days"));
        $wednesday = date('Y-m-d',strtotime("$monday +2 days"));
        $thursday  = date('Y-m-d',strtotime("$monday +3 days"));
        $friday    = date('Y-m-d',strtotime("$monday +4 days"));
        $saturday  = date('Y-m-d',strtotime("$monday +5 days"));
        $sunday    = date('Y-m-d',strtotime("$monday +6 days"));
        
        $labels = getEduAppGTLang(date('D',strtotime($monday))).','.getEduAppGTLang(date('D',strtotime($tuesday))).','.getEduAppGTLang(date('D',strtotime($wednesday))).','.getEduAppGTLang(date('D',strtotime($thursday))).','.getEduAppGTLang(date('D',strtotime($friday))).','.getEduAppGTLang(date('D',strtotime($saturday))).','.getEduAppGTLang(date('D',strtotime($sunday)));
        $values = $monday.','.$tuesday.','.$wednesday.','.$thursday.','.$friday.','.$saturday.','.$sunday;
        
        $response = array(
            'labels' => $labels,
            'values' => rtrim($this->getAttendanceForChart($values,$subject_id),',')
        );
        return $response;
    }
    
    
    function getMyAttendance($subject_id, $student_id)
    {
        $monday = '';
        if(date('D') != 'Mon'){
            $monday = date('Y-m-d',strtotime('last Monday'));    
        }else{
            $monday = date('Y-m-d');
        }
        $tuesday   = date('Y-m-d',strtotime("$monday +1 days"));
        $wednesday = date('Y-m-d',strtotime("$monday +2 days"));
        $thursday  = date('Y-m-d',strtotime("$monday +3 days"));
        $friday    = date('Y-m-d',strtotime("$monday +4 days"));
        $saturday  = date('Y-m-d',strtotime("$monday +5 days"));
        $sunday    = date('Y-m-d',strtotime("$monday +6 days"));
        
        $labels = getEduAppGTLang(date('D',strtotime($monday))).','.getEduAppGTLang(date('D',strtotime($tuesday))).','.getEduAppGTLang(date('D',strtotime($wednesday))).','.getEduAppGTLang(date('D',strtotime($thursday))).','.getEduAppGTLang(date('D',strtotime($friday))).','.getEduAppGTLang(date('D',strtotime($saturday))).','.getEduAppGTLang(date('D',strtotime($sunday)));
        $values = $monday.','.$tuesday.','.$wednesday.','.$thursday.','.$friday.','.$saturday.','.$sunday;
        
        $response = array(
            'labels' => $labels,
            'values' => rtrim($this->getMyAttendanceForChart($values,$subject_id, $student_id),',')
        );
        return $response;
    }
    
    function getMyAttendanceForChart($days, $subject_id, $student_id)
    {
        $exp = explode(',',$days);
        $value = '';
        for($i = 0; $i < count($exp); $i++)
        {
            $value .= $this->db->get_where('attendance', array('student_id' => $student_id,'subject_id' => $subject_id, 'status' => 1,'timestamp' => strtotime(date('d-m-Y',strtotime($exp[$i])))))->num_rows().',';
        }
        return $value;
    }
    
    public function createForum()
    {
        $fileName = 'file-'.uniqid().'-'.str_replace(" ", "",$_FILES["file_name"]["name"]);
        $data['date']          = $this->crud->getDateFormat().' '.date('h:i A');
        $data['delivery_date'] = date('Y-m-d');
        $data['class_id']      = $this->input->post('class_id');
        $data['section_id']    = $this->input->post('section_id');
        $data['subject_id']    = $this->input->post('subject_id');
        $data['title']         = html_escape($this->input->post('title'));
        $data['description']   = $this->input->post('description');
        if($this->input->post('status') == 1){
            $data['status']    = $this->input->post('status');   
            $data['notified']  = 1; 
        }
        $data['activity_type']  = 'forum';
        $data['uploader_role'] = $this->session->userdata('login_type');
        $data['uploader_id']   = $this->session->userdata('login_user_id');
        $data['year']          = $this->runningYear;
        if($_FILES["file_name"]["size"] > 0){
            $data['file']          = $fileName;
            $data['real_name']     = $_FILES["file_name"]["name"];
            $data['file_size']     = $this->crud->formatBytes($_FILES["file_name"]["size"]);   
        }
        $this->db->insert('activity', $data);
        move_uploaded_file($_FILES["file_name"]["tmp_name"], "public/uploads/forum/" . $fileName);
        if($this->input->post('status') == 1)
        {
            $this->crud->send_forum_notify();
        }
    }
    
    function getSubjectLives($data)
    {
        $ltype = $this->session->userdata('login_type');
        $in = base64_decode($data);
        $ex = explode('-',$in);
        $this->db->where('class_id', $ex[0]);
        $this->db->where('section_id', $ex[1]);
        $this->db->where('subject_id', $ex[2]);
        $this->db->where('year', $this->runningYear);
        $this->db->where('activity_type', 'live');
        if($ltype == 'student' || $ltype == 'parent'){
            $this->db->where('status',1);    
        }
        $this->db->order_by('order_time', 'DESC');
        return $this->db->get('activity')->result_array();
    }
    
    function getSubjectChoices($data)
    {
        $ltype = $this->session->userdata('login_type');
        $in = base64_decode($data);
        $ex = explode('-',$in);
        $this->db->where('class_id', $ex[0]);
        $this->db->where('section_id', $ex[1]);
        $this->db->where('subject_id', $ex[2]);
        $this->db->where('year', $this->runningYear);
        $this->db->where('activity_type', 'choice');
        if($ltype == 'student' || $ltype == 'parent'){
            $this->db->where('status',1);    
        }
        $this->db->order_by('order_time', 'DESC');
        return $this->db->get('activity')->result_array();
    }
    
    function getYoutubeVideos($data)
    {
        $ltype = $this->session->userdata('login_type');
        $in = base64_decode($data);
        $ex = explode('-',$in);
        $this->db->where('class_id', $ex[0]);
        $this->db->where('section_id', $ex[1]);
        $this->db->where('subject_id', $ex[2]);
        $this->db->where('year', $this->runningYear);
        $this->db->where('activity_type', 'video');
        if($ltype == 'student' || $ltype == 'parent'){
            $this->db->where('status',1);    
        }
        $this->db->order_by('order_time', 'DESC');
        return $this->db->get('activity')->result_array();
    }
    
    function getStudyMaterial($data)
    {
        $ltype = $this->session->userdata('login_type');
        $in = base64_decode($data);
        $ex = explode('-',$in);
        $this->db->where('class_id', $ex[0]);
        $this->db->where('section_id', $ex[1]);
        $this->db->where('subject_id', $ex[2]);
        $this->db->where('year', $this->runningYear);
        $this->db->where('activity_type', 'material');
        if($ltype == 'student' || $ltype == 'parent'){
            $this->db->where('status',1);    
        }
        $this->db->order_by('order_time', 'DESC');
        return $this->db->get('activity')->result_array();
    }
    
    function getForums($data)
    {
        $ltype = $this->session->userdata('login_type');
        $in = base64_decode($data);
        $ex = explode('-',$in);
        $this->db->where('class_id', $ex[0]);
        $this->db->where('section_id', $ex[1]);
        $this->db->where('subject_id', $ex[2]);
        $this->db->where('year', $this->runningYear);
        $this->db->where('activity_type', 'forum');
        if($ltype == 'student' || $ltype == 'parent'){
            $this->db->where('status',1);    
        }
        $this->db->order_by('order_time', 'DESC');
        return $this->db->get('activity')->result_array();
    }
    
    public function createMaterial()
    {
        $fileName = 'file-'.uniqid().'-'.str_replace(" ", "",$_FILES["file_name"]["name"]);
        $data['date']          = $this->crud->getDateFormat().' '.date('h:i A');
        $data['class_id']      = $this->input->post('class_id');
        $data['section_id']    = $this->input->post('section_id');
        $data['subject_id']    = $this->input->post('subject_id');
        $data['description']   = $this->input->post('description');
        if($this->input->post('status') == 1){
            $data['status']    = $this->input->post('status');   
            $data['notified']  = 1; 
        }
        $data['activity_type']  = 'material';
        $data['uploader_role'] = $this->session->userdata('login_type');
        $data['uploader_id']   = $this->session->userdata('login_user_id');
        $data['year']          = $this->runningYear;
        $data['file']          = $fileName;
        $data['real_name']     = $_FILES["file_name"]["name"];
        $data['file_size']     = $this->crud->formatBytes($_FILES["file_name"]["size"]);
        $this->db->insert('activity', $data);
        move_uploaded_file($_FILES["file_name"]["tmp_name"], "public/uploads/document/" . $fileName);
        if($this->input->post('status') == 1)
        {
            $body = "<strong>".$this->crud->get_name($this->session->userdata('login_type'),$this->session->userdata('login_user_id'))."</strong>". " ". getEduAppGTLang('study_material_notify');
            $this->submitNotify($body);   
        }
    }
    
    function deleteStudyMaterial($activityID)
    {
        $fileName = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->file;
        unlink("public/uploads/document/" . $fileName);
        $this->db->where('activity_id', $activityID);
        $this->db->delete('activity');
    }
    
    function deleteForum($activityID)
    {
        $fileName = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->file;
        unlink("public/uploads/forum/" . $fileName);
        $this->db->where('activity_id', $activityID);
        $this->db->delete('activity');
        
    }
    
    public function updateMaterial($activityID)
    {
        $notified = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->notified;
        $uploaderT = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->uploader_role;
        $upladerI = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->uploader_id;
        if($this->input->post('status') == 1 && $notified == 0)
        {
            $body = "<strong>".$this->crud->get_name($uploaderT,$upladerI)."</strong>". " ". getEduAppGTLang('study_material_notify');
            $this->submitNotify($body);   
        }
        
        $fileName = 'file-'.uniqid().'-'.str_replace(" ", "",$_FILES["file_name"]["name"]);
        $data['description']   = $this->input->post('description');
        if($this->input->post('status') == 1){
            $data['status']    = $this->input->post('status');   
            $data['notified']  = 1; 
        }
        if($_FILES["file_name"]["size"] > 0){
            $data['file']          = $fileName;
            $data['real_name']     = $_FILES["file_name"]["name"];
            $data['file_size']     = $this->crud->formatBytes($_FILES["file_name"]["size"]);   
        }
        $this->db->where('activity_id', $activityID);
        $this->db->update('activity', $data);
        move_uploaded_file($_FILES["file_name"]["tmp_name"], "public/uploads/document/" . $fileName);
    }
    
    function createSubjectChoice()
    {
        $data['date']          = $this->crud->getDateFormat().' '.date('h:i A');
        $data['class_id']      = $this->input->post('class_id');
        $data['section_id']    = $this->input->post('section_id');
        $data['subject_id']    = $this->input->post('subject_id');
        if($this->input->post('status') == 1){
            $data['status']    = $this->input->post('status');   
            $data['notified']  = 1; 
        }
        $data['activity_type']  = 'choice';
        $data['uploader_role'] = $this->session->userdata('login_type');
        $data['uploader_id']   = $this->session->userdata('login_user_id');
        $data['year']          = $this->runningYear;
        $data['title'] = strip_tags($this->input->post('question'));
        foreach ($this->input->post('options') as $row)
        {
            $data['description'] .= $row . ',';
        }
        $this->db->insert('activity', $data);
        
        if($this->input->post('status') == 1)
        {
            $body = "<strong>".$this->crud->get_name($this->session->userdata('login_type'),$this->session->userdata('login_user_id'))."</strong>". " ". getEduAppGTLang('new_subject_choice');
            $this->submitNotify($body);   
        }
    }
    
    function updateSubjectChoice($choiceID)
    {
        $notified = $this->db->get_where('activity', array('activity_id' => $choiceID))->row()->notified;
        $uploaderT = $this->db->get_where('activity', array('activity_id' => $choiceID))->row()->uploader_role;
        $upladerI = $this->db->get_where('activity', array('activity_id' => $choiceID))->row()->uploader_id;
        if($this->input->post('status') == 1 && $notified == 0)
        {
            $body = "<strong>".$this->crud->get_name($uploaderT,$upladerI)."</strong>". " ". getEduAppGTLang('new_subject_choice');
            $this->submitNotify($body);   
        }
        if($this->input->post('status') == 1){
            $data['status']    = $this->input->post('status');   
            $data['notified']  = 1; 
        }
        $data['title'] = strip_tags($this->input->post('question'));
        $options = '';
        foreach ($this->input->post('options') as $row)
        {
            if($row != ''){
                $options .= $row . ',';
            }   
        }
        $data['description'] = $options;
        $this->db->where('activity_id', $choiceID);
        $this->db->update('activity', $data);
    }
    
    function deleteAnnouncement($id)
    {
        $this->db->where('activity_id', $id);
        $this->db->delete('activity');
    }
    
    function deleteSubjectChoice($id)
    {
        $this->db->where('activity_id', $id);
        $this->db->delete('activity');
    }
    
    function createChoice()
    {
        $data['question'] = strip_tags($this->input->post('question'));
        foreach ($this->input->post('options') as $row)
        {
            $data['options'] .= $row . ',';
        }
        $data['user']          = $this->input->post('user');
        $data['status']        = 1;
        $data['date']          = $this->crud->getDateFormat();
        $data['date2']         = date('h:i A');
        $data['admin_id']      = $this->session->userdata('login_user_id');
        $data['type']          = "polls";
        $data['publish_date']  = date('Y-m-d H:i:s');
        $data['poll_code']     = substr(md5(rand(0, 1000000)), 0, 7);
        $this->crud->send_polls_notify();
        $this->db->insert('polls', $data);
    }
    
    function getAnnouncements($data)
    {
        $ltype = $this->session->userdata('login_type');
        $in = base64_decode($data);
        $ex = explode('-',$in);
        $this->db->order_by('order_time', 'DESC');
        $this->db->where('class_id',$ex[0]);
        $this->db->where('section_id',$ex[1]);
        $this->db->where('subject_id',$ex[2]);
        $this->db->where('year',$this->runningYear);
        if($ltype == 'student' || $ltype == 'parent'){
            $this->db->where('status',1);    
        }
        $this->db->where('activity_type','announcement');
        return $this->db->get('activity')->result_array();
    }
    
    function submitNotify($body)
    {
        $notify['notify'] = $body;
        $classID   = $this->input->post('class_id');
        $sectionID = $this->input->post('section_id');
        $subjectID = $this->input->post('subject_id');
        
        $students = $this->db->get_where('enroll', array('class_id' => $classID, 'section_id' => $sectionID, 'year' => $this->runningYear))->result_array();
        $n = 0;
        foreach($students as $row)
        {
            $n++;
            if($n == '1'){
                $notify['first']     = 1;                
            }
            else{
                $notify['first']     = 0;                
            }
            $notify['user_id']       = $row['student_id'];
            $notify['user_type']     = 'student';
            $notify['url']           = "student/subject_dashboard/".base64_encode($classID.'-'.$sectionID.'-'.$subjectID);
            $notify['date']          = $this->crud->getDateFormat();
            $notify['time']          = date('h:i A');
            $notify['status']        = 0;
            $notify['type']          = 'homework';
            $notify['class_id']      = $classID;
            $notify['section_id']    = $sectionID;
            $notify['year']          = $this->runningYear;
            $notify['subject_id']    = $subjectID;
            $notify['original_id']   = $this->session->userdata('login_user_id');
            $notify['original_type'] = $this->session->userdata('login_type');
            $this->db->insert('notification', $notify);
            
        }
    }
    
    function countOnlineExams($class_id,$section_id,$subject_id){
        $running_year = $this->db->get_where('settings' , array('type' => 'running_year'))->row()->description;
        $match = array('running_year' => $running_year, 'class_id' => $class_id, 'section_id' => $section_id,'subject_id' => $subject_id, 'status' => 'published');
        $exams = $this->db->where($match)->get('online_exam')->num_rows();
        return $exams;
    }
    
    function updateAnnouncement($activityID)
    {
        $notified = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->notified;
        $uploaderT = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->uploader_role;
        $upladerI = $this->db->get_where('activity', array('activity_id' => $activityID))->row()->uploader_id;
        if($this->input->post('status') == 1 && $notified == 0)
        {
            $body = "<strong>".$this->crud->get_name($uploaderT,$upladerI)."</strong>". " ". getEduAppGTLang('new_announcement');
            $this->submitNotify($body);   
        }
        $data['description']   = $this->input->post('description');
        if($this->input->post('status') == 1)
        {
            $data['status']        = $this->input->post('status');   
            $data['notified']  = 1; 
        }else{
            $data['status']        = 0;   
        }
        $this->db->where('activity_id', $activityID);
        $this->db->update('activity', $data);
    }
    
    function createAnnouncement()
    {   
        if($this->input->post('status') == 1){
            $data['status']     = $this->input->post('status');   
            $data['notified']   = 1; 
        }
        $data['year']           = $this->runningYear;
        $data['date']           = $this->crud->getDateFormat().' '.date('h:i A');
        $data['uploader_role']  = $this->session->userdata('login_type');
        $data['uploader_id']    = $this->session->userdata('login_user_id');
        $data['activity_type']  = 'announcement';
        $data['description']    = $this->input->post('description');
        $data['class_id']       = $this->input->post('class_id');
        $data['section_id']     = $this->input->post('section_id');
        $data['subject_id']     = $this->input->post('subject_id');
        $this->db->insert('activity', $data);
        
         if($this->input->post('status') == 1)
        {
            $body = "<strong>".$this->crud->get_name($this->session->userdata('login_type'),$this->session->userdata('login_user_id'))."</strong>". " ". getEduAppGTLang('new_announcement');
            $this->submitNotify($body);   
        }
    }
    
    //SetRead
    public function setRead($code,$type,$subject_id)
    {
        $year = $this->db->get_where('settings' , array('type' => 'running_year'))->row()->description;
        $userId    = $this->session->userdata('login_user_id');
        $check = $this->db->get_where('activity_read', array('student_id' => $userId, 'subject_activity_id' => $code,'activity_type' => $type, 'subject_id' => $subject_id, 'year' => $year));
        if($check->num_rows() == 0){
            $data['student_id']          = $userId;
            $data['subject_id']          = $subject_id;
            $data['subject_activity_id'] = $code;
            $data['date']                = $this->crud->getDateFormat().' '.date('h:i A');
            $data['year']                = $year;
            $data['activity_type']       = $type;
            $this->db->insert('activity_read',$data);
        }
    }
    
    //GetRead
    public function getRead($code,$type,$subject_id){
        $year = $this->db->get_where('settings' , array('type' => 'running_year'))->row()->description;
        $this->db->limit(5);
        $this->db->order_by('actividy_read_id', 'RANDOM');
        $check = $this->db->get_where('activity_read', array('subject_activity_id' => $code, 'activity_type' => $type, 'subject_id' => $subject_id, 'year' => $year))->result_array();
        return $check;
    }
    
    public function updateLiveClass($liveId)
    {
        $data['title']             = html_escape($this->input->post('title'));
        $data['description']       = html_escape($this->input->post('description'));
        if($this->input->post('livetype') == '2'){
            $data['siteUrl']       = $this->input->post('siteUrl');   
        }
        $data['date']              = html_escape($this->input->post('start_date'));
        $data['time']              = html_escape($this->input->post('start_time'));
        $data['wall_type']         = 'live';
        $this->db->where('live_id', $liveId);
        $this->db->update('live',$data);  
    }
    
    public function deleteLiveClass($liveId)
    {
        $this->db->where('live_id', $liveId);
        $this->db->delete('live');
    }
    
    public function createLevel()
    {
        $data['name']        = html_escape($this->input->post('name'));
        $data['grade_point'] = html_escape($this->input->post('point'));
        $data['mark_from']   = html_escape($this->input->post('from'));
        $data['mark_upto']   = html_escape($this->input->post('to'));
        $this->db->insert('grade', $data);
    }
    
    public function updateLevel($levelId)
    {
        $data['name']        = html_escape($this->input->post('name'));
        $data['grade_point'] = html_escape($this->input->post('point'));
        $data['mark_from']   = html_escape($this->input->post('from'));
        $data['mark_upto']   = html_escape($this->input->post('to'));
        $this->db->where('grade_id', $levelId);
        $this->db->update('grade', $data);
    }
    
    public function deleteLevel($levelId)
    {
        $this->db->where('grade_id', $levelId);
        $this->db->delete('grade');
    }
    
    public function deleteDelivery($Id)
    {
        $this->db->where('id',$Id);
        $this->db->delete('submission');
    }
    
    public function acceptBook($bookId)
    {
        $data['status'] = 1;
        $this->db->update('book_request', $data, array('book_request_id' => $bookId));
        $book_id        = $this->db->get_where('book_request', array('book_request_id' => $bookId))->row()->book_id;
        $issued_copies  = $this->db->get_where('book', array('book_id' => $book_id))->row()->issued_copies;
        $data2['issued_copies'] = $issued_copies + 1;
        $this->db->update('book', $data2, array('book_id' => $book_id));
    }
    
    public function rejectBook($bookId)
    {
        $data['status'] = 2;
        $this->db->update('book_request', $data, array('book_request_id' => $bookId));
    }
    
    public function deleteOnlineExam($examId)
    {
        $this->db->where('activity_id', $examId);
        $this->db->delete('activity');
        
        $this->db->where('online_exam_id', $examId);
        $this->db->delete('question_bank');
        
        $this->db->where('online_exam_id', $examId);
        $this->db->delete('online_exam_result');
    }
    
    public function reviewHomework()
    {
        $id      = $this->input->post('answer_id');
        $mark    = html_escape($this->input->post('mark'));
        $comment = html_escape($this->input->post('comment'));
        $entries = sizeof($mark);
        for($i = 0; $i < $entries; $i++) 
        {
            $data['mark']            = $mark[$i];
            $data['teacher_comment'] = $comment[$i];
            $this->db->where_in('id', $id[$i]);
            $this->db->update('submission', $data);
        }
    }
    
    public function singleHomework()
    {
        $student_id  = $this->db->get_where('submission', array('id' => $this->input->post('id')))->row()->student_id;
        $code        = $this->db->get_where('submission', array('id' => $this->input->post('id')))->row()->homework_code;
        $class_id        = $this->db->get_where('activity', array('activity_id' => $code))->row()->class_id;
        $section_id        = $this->db->get_where('activity', array('activity_id' => $code))->row()->section_id;
        $subject_id        = $this->db->get_where('activity', array('activity_id' => $code))->row()->subject_id;
        $title       = $this->db->get_where('activity', array('activity_id' => $code))->row()->title;

        $data['teacher_comment'] = html_escape($this->input->post('comment'));
        $data['mark']            = html_escape($this->input->post('mark'));
        $this->db->where('id', $this->input->post('id'));
        $this->db->update('submission', $data);

        $notify['notify']        = "<strong>". $this->crud->get_name($this->session->userdata('login_type'), $this->session->userdata('login_user_id'))."</strong>". " ". getEduAppGTLang('homework_rated') ." <b>".$title.".</b>";
        $notify['user_id']       = $student_id;
        $notify['user_type']     = 'student';
        $notify['first']         = 1;
        $notify['date']          = $this->crud->getDateFormat();
        $notify['time']          = date('h:i A');
        $notify['url']           = "student/subject_dashboard/".base64_encode($class_id.'-'.$section_id.'-'.$subject_id);
        $notify['status']        = 0;
        $notify['original_id']   = $this->session->userdata('login_user_id');
        $notify['original_type'] = $this->session->userdata('login_type');
        $this->db->insert('notification', $notify);
    }
    
    public function update_online_exam()
    {
        $ts  = explode(':',$this->input->post('time_start'));
        $nts = count($ts);
        $te  = explode(':',$this->input->post('time_end'));
        $nte = count($te);
        $data['title']              = html_escape($this->input->post('exam_title'));
        $data['class_id']           = $this->input->post('class_id');
        $data['section_id']         = $this->input->post('section_id');
        $data['results']            = $this->input->post('results');
        $data['show_random']        = $this->input->post('show_random');
        $data['subject_id']         = $this->input->post('subject_id');
        $data['minimum_percentage'] = html_escape($this->input->post('minimum_percentage'));
        $data['instruction']        = html_escape($this->input->post('instruction'));
        $data['password']           = html_escape($this->input->post('password'));
        $data['exam_date']          = strtotime(html_escape($this->input->post('exam_date')));
        if($nts == 3){
            $data['time_start']         = $this->input->post('time_start');   
        }else{
            $data['time_start']         = $this->input->post('time_start').':00';
        }
        if($nte == 3){
            $data['time_end']         = $this->input->post('time_end');   
        }else{
            $data['time_end']         = $this->input->post('time_end').':00';
        }
        $data['duration']           = strtotime(date('Y-m-d', $data['exam_date']).' '.$data['time_end']) - strtotime(date('Y-m-d', $data['exam_date']).' '.$data['time_start']);

        $this->db->where('online_exam_id', $this->input->post('online_exam_id'));
        $this->db->update('online_exam', $data);
    }
    
    public function promoteStudents()
    {
        $running_year                =   $this->input->post('running_year');  
        $from_class_id               =   $this->input->post('promotion_from_class_id'); 
        $from_section_id             =   $this->input->post('promotion_from_section_id'); 
        $students_of_promotion_class =   $this->db->get_where('enroll' , array('class_id' => $from_class_id, 'section_id' => $from_section_id , 'year' => $running_year))->result_array();
        foreach($students_of_promotion_class as $row) 
        {
            $enroll_data['enroll_code']     =   substr(md5(rand(0, 1000000)), 0, 7);
            $enroll_data['student_id']      =   $row['student_id'];
            $enroll_data['section_id']      =   $this->input->post('promotion_status_section_'.$row['student_id']);
            $enroll_data['class_id']        =   $this->input->post('promotion_status_'.$row['student_id']);
            $enroll_data['year']            =   $this->input->post('promotion_year');
            $enroll_data['date_added']      =   strtotime(date("Y-m-d H:i:s"));
            $this->db->insert('enroll' , $enroll_data);
        } 
    }
    
    public function createCourse()
    {
        $md5 = md5(date('d-m-y H:i:s'));
        $data['name']        = html_escape($this->input->post('name'));
        $data['about']       = html_escape($this->input->post('about'));
        $data['class_id']    = $this->input->post('class_id');
        $data['section_id']  = $this->input->post('section_id');
        $data['icon']        = $md5.str_replace(' ', '', $_FILES['userfile']['name']);
        $data['teacher_id']  = $this->input->post('teacher_id');
        $data['year']        = $this->runningYear;
        $this->db->insert('subject', $data);
        move_uploaded_file($_FILES['userfile']['tmp_name'], 'public/uploads/subject_icon/' . $md5.str_replace(' ', '', $_FILES['userfile']['name']));
    }
    
    public function updateCourse($courseId)
    {
        $class_id           = $this->db->get_where('subject', array('subject_id' => $courseId))->row()->class_id;
        $md5                =  md5(date('d-m-y H:i:s'));
        if($_FILES['userfile']['size'] > 0){
            $data['icon']   = $md5.str_replace(' ', '', $_FILES['userfile']['name']);
        }
        $data['name']       = html_escape($this->input->post('name'));
        $data['about']      = html_escape($this->input->post('about'));
        $data['teacher_id'] = $this->input->post('teacher_id');
        $this->db->where('subject_id', $courseId);
        $this->db->update('subject', $data);
        move_uploaded_file($_FILES['userfile']['tmp_name'], 'public/uploads/subject_icon/' . $md5.str_replace(' ', '', $_FILES['userfile']['name']));
    }
    
    public function deleteCourse($courseId)
    {
        $this->db->where('subject_id', $courseId);
        $this->db->delete('subject');
    }
    
    public function createClass()
    {
        $data['name']         = html_escape($this->input->post('name'));
        $data['teacher_id']   = $this->input->post('teacher_id');
        $this->db->insert('class', $data);
        $class_id = $this->db->insert_id();
        $data2['class_id']    =   $class_id;
        $data2['name']        =   'A';
        $this->db->insert('section' , $data2);
    }
    
    public function updateClass($classId)
    {
        $data['name']         = html_escape($this->input->post('name'));
        $data['teacher_id']   = $this->input->post('teacher_id');
        $this->db->where('class_id', $classId);
        $this->db->update('class', $data);
    }
    
    public function deleteClass($classId)
    {
        $this->db->where('class_id', $classId);
        $this->db->delete('class');
    }
    
    public function createSection()
    {
        $data['name']       =   html_escape($this->input->post('name'));
        $data['class_id']   =   $this->input->post('class_id');
        $data['teacher_id'] =   $this->input->post('teacher_id');
        $this->db->insert('section' , $data);
    }
    
    public function updateSection($sectionId){
        $data['name']       = html_escape($this->input->post('name'));
        $data['teacher_id'] = $this->input->post('teacher_id');
        $this->db->where('section_id', $sectionId);
        $this->db->update('section', $data);
    }
    
    public function deleteSection($sectionId)
    {
        $this->db->where('section_id' , $sectionId);
        $this->db->delete('section');
    }
    
    public function createSemester()
    {
        $data['name']    = html_escape($this->input->post('name'));
        $this->db->insert('exam', $data);
    }
    
    public function updateSemester($examId)
    {
        $data['name']    = html_escape($this->input->post('name'));
        $this->db->where('exam_id', $examId);
        $this->db->update('exam', $data);
    }
    
    public function deleteSemester($examId)
    {
        $this->db->where('exam_id', $examId);
        $this->db->delete('exam');
    }
    
    public function createReport()
    {
        $parent_phone = '';
        $parent_email = '';
        $parent_id           = $this->db->get_where('student', array('student_id' => $this->input->post('student_id')))->row()->parent_id;
        $student_name        = $this->crud->get_name('student', $this->input->post('student_id'));
        if($parent_id > 0){
            $parent_phone        = $this->db->get_where('parent', array('parent_id' => $parent_id))->row()->phone;
            $parent_email        = $this->db->get_where('parent', array('parent_id' => $parent_id))->row()->email;
        }   
        $data['student_id']  = $this->input->post('student_id');
        $data['class_id']    = $this->input->post('class_id');
        $data['section_id']  = $this->input->post('section_id');
        $data['user_id']     = $this->session->userdata('login_type')."-".$this->session->userdata('login_user_id');
        $data['title']       = html_escape($this->input->post('title'));
        $data['description'] = html_escape($this->input->post('description'));
        if($_FILES["file_name"]["size"] > 0){
            $data['file']        = $_FILES["file_name"]["name"];   
        }
        $data['date']        = $this->crud->getDateFormat();
        $data['priority']    = $this->input->post('priority');
        $data['status']      = 0;
        $data['code']        = substr(md5(rand(0, 1000000)), 0, 7);
        $this->db->insert('student_report', $data);
        if($parent_id > 0){
            $this->crud->students_reports($this->input->post('student_id'),$parent_id);   
        }
        move_uploaded_file($_FILES["file_name"]["tmp_name"], 'public/uploads/report_files/'. $_FILES["file_name"]["name"]);
        
        $notify = $this->db->get_where('settings' , array('type' => 'students_reports'))->row()->description;
        if($notify == 1)
        {
            $message = getEduAppGTLang('behavioral_report_has_been_created_for')." " . $student_name;
            $sms_status = $this->db->get_where('settings' , array('type' => 'sms_status'))->row()->description;
            if ($sms_status == 'msg91') 
            {
                if($parent_phone != ''){
                    $result = $this->crud->send_sms_via_msg91($message, $parent_phone);   
                }
            }
            else if ($sms_status == 'twilio') 
            {
                if($parent_phone != ''){
                    $this->crud->twilio_api($message,"".$parent_phone."");
                }
            }
            else if ($sms_status == 'clickatell') 
            {
                if($parent_phone != ''){
                    $this->crud->clickatell($message,$parent_phone);
                }
            }
        }
    }
    
    public function reportResponse()
    {
        $data['report_code'] = $this->input->post('report_code');
        $data['message']     = html_escape($this->input->post('message'));
        $data['date']        = $this->crud->getDateFormat();
        $data['sender_type'] = $this->session->userdata('login_type');
        $data['sender_id']   = $this->session->userdata('login_user_id');
        return $this->db->insert('report_response', $data);
    }
    
    public function updateReport($code)
    {
        $notify['notify'] =  "<b>".$this->db->get_where('student_report', array('code' => $code))->row()->title."</b>"." ". getEduAppGTLang('report_solved');
        $user       = $this->db->get_where('student_report', array('code' => $code))->row()->user_id;
        $final      = explode("-", $user);
        $user_type  = $final[0];
        $user_id    = $final[1];
        $student_id = $this->db->get_where('student_report', array('code' => $code))->row()->student_id;
        $parent_id  = $this->db->get_where('student', array('student_id' => $student_id))->row()->parent_id;

        $notify['user_id']       = $user_id;
        $notify['user_type']     = $user_type;
        $notify['url']           = $user_type."/view_report/".$code;
        $notify['date']          = $this->crud->getDateFormat();
        $notify['time']          = date('h:i A');
        $notify['status']        = 0;
        $notify['first']         = 1;
        $notify['original_id']   = $this->session->userdata('login_user_id');
        $notify['original_type'] = $this->session->userdata('login_type');
        $this->db->insert('notification', $notify);

        $notify2['notify']        = $notify['notify'];
        $notify2['user_id']       = $parent_id;
        $notify2['user_type']     = 'parent';
        $notify2['url']           = "parents/view_report/".$code;
        $notify2['date']          = $this->crud->getDateFormat();
        $notify2['time']          = date('h:i A');
        $notify2['status']        = 0;
        $notify2['original_id']   = $this->session->userdata('login_user_id');
        $notify2['original_type'] = $this->session->userdata('login_type');
        $this->db->insert('notification', $notify2);

        $data['status']           = 1;
        $this->db->where('code', $code);
        $this->db->update('student_report', $data);
    }
    
    function getInfo($type) {
        $query = $this->db->get_where('academic_settings', array('type' => $type));
        return $query->row()->description;
    }
    
    public function createRoutine()
    {
        $data['class_id']       = $this->input->post('class_id');
        if($this->input->post('section_id') != '') 
        {
            $data['section_id'] = $this->input->post('section_id');
        }
        $subject_id = $this->input->post('subject_id');
        $teacher_id = $this->db->get_where('subject', array('subject_id' => $subject_id))->row()->teacher_id;
        $data['subject_id']     = $this->input->post('subject_id');
        $data['time_start']     = html_escape($this->input->post('time_start'));
        $data['time_end']       = html_escape($this->input->post('time_end'));
        $data['classroom_id']   = $this->input->post('classroom_id');
        $data['time_start_min'] = html_escape($this->input->post('time_start_min'));
        $data['time_end_min']   = html_escape($this->input->post('time_end_min'));
        $data['day']            = $this->input->post('day');
        $data['amend']          = $this->input->post('ending_ampm');
        $data['amstart']        = $this->input->post('starting_ampm');
        $data['day']            = $this->input->post('day');
        $data['teacher_id']     = $teacher_id;
        $data['year']           = $this->db->get_where('settings' , array('type' => 'running_year'))->row()->description;
        $this->db->insert('class_routine', $data);
    }
    
    public function updateRoutine($routineId)
    {
        $data['time_start']     = html_escape($this->input->post('time_start'));
        $data['time_end']       = html_escape($this->input->post('time_end'));
        $data['time_start_min'] = html_escape($this->input->post('time_start_min'));
        $data['time_end_min']   = html_escape($this->input->post('time_end_min'));
        $data['amend']          = html_escape($this->input->post('ending_ampm'));
        $data['amstart']        = html_escape($this->input->post('starting_ampm'));
        $data['classroom_id']   = $this->input->post('classroom_id');
        $data['day']            = $this->input->post('day');
        $data['year']           = $this->db->get_where('settings' , array('type' => 'running_year'))->row()->description;
        $this->db->where('class_routine_id', $routineId);
        $this->db->update('class_routine', $data);
    }
    
    public function deleteRoutine($routineId)
    {
        $this->db->where('class_routine_id', $routineId);
        $this->db->delete('class_routine');
    }
    
    public function uploadMarks($datainfo,$examId)
    {
        $info = base64_decode($datainfo);
        $ex = explode('-', $info);
        $data['exam_id']    = $examId;
        $data['class_id']   = $ex[0];
        $data['section_id'] = $ex[1];
        $data['subject_id'] = $ex[2];
        $data['year']       = $this->runningYear;
        $students = $this->db->get_where('enroll' , array('class_id' => $data['class_id'] , 'section_id' => $data['section_id'] , 'year' => $data['year']))->result_array();
        foreach($students as $row) 
        {
            $verify_data = array('exam_id' => $data['exam_id'],'class_id' => $data['class_id'],'section_id' => $data['section_id'],
            'student_id' => $row['student_id'],'subject_id' => $data['subject_id'], 'year' => $data['year']);
            $query = $this->db->get_where('mark' , $verify_data);
            if($query->num_rows() < 1) 
            {   
                $data['student_id'] = $row['student_id'];
                $this->db->insert('mark' , $data);
            }
        }
    }
    
    public function submitExam($online_exam_id)
    {
        $answer_script = array();
        $question_bank = $this->db->get_where('question_bank', array('online_exam_id' => $online_exam_id))->result_array();
        foreach ($question_bank as $question) 
        {
          $correct_answers  = $this->crud->get_correct_answer($question['question_bank_id']);
          $container_2 = array();
          if (isset($_POST[$question['question_bank_id']])) 
          {
              foreach ($this->input->post($question['question_bank_id']) as $row) 
              {
                  $submitted_answer = "";
                  if ($question['type'] == 'true_false') {
                      $submitted_answer = $row;
                  }
                  elseif($question['type'] == 'fill_in_the_blanks'){
                    $suitable_words = array();
                    $suitable_words_array = explode(',', $row);
                    foreach ($suitable_words_array as $key) {
                      array_push($suitable_words, strtolower($key));
                    }
                    $submitted_answer = json_encode(array_map('trim',$suitable_words));
                  }
                  else{
                      array_push($container_2, strtolower($row));
                      $submitted_answer = json_encode($container_2);
                  }
                  $container = array(
                      "question_bank_id" => $question['question_bank_id'],
                      "submitted_answer" => $submitted_answer,
                      "correct_answers"  => $correct_answers
                  );
              }
          }
          else {
              $container = array(
                  "question_bank_id" => $question['question_bank_id'],
                  "submitted_answer" => "",
                  "correct_answers"  => $correct_answers
              );
          }
          array_push($answer_script, $container);
        }
        $this->crud->submit_online_exam($online_exam_id, json_encode($answer_script));
    }
    
    function requestStudentBook()
    {
        $data['book_id']            = $this->input->post('book_id');
        $data['student_id']         = $this->session->userdata('login_user_id');
        $data['issue_start_date']   = html_escape(strtotime($this->input->post('start')));
        $data['issue_end_date']     = html_escape(strtotime($this->input->post('end')));
        $this->db->insert('book_request', $data);
    }
    
    function sendFileHomework($homeworkCode)
    {
        ini_set( 'memory_limit', '200M' );
        ini_set('upload_max_filesize', '200M');  
        ini_set('post_max_size', '200M');  
        ini_set('max_input_time', 3600);  
        ini_set('max_execution_time', 3600);
        
        $data['homework_code']   = $homeworkCode;
        $name = substr(md5(rand(0, 1000000)), 0, 7).$_FILES["file_name"]["name"];
        $data['student_id']      = $this->session->userdata('login_user_id');
        $data['date']            = $this->crud->getDateFormat().' '.date('H:i');
        $data['class_id']        = $this->input->post('class_id');
        $data['section_id']      = $this->input->post('section_id');
        $data['file_name']       =  $name;
        $data['student_comment'] = html_escape($this->input->post('comment'));
        $data['subject_id']      = $this->input->post('subject_id');
        $data['status'] = 1;
        $this->db->insert('submission', $data);
        $delivery = $this->db->insert_id();
        include 'public/class.fileuploader.php';
        $FileUploader = new FileUploader('files', array(
            'uploadDir' => './public/uploads/homework_delivery/',
            'replace' => true,
        ));
        $datax = $FileUploader->upload();
        for($i = 0; $i < count($datax['files']); $i++)
        {
            $insert_data['file']          = $datax['files'][$i]['name'];
            $insert_data['homework_code'] = $homeworkCode;
            $insert_data['student_id']    = $this->session->userdata('login_user_id');
            $insert_data['delivery_id']   = $delivery;
            $this->db->insert('homework_files', $insert_data);   
        }
    }
    
    public function sendTextHomework($homeworkCode)
    {
        $data['homework_code']    = $homeworkCode;
        $data['student_id']       = $this->session->userdata('login_user_id');
        $data['date']             = $this->crud->getDateFormat().' '.date('H:i');
        $data['class_id']         = $this->input->post('class_id');
        $data['section_id']       = $this->input->post('section_id');
        $data['homework_reply']   = html_escape($this->input->post('reply'));
        $data['student_comment']  = html_escape($this->input->post('comment'));
        $data['subject_id']       = $this->input->post('subject_id');
        $data['status']           = 1;
        $this->db->insert('submission', $data);
    }
    
    public function updateTextHomework($id)
    {
        $data['date']             = $this->crud->getDateFormat().' '.date('H:i');
        $data['homework_reply']   = html_escape($this->input->post('reply'));
        $data['student_comment']  = html_escape($this->input->post('comment'));
        $this->db->where('id', $id);
        $this->db->update('submission', $data);
    }
    
    public function deleteFileHomework($fhomework_file_id)
    {
        $file_n = $this->db->get_where('homework_files', array('fhomework_file_id' => $fhomework_file_id))->row()->file;
        unlink("public/uploads/homework_delivery/" . $file_n);
        $this->db->where('fhomework_file_id',$fhomework_file_id);
        $this->db->delete('homework_files');
    }
    
    function updateFileHomework($id,$homeworkCode)
    {
        ini_set( 'memory_limit', '200M' );
        ini_set('upload_max_filesize', '200M');  
        ini_set('post_max_size', '200M');  
        ini_set('max_input_time', 3600);  
        ini_set('max_execution_time', 3600);
        
        $name = substr(md5(rand(0, 1000000)), 0, 7).$_FILES["file_name"]["name"];
        $data['date']            = $this->crud->getDateFormat().' '.date('H:i');
        $data['file_name']       =  $name;
        $data['student_comment'] = html_escape($this->input->post('comment'));
        $this->db->where('id', $id);
        $this->db->update('submission', $data);
        
        include 'public/class.fileuploader.php';
        $FileUploader = new FileUploader('files', array(
            'uploadDir' => './public/uploads/homework_delivery/',
            'replace' => true,
        ));
        $datax = $FileUploader->upload();
        for($i = 0; $i < count($datax['files']); $i++)
        {
            $insert_data['file']          = $datax['files'][$i]['name'];
            $insert_data['homework_code'] = $homeworkCode;
            $insert_data['student_id']    = $this->session->userdata('login_user_id');
            $insert_data['delivery_id']   = $id;
            $this->db->insert('homework_files', $insert_data);   
        }
    }
    
    public function getAllAcitivityProgress($classid, $sectionid, $subjectid)
    {
        return $this->db->query("SELECT activity_id, title, activity_type FROM activity WHERE class_id = $classid AND section_id = $sectionid AND subject_id = $subjectid AND year = '".$this->runningYear."' AND status = 1 AND activity_type NOT IN ('announcement','choice','material','video') ORDER BY order_time ASC;")->result_array();
        
    }
    
    public function checkActivityStatus($idactivity, $studentid, $activity_type)
    {
        if($activity_type == 'homework' ){
            $quers = "SELECT id FROM submission WHERE homework_code = $idactivity AND student_id = $studentid";
        }
        
        if($activity_type == 'live'){
            $quers = "SELECT id FROM live_status WHERE live_id = $idactivity AND student_id = $studentid";
        }
        
        if($activity_type == 'forum'){
            $quers = "SELECT message_id FROM forum_message WHERE activity_id = $idactivity AND user_id = $studentid AND user_type = 'student'";
        }
        
        if($activity_type == 'exam'){
            $quers = "SELECT online_exam_result_id FROM online_exam_result WHERE online_exam_id = $idactivity AND student_id = $studentid";
        }
        
        if($quers != '')
        {
            $ccts = $this->db->query($quers)->num_rows();
        }
        else{
            $ccts = 0;
        }
        
        if($ccts > 0)
        {
            return 1;
        }
        
        else
        {
            return 0;
        }
    }
    
}