<?php

namespace App\Controllers;

/**
 * This class controls viewing teachers on the system.
 *
 * @author Al Zziwa <azziwa@gmail.com>
 * @version 1.1.0
 * @copyright TMIS
 * @created 01/30/2015
 */
use App\Models\_teacher;
use App\Models\_document;
use App\Models\_person;

class Teacher extends BaseController
{
    #Constructor to set some default values at class load
    public function __construct()
    {
        // parent::__construct();
        $this->teacher = new _teacher();
        $this->document = new _document();
        $this->person = new _person();
    }
    
    
    
    
    # Add a new teacher
    public function add()
    {
        $data = filter_forwarded_data($this);
        # Only proceed if just viewing or has access rights
        if (!(((!empty($data['action']) && $data['action'] == 'view')) || check_access($this, 'add_new_teacher', 'boolean'))) {
            check_access($this, 'add_new_teacher');
        }
        
        # Remove any session variables if still in the session.
        if (empty($_POST) && empty($data['edit']) && !(!empty($data['urlaction']) && $data['urlaction'] == 'submit')) {
            $this->teacher->clear_session();
        }
        
        # If user has posted the form for processing
        if (!empty($_POST)) {
            # 1. Save or add the data to session?
            
            # a) Just add to session
            if ($this->request->getPost('preview') || isset($_POST['preview'])) {
                $response = $this->teacher->add_to_session($this->request->getPost());
                if ($response['boolean']) {
                    $data['preview'] = "Y";
                } else {
                    $data['msg'] = $response['msg'];
                }
            }
            # b) Save the data to the database
            else {
                if ($this->request->getPost('userid')) {
                    $result = $this->teacher->updated($this->request->getPost());
                    if ($result['boolean']) {
                        $this->person->add_education_and_qualifications($result['person_id'], $this->request->getPost());
                        $data['forward'] = base_url().'/Teacher/lists'.(!empty($action)? '/action/'.$action: '/action/view');
                        $data['result'] = $result;
                    }
                } else {
                    $result = $this->teacher->add_new($this->request->getPost());
                    if ($result['boolean']) {
                        $this->person->add_education_and_qualifications($result['person_id'], $this->request->getPost());
                        $this->person->submit_application($result['person_id'], array('user_id'=>$result['id'], 'emailaddress'=>$this->session->get('emailaddress'), 'first_name'=>$this->session->get('firstname') ));
                    }
                }
            }
            
            # 2. Show the appropriate message
            if (!empty($result)) {
                $this->session->set('msg', (!empty($result['msg'])? $result['msg']: "The teacher data has been submitted for approval."));
            }
            
            # 3. Redirect if saved successfully
            if (!empty($result['boolean']) && $result['boolean'] && empty($data['id'])) {
                $this->teacher->clear_session();
                return redirect()->to('teacher/lists'.(!empty($action)? '/action/'.$action: '/action/view'));
            }
        }
        
        #If editing - and for the first time, load the teacher details into the session
        if (!empty($data['id']) && empty($data['edit']) && empty($_POST)) {
            $this->teacher->populate_session($data['id']);
        }
        if (!empty($data['action']) && $data['action'] == 'view') {
            $data['preview'] = "Y";
        }
        
        # Viewing the teacher's profile, collect any documents they have been issued
        if (!empty($data['id']) && !empty($data['action']) && $data['action'] == 'view') {
            $data['documents'] = $this->teacher->get_documents($data['id']);
            #Change teacher WIP ID while being viewed by a HR or Tiet during verification.
            $permissions = array('verify_teacher_application_at_hr_level','verify_pre_primary_teacher_application_at_hr_level','verify_pre_primary_teacher_application_at_instructor_level','verify_teacher_application_at_instructor_level');
            // $current_actions = array('certify','certify_pre_primary');
            if(in_array($_SESSION['__selected_permission'], $permissions)) $this->query_reader->run('update_work_in_progress', array('user_id'=>$data['id'], 'wip_id'=>$this->session->get('__user_id')));
        }
        
        # This helps differentiate source of command for shared functions with the teacher's registration functionality
        $this->session->set('is_admin_adding_teacher', 'Y');
        $this->user->populate_session($this->session->get('__user_id'), true);
        $data['profileuserrole'] = $_SESSION['profile_userrole'];
        echo view('teacher/new_teacher', $data);
    }
    
    
    
    
    # Add the teacher education info to the session
    public function add_education()
    {
        $data = filter_forwarded_data($this);
        $data['response'] = $this->person->add_education('', $this->request->getPost());
        $data['area'] = "education_list";
        echo view('addons/basic_addons', $data);
    }
    
    
    
    
    # Add the teacher subject info to the session
    public function add_subject()
    {
        $data = filter_forwarded_data($this);
        $data['response'] = $this->person->add_subject_taught('', $this->request->getPost());
        $data['area'] = "subject_list";
        echo view('addons/basic_addons', $data);
    }
    
    
    
    
    # Add the teacher document to the session (and database)
    public function add_document()
    {
        $data = filter_forwarded_data($this);
        
        # Process the document addition if one has been successfully uploaded
        if (!empty($_FILES['documenturl__fileurl']) && file_exists($_FILES['documenturl__fileurl']['tmp_name'])) {
            $upload = $this->document->upload($_FILES['documenturl__fileurl'], array('type'=>'document'));
            $_POST['documenturl__fileurl'] = $upload['file'];
        }  
        
        $data['response'] = $this->person->add_document('', $this->request->getPost());
        $data['area'] = "document_list";
        echo view('addons/basic_addons', $data);
    }
    
    
    
    
    # View a teacher list
    public function lists()
    {
        $data = filter_forwarded_data($this);
        if (empty($data['action'])) {
            $data['action'] = 'report';
        }
        $instructions['action'] = array('view'=>'view_teacher_data_changes','certify'=>'certify_teacher_application_at_instructor_level', 'confirm' => 'confirm_teacher_application_at_tiet_officer_level', 'verify' => 'verify_teacher_application_at_hr_level', 'approve'=>'verify_teacher_application_at_instructor_level','approve_pre_primary'=>'verify_pre_primary_teacher_application_at_instructor_level','verify_pre_primary'=>'verify_pre_primary_teacher_application_at_hr_level','certify_pre_primary'=>'certify_pre_primary_teacher_application_at_instructor_level', 'report'=>'view_teachers', 'payrollreport'=>'view_payroll_report', 'cimreport'=>'view_cim_report','rejectreport'=>'view_reject_report','mandatoryretirement'=>'view_retirement_report', 'subjectreport'=>'view_teacher_subjectreport','positionreport'=>'view_teacher_positionreport','gradereport'=>'view_teacher_gradereport', 'approvedreport'=>'view_approved_report' );
        $this->session->set('current_action',$data['action']);
        check_access($this, get_access_code($data, $instructions));
        
        $data['list'] = $this->teacher->get_list($data);
        #Make sure the approver has a signature on file if they are going to generate a certificate
        #if(!empty($data['list']) && !$this->session->get('__signature') && !empty($data['action']) && $data['action']=='approve')
        if ((!empty($data['list']) && !$this->session->get('__signature') && !empty($data['action']) && $data['action']=='certify') || (!empty($data['list']) && !$this->session->get('__signature') && !empty($data['action']) && $data['action']=='certify_pre_primary')) {
            $data['msg'] = "WARNING: You need to <a href='".base_url()."/Profile/user_data'>upload a signature</a> to approve teacher certification.";
            $this->session->set('__nosignature', 'Y');
        }
        echo view('teacher/list_teachers', $data);
    }
    
    
    
    
    # Cancel a teacher addition
    public function cancel()
    {
        $data = filter_forwarded_data($this);
        
        $this->teacher->clear_session();
        return redirect()->to('teacher/lists'.(!empty($data['action'])? '/action/'.$data['action']: ''));
    }
    
    
    # Verify the teacher (all actions: approve, reject, etc)
    public function verify()
    {
        $data = filter_forwarded_data($this);
        if (!empty($_POST)) {
            #get Teacher Grade into session [mover]
            $grade = $this->get_grade();
            
            # Approve or reject a teacher
            $result = $this->teacher->verify($_POST);
            
            $actionPart = current(explode("_", $_POST['action']));
            $actions = array('approve'=>'approved', 'reject'=>'rejected', 'archive'=>'archived', 'restore'=>'restored','confirm'=>'confirmed','certify'=>'certified');
            if ($_POST['action'] == "reject_incorrectgrade") $actionWord = 'regarded.';
            else $actionWord = !empty($actions[$actionPart])? $actions[$actionPart]: 'made';
            $this->session->set('msg', "The teacher has been ".$actionWord);
        #$this->session->set('msg', ($result['boolean']? "The teacher has been ".$actionWord: (!empty($result['msg'])? $result['msg']: "ERROR: The teacher could not be ".$actionWord) ));
        } else {
            # Get list type
            $data['list_type'] = current(explode("_", $data['action']));
            $data['area'] = 'verify_teacher';
            echo view('addons/basic_addons', $data);
        }
    }
    
    
    #get grade outof the others
    public function get_grade()
    {
        if (!empty($_POST['other'])) {
            $dataarray = explode('-', $_POST['other']);
        
            $dataarray = explode('|', $dataarray[0]);
    
            $grade_category = explode('_', $dataarray[1]);
            if (!empty($grade_category)) {
                $this->session->set('graded', 'true');
            } else {
                $this->session->remove('graded');
            }
        }
    }
    
    
    
    
    
    
    # Download the list
    public function download()
    {
        
        if(!empty($_POST)) {
            $this->session->set('start_date', $_POST['startdate']);
            $this->session->set('end_date', $_POST['enddate']);
        } 
        $data = filter_forwarded_data($this);
        check_access($this, 'view_teachers');
        
        $data['list'] = array();
        $list = $this->teacher->get_list(array('action'=>(!empty($data['action']) && in_array($data['action'], array('payrollreport','cimreport','rejectreport','mandatoryretirement','subjectreport', 'positionreport','gradereport','approvedreport' ))? $data['action']: 'download'), 'pagecount'=>DOWNLOAD_LIMIT));
        
        # Payroll Teacher Report
        if (!empty($data['action']) && $data['action'] == 'payrollreport') {
            foreach ($list as $row) {
                array_push($data['list'], array('Registration Number'=>$row['file_number'], 'Old UTS Number'=>$row['uts_number'], 'Name'=>$row['name'], 'Title'=>$row['title'], 'Salary Scale'=>$row['salary_scale'], 'Birth Date'=>format_date($row['date_of_birth'], 'd-M-Y', ''), 'Confirmation Date'=>format_date($row['date_of_confirmation'], 'd-M-Y', ''), 'First Appointment Date'=>format_date($row['first_appointment_date'], 'd-M-Y', ''), 'Current Appointment Date'=>format_date($row['current_appointment_date'], 'd-M-Y', ''), 'Status'=>$row['teacher_status'], 'Qualifications'=>$row['qualifications'], 'Proposed Retirement'=>format_date($row['proposed_retirement'], 'd-M-Y', ''), 'Retirement Status'=>$row['retirement_status']  ));
            }
        }
        # CIM Teacher Report
        elseif (!empty($data['action']) && $data['action'] == 'cimreport') {
            foreach ($list as $row) {
                array_push($data['list'], array('Registration Number'=>$row['file_number'], 'Old UTS Number'=>$row['uts_number'], 'Name'=>$row['name'], 'Title'=>$row['title'], 'Responsibility'=>$row['responsibility'], 'Substantive Post'=>$row['substantive_post'], 'Birth Date'=>format_date($row['date_of_birth'], 'd-M-Y', ''), 'Confirmation Date'=>format_date($row['date_of_confirmation'], 'd-M-Y', ''), 'Location'=>$row['location'], 'School'=>$row['school'], 'School Type'=>$row['school_type'], 'Subjects (Major)'=>$row['subjects_major'], 'Subjects (Minor)'=>$row['subjects_minor'], 'Subjects (Other)'=>$row['subjects_other'], 'First Appointment Date'=>format_date($row['first_appointment_date'], 'd-M-Y', ''), 'Posting Date'=>format_date($row['posting_date'], 'd-M-Y', ''), 'Current Appointment Date'=>format_date($row['current_appointment_date'], 'd-M-Y', ''), 'Status'=>$row['teacher_status'], 'Qualifications'=>$row['qualifications'], 'Proposed Retirement'=>format_date($row['proposed_retirement'], 'd-M-Y', ''), 'Retirement Status'=>$row['retirement_status'] ));
            }
        }

        #Rejected Applications
        elseif (!empty($data['action']) && $data['action'] == 'rejectreport') {
            foreach ($list as $row) {
                array_push($data['list'], array('Item'=>$row['Item'], 'Applicant'=>$row['Applicant'], 'Step'=>$row['Step'], 'Approver'=>$row['Approver'], 'Reason'=>$row['Reason'], 'Date'=>format_date($row['Date'], 'd-M-Y', ''), 'Applicant Email'=>$row['ApplicantEmail'], 'Approver Email'=>$row['ApproverEmail'] ));
            }
        }
        #Approved Applicants
        elseif (!empty($data['action']) && $data['action'] == 'approvedreport') {
            foreach ($list as $row) {
                array_push($data['list'], array('Item'=>$row['Item'], 'Applicant'=>$row['Applicant'], 'Step'=>$row['Step'], 'Approver'=>$row['Approver'], 'Reason'=>$row['Reason'], 'Date'=>format_date($row['Date'], 'd-M-Y', ''), 'Applicant Email'=>$row['ApplicantEmail'], 'Approver Email'=>$row['ApproverEmail'] ));
            }
        }

        #Mandatory Retirement
        elseif (!empty($data['action']) && $data['action'] == 'mandatoryretirement') {
            foreach ($list as $row) {
                array_push($data['list'], array('Name'=>$row['teacher_name'], 'Age'=>$row['age'].str_replace('<br>', ' ', format_age($row['age'], 'timeleft')), 'UTS'=>$row['file_number'], 'IPPS'=>$row['ipps'], 'NIN'=>$row['nin'],  'School'=>$row['emp_school']));
            }
        }
        elseif(!empty($data['action']) && $data['action'] == 'subjectreport'){
            foreach ($list as $row) {
                array_push($data['list'], array('Name'=>$row['teacher_name'], 'Age'=>$row['age'].str_replace('<br>', ' ', format_age($row['age'], 'timeleft')), 'NIN'=>$row['nin'],  'School'=>$row['emp_school'], 'Subjects Taught'=>$row['subject'] ));
            }
        }
        elseif(!empty($data['action']) && $data['action'] == 'positionreport'){
            foreach ($list as $row) {
                array_push($data['list'], array('Name'=>$row['teacher_name'], 'Age'=>$row['age'].str_replace('<br>', ' ', format_age($row['age'], 'timeleft')), 'NIN'=>$row['nin'], 'IPPS'=>$row['ipps'], 'School'=>$row['emp_school'], 'Title'=>$row['title'] ));
            }
        }
        elseif(!empty($data['action']) && $data['action'] == 'gradereport'){
            foreach ($list as $row) {
                array_push($data['list'], array('Name'=>$row['teacher_name'], 'Age'=>$row['age'].str_replace('<br>', ' ', format_age($row['age'], 'timeleft')), 'NIN'=>$row['nin'], 'Grade'=>$row['grade'],'Certificate Number'=>$row['tracking_number']."\r",  'School'=>$row['emp_school'], 'Title'=>$row['title'] ));
            }
        }


        # Normal Teacher Report
        else {
            foreach ($list as $row) {
                array_push($data['list'], array('Teacher Name'=>$row['name'], 'Age'=>$row['age'].str_replace('<br>', ' ', format_age($row['age'], 'timeleft')), 'NIN'=>$row['nin'], 'Gender'=>$row['gender'], 'Certificate Number'=>$row['tracking_number']."\r", 'Grade'=>$row['grade'], 'Email Address'=>$row['email_address'], 'Telephone'=>$row['telephone']."\r", 'Date Added'=>date('d-M-Y', strtotime($row['date_added'])) ));
            }
        }
        $data['area'] = 'download_csv';
        echo view('page/download', $data);
    }
    
    
    
    
    
    
    
    # View teacher custom report
    public function custom_report()
    {
        $data = filter_forwarded_data($this);
        check_access($this, 'view_custom_teacher_report');
        
        # The user has posted the report specifications
        if (!empty($_POST)) {
            $data['posts'] = $_POST;
            $data['list'] = $this->teacher->generate_custom_report($this->request->getPost());
            $data['area'] = 'custom_report_view';
            echo view('teacher/addons', $data);
        }
        # This is the main report page
        else {
            echo view('teacher/custom_report', $data);
        }
    }
    
    
    
    
    
    # Show report specs
    public function report_specification()
    {
        $data = filter_forwarded_data($this);
        
        $data['area'] = 'report_specifications';
        echo view('teacher/addons', $data);
    }
}

/* End of controller file */
