<?php

namespace App\Models;

use CodeIgniter\Model;
use App\Models\_approval_chain;
use App\Models\_document;
use App\Models\_query_reader;
use App\Models\_messenger;

class _teacher extends Model
{
    #Constructor to set some default values at class load
    public function __construct()
    {
        // parent::__construct();
        $this->approval_chain = new _approval_chain();
        $this->document = new _document();
        $this->query_reader = new _query_reader();
        $this->messenger = new _messenger();
        $this->db = \Config\Database::connect();
        $this->session = \Config\Services::session();
    }
    
    # Add a new teacher
    public function add_new($teacherDetails)
    {
        $msg = "";
        # First check if a user with the given email already exists
        $check = $this->query_reader->get_row_as_array('get_user_by_email', array('email_address'=>$this->session->get('emailaddress') ));
        if (empty($check)) {
            # 1. Add the person data
            $personId = $this->query_reader->add_data('add_person_data', array('first_name'=>$this->session->get('firstname'), 'last_name'=>$this->session->get('lastname'), 'gender'=>$this->session->get('gender'), 'citizenship_country'=>$this->session->get('citizenship__country'), 'citizenship_type'=>$this->session->get('citizenship__citizentype'), 'marital_status'=>$this->session->get('marital'), 'date_of_birth'=>format_date($this->session->get('birthday'), 'YYYY-MM-DD') ));
            
            if (!empty($personId) || $personId == 0) {
                $emailContactId = $this->query_reader->add_data('add_contact_data', array('contact_type'=>'email', 'carrier_id'=>'', 'details'=>$this->session->get('emailaddress'), 'parent_id'=>$personId, 'parent_type'=>'person'));
                if ($this->session->get('telephone')) {
                    $phoneContactId = $this->query_reader->add_data('add_contact_data', array('contact_type'=>'telephone', 'carrier_id'=>'', 'details'=>$this->session->get('telephone'), 'parent_id'=>$personId, 'parent_type'=>'person'));
                }
                        
                # Save the birth place
                if ($this->session->get('birthplace__addressline')) {
                    $birthPlaceId = $this->add_address($personId, array('address_type'=>'physical', 'importance'=>'birthplace', 'details'=>htmlentities($this->session->get('birthplace__addressline'), ENT_QUOTES), 'district'=>$this->session->get('birthplace__district'), 'country'=>$this->session->get('birthplace__country'), 'county'=>($this->session->get('birthplace__county')? $this->session->get('birthplace__county'): "") ));
                }
                # Save permanent address
                if ($this->session->get('permanentaddress__addressline')) {
                    $permanentId = $this->add_address($personId, array('address_type'=>$this->session->get('permanentaddress__addresstype'), 'importance'=>'permanent', 'details'=>$this->session->get('permanentaddress__addressline'), 'district'=>$this->session->get('permanentaddress__district'), 'country'=>$this->session->get('permanentaddress__country'), 'county'=>($this->session->get('permanentaddress__county')? $this->session->get('permanentaddress__county'): "") ));
                }
                # Save contact address
                if ($this->session->get('contactaddress__addressline')) {
                    $contactId = $this->add_address($personId, array('address_type'=>$this->session->get('contactaddress__addresstype'), 'importance'=>'contact', 'details'=>$this->session->get('contactaddress__addressline'), 'district'=>$this->session->get('contactaddress__district'), 'country'=>$this->session->get('contactaddress__country'), 'county'=>($this->session->get('contactaddress__county')? $this->session->get('contactaddress__county'): "") ));
                }
                
                if ($this->session->get('teacherid')) {
                    $this->add_another_id($personId, array('id_type'=>'teacher_id', 'id_value'=>$this->session->get('teacherid')));
                }
                
                # 3. Create an account - For the first account, use the user's email address as the login username.
                $password = generate_temp_password();
                $userId = $this->query_reader->add_data('add_user_data', array('person_id'=>$personId, 'login_name'=>$this->session->get('emailaddress'), 'login_password'=>sha1($password), 'permission_group'=>'Teacher', 'status'=>'completed' ));
                
                if (empty($userId)) {
                    $msg = "ERROR: We could not create your user record.";
                } else {
                    $result = $this->messenger->send($userId, array('code'=>'introduce_new_user', 'email_from'=>SITE_ADMIN_MAIL, 'from_name'=>SITE_ADMIN_NAME, 'password'=>$password, 'first_name'=>$this->session->get('firstname'), 'emailaddress'=>$this->session->get('emailaddress'), 'login_link'=>base_url(), array('email')));
                    if (!$result) {
                        $msg = "ERROR: We could not send the new account email message to the user.";
                    }
                    
                    $this->session->set('user_id', $userId);
                }
                
                
                # 4. Take note of the new teacher's person ID for use later
                if (!empty($result) && $result) {
                    $this->session->set('person_id', $personId);
                    # If we have been using a temp person ID, update the database with the real ID and remove the temp one
                    if ($this->session->get('temp_person_id')) {
                        $result = $this->query_reader->run('update_document_owner', array('temp_id'=>$this->session->get('temp_person_id'), 'actual_id'=>$personId ));
                        if ($result) {
                            $this->session->remove('temp_person_id');
                        }
                    }
                }
            } else {
                $msg = "ERROR: We could not create your record.";
            }
        } else {
            $msg = "WARNING: A user with the email entered already exists. Please login or recover your password to continue'";
        }
        
        return array('boolean'=>(!empty($result)? $result: false), 'msg'=>$msg, 'id'=>(!empty($userId)? $userId: ''), 'person_id'=>(!empty($personId)? $personId: ''));
    }
        
            
        
        
    # Update the teacher data
    public function updated($details)
    {
        $msg = '';
        $results = array();
        $user = $this->query_reader->get_row_as_array('get_user_by_id', array('user_id'=>$details['userid']));
        
        $result = $this->query_reader->run('update_person_data', array('person_id'=>$user['person_id'], 'first_name'=>$this->session->get('firstname'),
        'last_name'=>$this->session->get('lastname'), 'gender'=>$this->session->get('gender'),
        'nin'=>strtoupper($this->session->get('nin')), 'religion'=>$this->session->get('religion'),
        'teacherQualCat'=>$this->session->get('teacherQualCat'),'emp_school'=>$this->session->get('emp_school'),
        // 'emis'=>$this->session->get('emis'),
        'employmentCat'=>$this->session->get('employmentCat'),
        'ipps'=>$this->session->get('ipps'),'title'=>$this->session->get('title'),
        'region'=>$this->session->get('region'),'emp_district'=>$this->session->get('emp_district'),
        'emp_subCounty'=>$this->session->get('emp_subCounty'),
        'marital_status'=>($this->session->get('marital')? $this->session->get('marital'): 'unknown'),
        'citizenship_country'=>$this->session->get('citizenship__country'),
        'citizenship_type'=>$this->session->get('citizenship__citizentype'),
        'date_of_birth'=>format_date($this->session->get('birthday'), 'YYYY-MM-DD') ));
        
        array_push($results, $result);
        
        #re-apply condition
            
        if ($this->session->get('teacherstatus') == 'rejected' || $this->session->get('teacherstatus') == 'pending') {
            $reapply = $this->change_status($details['userid'], 'completed');
            $msg=$reapply? "Your application has been re-submitted for consideration.": "WARNING: Your application was not submitted.";
        }
        
        # Add or update the contact telephone if given
        if ($this->session->get('telephone')) {
            $telno=$this->query_reader->get_list('get_telephone_number', array('parent_id'=>$user['person_id']));
            $code=(!empty($telno))? 'update_contact_data': 'add_contact_data';
            $result = $this->query_reader->run($code, array('details'=>$this->session->get('telephone'),
            'carrier_id'=>'', 'contact_type'=>'telephone', 'parent_type'=>'person', 'parent_id'=>$user['person_id'] ));
            array_push($results, $result);
        }

        #Update the email address if given
        if ($this->session->get('emailaddress')) {
            $result = $this->query_reader->run('update_user_email', array('user_id'=>$details['userid'], 'login_name'=>$this->session->get('emailaddress'),
             'details'=>$this->session->get('emailaddress'), 'carrier_id'=>'', 'contact_type'=>'email', 'parent_type'=>'person',
             'parent_id'=>$user['person_id'], 'updated_by'=>$this->session->get('user_id') ));
            array_push($results, $result);
        }
        
        if ($this->session->get('birthplace__addressline')) {
            $result = $this->query_reader->run('update_address_data', array('parent_id'=>$user['person_id'], 'parent_type'=>'person', 'address_type'=>'physical', 'importance'=>'birthplace', 'details'=>$this->session->get('birthplace__addressline'), 'district'=>$this->session->get('birthplace__district'), 'country'=>$this->session->get('birthplace__country'), 'county'=>($this->session->get('birthplace__county')? $this->session->get('birthplace__county'): "") ));
            array_push($results, $result);
        }
        # Save permanent address
        if ($this->session->get('permanentaddress__addressline')) {
            $result = $this->query_reader->run('update_address_data', array('parent_id'=>$user['person_id'], 'parent_type'=>'person', 'address_type'=>$this->session->get('permanentaddress__addresstype'), 'importance'=>'permanent', 'details'=>$this->session->get('permanentaddress__addressline'), 'district'=>$this->session->get('permanentaddress__district'), 'country'=>$this->session->get('permanentaddress__country'), 'county'=>($this->session->get('permanentaddress__county')? $this->session->get('permanentaddress__county'): "") ));
        }
        # Save contact address
        if ($this->session->get('contactaddress__addressline')) {
            $result = $this->query_reader->run('update_address_data', array('parent_id'=>$user['person_id'], 'parent_type'=>'person', 'address_type'=>$this->session->get('contactaddress__addresstype'), 'importance'=>'contact', 'details'=>$this->session->get('contactaddress__addressline'), 'district'=>$this->session->get('contactaddress__district'), 'country'=>$this->session->get('contactaddress__country'), 'county'=>($this->session->get('contactaddress__county')? $this->session->get('contactaddress__county'): "") ));
        }
        
        
        $this->add_another_id($user['person_id'], array('id_type'=>'teacher_id', 'id_value'=>$this->session->get('teacherid')));
        
        return array('boolean'=>(!empty($result)? $result: false), 'msg'=>$msg, 'id'=>(!empty($userId)? $userId: ''), 'person_id'=>$user['person_id']);
    }
    
        
    
    
    # Add another ID that identifies that person on a third party system
    public function add_another_id($personId, $idDetails)
    {
        return $this->query_reader->add_data('add_another_id', array('parent_id'=>$personId, 'parent_type'=>'person', 'id_type'=>$idDetails['id_type'], 'id_value'=>$idDetails['id_value']));
    }
        
    
    # Add a person's address
    public function add_address($personId, $addressDetails)
    {
        return $this->query_reader->add_data('add_new_address', array('parent_id'=>$personId, 'parent_type'=>'person', 'address_type'=>$addressDetails['address_type'], 'importance'=>$addressDetails['importance'], 'details'=>$addressDetails['details'], 'county'=>$addressDetails['county'], 'district'=>$addressDetails['district'], 'country'=>$addressDetails['country']));
    }


    # Clear a teacher session profile
    public function clear_session()
    {
        $fields = ['lastname', 'firstname', 'telephone', 'emailaddress', 'gender', 'marital', 'birthday', 'birthplace__addressline',
        'nin', 'ipps', 'religion', 'region', 'title', 'teacherQualCat','emp_school','employmentCat','emp_district','emp_subCounty',
        'birthplace__county', 'birthplace__district', 'birthplace__country', 'birthplace__addresstype', 'birthplace__district__hidden',
        'birthplace__country__hidden', 'teacherid', 'permanentaddress', 'permanentaddress__addressline', 'permanentaddress__county',
        'permanentaddress__district', 'permanentaddress__country', 'permanentaddress__addresstype', 'contactaddress',
        'contactaddress__addressline', 'contactaddress__county', 'contactaddress__district', 'contactaddress__country',
        'contactaddress__addresstype', 'citizenship__country', 'citizenship__citizentype', 'education_list', 'subject_list',
         'is_admin_adding_teacher', 'profile_id', 'profile_personid', 'profile_nin', 'profile_loginname', 'profile_userrole', 'profile_lastname',
         'profile_firstname', 'profile_signature', 'profile_telephone', 'profile_emailaddress', 'profile_photo'];
        
        $this->session->remove($fields);
    }
    
    
    
    

    # Populate a user session profile
    public function populate_session($teacherId)
    {
        $teacher = $this->query_reader->get_row_as_array('get_teacher_profile', array('teacher_id'=>$teacherId));
        
        if (!empty($teacher)) {
            $this->session->set('user_id', $teacherId);
            $this->session->set('lastname', $teacher['last_name']);
            $this->session->set('firstname', $teacher['first_name']);
            $this->session->set('teacherstatus', $teacher['teacher_status']);
            $this->session->set('telephone', $teacher['telephone']);
            $this->session->set('emailaddress', $teacher['email_address']);
            $this->session->set('gender', $teacher['gender']);
            $this->session->set('marital', $teacher['marital_status']);
            $this->session->set('birthday', $teacher['date_of_birth']);
            $this->session->set('nin', $teacher['nin']);
            $this->session->set('religion', $teacher['religion']);
            $this->session->set('teacherQualCat', $teacher['teacherQualCat']);
            $this->session->set('emp_school', $teacher['emp_school']);
            // $this->session->set('emis', $teacher['emis']);
            $this->session->set('employmentCat', $teacher['employmentCat']);
            $this->session->set('ipps', $teacher['ipps']);
            $this->session->set('title', $teacher['title']);
            $this->session->set('region', $teacher['region']);
            $this->session->set('emp_district', $teacher['emp_district']);
            $this->session->set('emp_subCounty', $teacher['emp_subCounty']);
            $this->session->set('photo', $teacher['photo']);
            $this->session->set('birthplace__addressline', $teacher['birthplace__addressline']);
            $this->session->set('birthplace__county', $teacher['birthplace__county']);
            $this->session->set('birthplace__district', $teacher['birthplace__district']);
            $this->session->set('birthplace__country', $teacher['birthplace__country']);
            $this->session->set('birthplace__addresstype', $teacher['birthplace__addresstype']);
            $this->session->set('teacherid', $teacher['teacher_id']);
            $this->session->set('person_id', $teacher['person_id']);
            $this->session->set('permanentaddress', $teacher['permanentaddress__addressline']);
            $this->session->set('permanentaddress__addressline', $teacher['permanentaddress__addressline']);
            $this->session->set('permanentaddress__county', $teacher['permanentaddress__county']);
            $this->session->set('permanentaddress__district', $teacher['permanentaddress__district']);
            $this->session->set('permanentaddress__country', $teacher['permanentaddress__country']);
            $this->session->set('permanentaddress__addresstype', $teacher['permanentaddress__addresstype']);
            $this->session->set('contactaddress', $teacher['contactaddress__addressline']);
            $this->session->set('contactaddress__addressline', $teacher['contactaddress__addressline']);
            $this->session->set('contactaddress__county', $teacher['contactaddress__county']);
            $this->session->set('contactaddress__district', $teacher['contactaddress__district']);
            $this->session->set('contactaddress__country', $teacher['contactaddress__country']);
            $this->session->set('contactaddress__addresstype', $teacher['contactaddress__addresstype']);
            $this->session->set('citizenship__country', $teacher['citizenship__country']);
            $this->session->set('citizenship__citizentype', $teacher['citizenship__type']);
            $this->session->set('verificationcode', generate_person_code($teacher['person_id']));
            #Get teacher education
            $education = $this->query_reader->get_list('get_teacher_education', array('person_id'=>$teacher['person_id']));
            $this->session->set('education_list', $education);
            
            #Get teacher's subjects taught list
            $subjects = $this->query_reader->get_list('get_teacher_subjects', array('person_id'=>$teacher['person_id']));
            $this->session->set('subject_list', $subjects);
            
            #Get teacher's document list
            $documents = $this->query_reader->get_list('get_teacher_documents', array('person_id'=>$teacher['person_id']));
            $this->session->set('document_list', $documents);
            #Get the teacher's system issued documents
            $certs = $this->query_reader->get_list('get_teacher_certificates', array('person_id'=>$teacherId));
            $this->session->set('certs_list', $certs);

            #Get the tiet issued certificates
            $tiet = $this->query_reader->get_list('get_tiet_certificates', array('person_id'=>$teacher['person_id'] ));
            $this->session->set('tiet_list', $tiet);
        }
    }
    
                
        
        
    # Add new posted data to the session
    public function add_to_session($details)
    {
        return process_fields($this, $details);
    }
    


        
    
    # Get list of teachers
    public function get_list($instructions=array())
    {
        $searchString = " U.teacher_status='active' AND U.permission_group_id='2' ";
        $query = 'get_teacher_list_data';
        if (!empty($instructions['action']) && $instructions['action']== 'view') {
            $searchString = " U.teacher_status IN ('pending', 'completed') ";
        } elseif (!empty($instructions['action']) && $instructions['action']== 'verify') {
            $searchString = " (wip_id = 0 OR wip_id=" .$this->session->get('__user_id'). ") AND (U.permission_group_id='2' OR U.permission_group_id = '1') AND U.teacher_status = 'completed' AND (P.teacherQualCat IS NULL OR NOT P.teacherQualCat = 'Pre-Primary') ";
        } elseif (!empty($instructions['action']) && $instructions['action']== 'approve') {
            $searchString = " (wip_id = 0 OR wip_id=" .$this->session->get('__user_id'). ") AND U.teacher_status = 'approved' AND (P.teacherQualCat IS NULL OR NOT P.teacherQualCat = 'Pre-Primary') AND U.permission_group_id='2' ";
        } elseif (!empty($instructions['action']) && $instructions['action']== 'confirm') {
            $searchString = " U.teacher_status = 'approved' AND U.permission_group_id='2' ";
        } elseif (!empty($instructions['action']) && $instructions['action']== 'certify') {
            //exit("movers");
            $searchString = " U.teacher_status = 'confirmed' AND (P.teacherQualCat IS NULL OR NOT P.teacherQualCat = 'Pre-Primary') AND U.permission_group_id='2' ";
        }elseif (!empty($instructions['action']) && $instructions['action']== 'verify_pre_primary') {
            $searchString = " (wip_id = 0 OR wip_id=" .$this->session->get('__user_id'). ") AND (U.permission_group_id='2' OR U.permission_group_id = '1') AND U.teacher_status = 'completed' AND P.teacherQualCat = 'Pre-Primary' ";
        } elseif (!empty($instructions['action']) && $instructions['action']== 'approve_pre_primary') {
            $searchString = " (wip_id = 0 OR wip_id=" .$this->session->get('__user_id'). ") AND U.teacher_status = 'approved' AND P.teacherQualCat = 'Pre-Primary' AND U.permission_group_id='2' ";
        } elseif (!empty($instructions['action']) && $instructions['action']== 'certify_pre_primary') {
            $searchString = " U.teacher_status = 'confirmed' AND P.teacherQualCat = 'Pre-Primary' AND U.permission_group_id='2' ";
        } elseif (!empty($instructions['action']) && $instructions['action']== 'payrollreport') {
            $searchString = " U.teacher_status NOT IN ('unknown','pending') ";
            $query = 'get_teacher_payroll_data';
        } elseif (!empty($instructions['action']) && $instructions['action']== 'cimreport') {
            $searchString = " U.teacher_status NOT IN ('unknown','pending') ";
            $query = 'get_teacher_cim_data';
        } elseif (!empty($instructions['action']) && $instructions['action']== 'rejectreport') {
            $searchString = " A.status = 'rejected' ";
            $query = 'get_reject_list';
        } elseif (!empty($instructions['action']) && $instructions['action']== 'approvedreport') {
            $searchString = " A.status = 'approved' ";
            $query = 'get_reject_list';
        } elseif (!empty($instructions['action']) && $instructions['action']== 'approval_status') {
            $searchString = "U.teacher_status IN ('approved', 'completed') AND (U.permission_group_id='2' OR U.permission_group_id = '1') ";
        } elseif (!empty($instructions['action']) && $instructions['action']== 'mandatoryretirement') {
            $searchString = " P.employmentCat ='Government' ";
            $query = 'get_mandatory_retirement_list';
        }
        elseif (!empty($instructions['action']) && $instructions['action']== 'subjectreport') {
            $searchString = " U.teacher_status ='active' AND U.permission_group_id='2' ";
            $query = 'get_subjects_taught_list';
        }
        elseif (!empty($instructions['action']) && $instructions['action']== 'gradereport') {
            $searchString = " U.teacher_status ='active' AND U.permission_group_id='2' ";
            $query = 'get_teacher_grades_list';
        }
        elseif (!empty($instructions['action']) && $instructions['action']== 'positionreport') {
            $searchString = " U.teacher_status ='active' AND U.permission_group_id='2' ";
            $query = 'get_positions_held_list';
        }
        
        # If a search phrase is sent in the instructions
        if (!empty($instructions['searchstring'])) {
            $searchString .= " AND ".$instructions['searchstring'];
        }
        if (!empty($_SESSION['end_date']) && !empty($_SESSION['start_date'])) {
            $range = " (U.date_added BETWEEN DATE('" .format_date($_SESSION['start_date']). "') AND DATE('" .format_date($_SESSION['end_date']). "'))";
            $searchString .= " AND " .$range;            
        }
        
        # Instructions
        $count = !empty($instructions['pagecount'])? $instructions['pagecount']: NUM_OF_ROWS_PER_PAGE;
        $start = !empty($instructions['page'])? ($instructions['page']-1)*$count: 0;
        
        return $this->query_reader->get_list($query, array('search_query'=>$searchString, 'limit_text'=>$start.','.($count+1), 'order_by'=>" ORDER BY U.id ASC "));
        $this->session->remove(['start_date','end_date']);
    }
    
    
    
    
    
    
    
    
    # Approve or reject a teacher
    public function verify($instructions)
    {
        $result = array('boolean'=>false, 'msg'=>'ERROR: The teacher verification instructions could not be resolved.');
        
        if (!empty($instructions['action'])) {
            switch ($instructions['action']) {
                case 'approve_toapproved':
                    $result = $this->approval_chain->add_chain($instructions['id'], 'registration', '2', 'approved', (!empty($instructions['reason'])? htmlentities($instructions['reason'], ENT_QUOTES): ''));
                    $this->change_status($instructions['id'], 'approved');
                    $this->query_reader->run('update_work_in_progress', array('user_id'=>$instructions['id'], 'wip_id'=>0));
                    #Also activate the user so that they can log in - at the first approval
                    $result2 = $this->query_reader->run('update_user_status', array('user_id'=>$instructions['id'], 'status'=>'active', 'updated_by'=>$this->session->get('__user_id') ));
                break;
                
                case  'certify_certificate':
                $result = $this->approval_chain->add_chain($instructions['id'], 'registration', '4', 'approved', (!empty($instructions['reason'])? htmlentities($instructions['reason'], ENT_QUOTES): ''), $details=array());
                    
                $signature = 	$this->session->get('__signature');
                $QUERY = $this->db->query("SELECT * FROM teacher_certificates  WHERE person_id = (SELECT person_id FROM user WHERE id = ".$instructions['id'].") ORDER BY  id DESC LIMIT 1 ")->getResultArray();
                
                $tracking_number = $this->approval_chain->generate_certificate_number($instructions['id'], $QUERY[0]['grade']);
     
                $filename = $letterUrl = 'Certificate_of_registration_'.strtotime('now').'.pdf';
                $location = UPLOAD_DIRECTORY.'documents/';
                $document = $QUERY[0]['certificate'];
                
                #ADD DETAILS TO REPOPULATE TEMPLATE TO ADD COMMISSIONER SIGNATURE
                $documentdetails['SIGNATUREURL'] = $signature;
                $documentdetails['trackingnumber'] = $documentdetails['CERTIFICATENUMBER'] = $tracking_number;

                $template['details'] =  $QUERY[0]['certificate'];
                
                $document =$this->document->populate_template($template, $documentdetails);       
        
                $return = 'url';
                $documentSettings = array('size'=>'A4','orientation'=>'portrait');
                if (!empty($details['document_size'])) {
                    $documentSettings['size'] = $details['document_size'];
                }
                if (!empty($details['document_orientation'])) {
                    $documentSettings['orientation'] = $details['document_orientation'];
                }
                $action='save';
                
                $this->document->generate_pdf($document, $location.$letterUrl, $action, $documentSettings);
                
                # If the file is created, then return the file name, else, just an empty string
                $letterUrl =  file_exists($location.$letterUrl)? ($return == 'url'? $location.$letterUrl: $letterUrl): '';
                        
                $documentType  = 'send_registration_certificate';
                $requiredModes =  array('system');
                $userid = $instructions['id'];
                
                    
                 
                if (!empty($letterUrl)) {
                    if ($result) {
                        $this->query_reader->run('add_system_document', array('url'=>$filename, 'document_type'=>'registration_certificate', 'grade'=>$QUERY[0]['grade'], 'tracking_number'=>$tracking_number, 'description'=>'Registration Certificate', 'parent_id'=>$userid, 'parent_type'=>'person' ));
                    }
                                 
                    $result = $this->messenger->send($userid, array('code'=>$documentType, 'fileurl'=>$letterUrl, 'email_from'=>SITE_ADMIN_MAIL, 'from_name'=>SITE_ADMIN_NAME));
                }
                $result = 	$this->change_status($instructions['id'], 'active');
                $data['boolean'] = true;
                return $data;

                break;
                
                case 'reject_fromcompleted':
                $result = $this->approval_chain->add_chain(
                    $instructions['id'],
                    'registration',
                    '2',
                    'rejected',
                    (!empty($instructions['reason'])? htmlentities($instructions['reason'], ENT_QUOTES): 'Reason Not Given by HR.')
                );
                $this->handle_rejection_change_status($instructions['id'], 'rejected', $instructions['reason']);
                $this->query_reader->run('update_work_in_progress', array('user_id'=>$instructions['id'], 'wip_id'=>0));
                break;
                
                case 'approve_toactive':
                    #These details are passed in the other field from the UI
                    $instructions = process_other_field($instructions);
                    $details['effectivedate'] = $instructions['effectivedate'];
                    $details['grade__grades'] = $instructions['grade__grades'];
                    
                    $result = $this->approval_chain->add_chain($instructions['id'], 'registration', '3', 'approved', (!empty($instructions['reason'])? htmlentities($instructions['reason'], ENT_QUOTES): ''), $details);
                    
                    $this->change_status($instructions['id'], 'active');
                break;
                
                case 'approve_toconfirmed':
                    #These details are passed in the other field from the UI
                    $instructions = process_other_field($instructions);
                    $details['effectivedate'] = $instructions['effectivedate'];
                    $details['grade__grades'] = !isset($instructions['grade__grades'])? $instructions['multiple']:$instructions['grade__grades'];
                    
                    $result = $this->approval_chain->add_chain($instructions['id'], 'registration', '3', 'approved', (!empty($instructions['reason'])? htmlentities($instructions['reason'], ENT_QUOTES): ''), $details);
                    
                    $this->change_status($instructions['id'], 'confirmed');
                    $this->query_reader->run('update_work_in_progress', array('user_id'=>$instructions['id'], 'wip_id'=>0));
                break;

                case 'confirm_document':
                    #These details are passed in the other field from the UI
                    $instructions = process_other_field($instructions);
                    $details['effectivedate'] = $instructions['effectivedate'];
                    $details['grade__grades'] = $instructions['grade__grades'];
                    $result = $this->approval_chain->add_chain($instructions['id'], 'registration', '3', 'confirm', (!empty($instructions['reason'])? htmlentities($instructions['reason'], ENT_QUOTES): ''), $details);
                    #confirmed ::
                    $this->change_status($instructions['id'], 'confirmed');
                    
                    
                break;
                case 'reject_fromapproved':
                $result = $this->approval_chain->add_chain(
                    $instructions['id'],
                    'registration',
                    '3',
                    'rejected',
                    (!empty($instructions['reason'])? htmlentities($instructions['reason'], ENT_QUOTES): 'The reason was not given by Tiet Officer.'),
                    $details=array()
                );
                $this->handle_rejection_change_status(
                    $instructions['id'],
                    'rejected',
                    $instructions['reason']
                );
                $this->query_reader->run('update_work_in_progress', array('user_id'=>$instructions['id'], 'wip_id'=>0));
                break;
            
                case 'reject_fromcertified':
                $result = $this->approval_chain->add_chain(
                    $instructions['id'],
                    'registration',
                    '4',
                    'rejected',
                    (!empty($instructions['reason'])? htmlentities($instructions['reason'], ENT_QUOTES): 'The reason was not given by Commissioner Tiet.'),
                    $details=array()
                );
                    // $this->change_status($instructions['id'], 'approved');
                    $this->handle_rejection_change_status($instructions['id'],'rejected', $instructions['reason']);
                break;

                case 'reject_incorrectgrade':
                    $result = $this->approval_chain->add_chain(
                        $instructions['id'], 'registration', '4', 'rejected',
                        (!empty($instructions['reason'])? htmlentities($instructions['reason'], ENT_QUOTES): 'Grade awarded by Tiet was incorrect.'),
                        $details=array());
                    $this->query_reader->run('update_teacher_status', array('user_id'=>$instructions['id'], 'status'=>'approved', 'updated_by'=>$this->session->get('__user_id')));
                break;

                case 'archive':
                    $result = $this->change_status($instructions['id'], 'archived');
                break;
                
                case 'restore':
                    $result = $this->change_status($instructions['id'], 'active');
                break;
            }
        }
        
        return $result;
    }
    
    
    
    public function handle_rejection_change_status($userId, $newStatus, $rejectReason)
    {
        $result1 = !in_array($newStatus, array('archived'))?
        $this->messenger->send($userId, array('code'=>'reject_user_application',
        'status'=>strtoupper($newStatus), 'reason'=>$rejectReason)): true;
        
        $result2 = $this->query_reader->run(
            'update_teacher_status', array('user_id'=>$userId, 'status'=>$newStatus, 'updated_by'=>$this->session->get('__user_id')));
        
        return get_decision(array($result1,$result2), false);
    }
    
    

    
    # Change the status of the teacher
    public function change_status($userId, $newStatus)
    {
        $result1 = !in_array($newStatus, array('archived'))? $this->messenger->send($userId, array('code'=>'notify_change_of_user_status', 'status'=>strtoupper($newStatus))): true;
        
        $result2 = $this->query_reader->run('update_teacher_status', array('user_id'=>$userId, 'status'=>$newStatus, 'updated_by'=>$this->session->get('__user_id') ));
        
        return get_decision(array($result1,$result2), false);
    }
    
    
    
    
    # Get teacher documents
    public function get_documents($teacherId)
    {
        return $this->query_reader->get_list('get_user_documents', array('user_id'=>$teacherId));
    }
    



    #Upgrade certificate
    public function upgrade($details)
    {
        $msg = "";

        # 1. Mark the user status as complete - for the HR to be able to approve it
        $result1 = $this->query_reader->run('update_teacher_status', array('user_id'=>$details['userid'], 'status'=>'completed', 'updated_by'=>$details['userid']));
        if (!$result1) {
            $msg = "ERROR: We could not submit your application for a Certificate Upgrade.";
        }

        # 2. Start the teacher approval chain
        $result = $this->approval_chain->add_chain($details['userid'], 'registration', '1', 'approved', 'Certificate Upgrade Request.');
        $result2 = $result['boolean'];
        if (!$result2) {
            $msg = "ERROR: We could not set up your upgrade for approval.";
        }

        # 3. Send notification of application submission
        $result3 =  $this->messenger->send($details['userid'], array('code'=>'upgrade_application_submitted', 'email_from'=>SIGNUP_EMAIL, 'from_name'=>SITE_GENERAL_NAME, 'first_name'=>htmlentities($_SESSION['firstname'], ENT_QUOTES), 'emailaddress'=>$_SESSION['emailaddress'], 'login_link'=>base_url() ), array('email'));
        
        if (!$result3) {
            $msg = "ERROR: We could not send your Certificate Upgrade confirmation email.";
        }
        $isSubmitted = get_decision(array($result1,$result2), false);
    
        return array('boolean'=>$isSubmitted, 'msg'=>($isSubmitted? "Your application for a Certificate Upgrade has been submitted.": $msg));
    }






    
    
    # Generate custom report
    public function generate_custom_report($specs)
    {
        $list = array();
        if ($specs['reporttype__reporttypes'] == 'Number of Registered Teachers') {
            switch ($specs['reportsubtype__registerednumbers']) {
                case 'By Gender':
                    $list = $this->query_reader->get_list('report_stat_registerednumbers_by_gender');
                break;
                
                case 'By Grade':
                    $list = $this->query_reader->get_list('report_stat_registerednumbers_by_grade');
                break;
                
                case 'By Subject':
                    $list = $this->query_reader->get_list('report_stat_registerednumbers_by_subject');
                break;
                
                case 'By School':
                    $list = $this->query_reader->get_list('report_stat_registerednumbers_by_school');
                break;
                
                case 'By District':
                    $list = $this->query_reader->get_list('report_stat_registerednumbers_by_district');
                break;
                
                case 'By Region':
                    $list = $this->query_reader->get_list('report_stat_registerednumbers_by_region');
                break;
                case 'By Religion':
                    $list = $this->query_reader->get_list('report_stat_registerednumbers_by_religion');
                break;
                case 'By Position':
                    $list = $this->query_reader->get_list('report_stat_registerednumbers_by_position');
                break;
                case 'By Teaching Category':
                    $list = $this->query_reader->get_list('report_stat_registerednumbers_by_teaching_category');
                break;
                case 'By Employment Category':
                    $list = $this->query_reader->get_list('report_stat_registerednumbers_by_employment_category');
                break;
                case 'Due for Retirement':
                    $list = $this->query_reader->get_list('report_stat_registerednumbers_due_for_retirement');
                break;
            }
        } elseif ($specs['reporttype__reporttypes'] == 'Teacher Appointments') {
            switch ($specs['reportsubtype__teacherappointments']) {
                case 'By Post':
                    $list = $this->query_reader->get_list('report_stat_teacherappointments_by_post', array('start_date'=>format_date($specs['startdate']),'end_date'=>format_date($specs['enddate']) ));
                break;
                
                case 'By School':
                    $list = $this->query_reader->get_list('report_stat_teacherappointments_by_school', array('start_date'=>format_date($specs['startdate']),'end_date'=>format_date($specs['enddate']) ));
                break;
                
                case 'By District':
                    $list = $this->query_reader->get_list('report_stat_teacherappointments_by_district', array('start_date'=>format_date($specs['startdate']),'end_date'=>format_date($specs['enddate']) ));
                break;
                
                case 'By Region':
                    $list = $this->query_reader->get_list('report_stat_teacherappointments_by_region', array('start_date'=>format_date($specs['startdate']),'end_date'=>format_date($specs['enddate']) ));
                break;
            }
        } elseif ($specs['reporttype__reporttypes'] == 'Teacher Status') {
            switch ($specs['reportsubtype__teacherstatus']) {
                case 'Applied':
                    $list = $this->query_reader->get_list('report_stat_teacherstatus_applied');
                break;
                
                case 'On Probation':
                    $list = $this->query_reader->get_list('report_stat_teacherstatus_on_probation');
                break;
                
                case 'Confirmed':
                    $list = $this->query_reader->get_list('report_stat_teacherstatus_confirmed');
                break;
                
                case 'On Leave':
                    $list = $this->query_reader->get_list('report_stat_teacherstatus_on_leave');
                break;
                
                case 'Retired':
                    $list = $this->query_reader->get_list('report_stat_teacherstatus_retired');
                break;
                case 'Rejected':
                    $list = $this->query_reader->get_list('report_stat_teacherstatus_rejected');
                break;

                case 'Pending':
                    $list = $this->query_reader->get_list('report_stat_teacherstatus_pending');
                break;

                case 'Verified':
                    $list = $this->query_reader->get_list('report_stat_teacherstatus_verified');
                break;


                case 'Rejected':
                    $list = $this->query_reader->get_list('report_stat_teacherstatus_rejected');
                break;
                case 'Approved':
                    $list = $this->query_reader->get_list('report_stat_teacherstatus_approved');
                break;
                                
                                case 'Certified':

                                        $list = $this->query_reader->get_list('report_stat_teacherstatus_certified');
                                break;
            }
        } elseif ($specs['reporttype__reporttypes'] == 'Monitoring') {
            switch ($specs['reportsubtype__monitoring']) {
                case 'Applications':
                    $list = $this->query_reader->get_list('monitor_applications_report', array('start_date'=>format_date($specs['startdate']),'end_date'=>format_date($specs['enddate']) ));
                break;

                case 'Department':
                    $list = $this->query_reader->get_list('monitor_department_report', array('start_date'=>format_date($specs['startdate']),'end_date'=>format_date($specs['enddate']) ));
                break;

                case 'Staff':
                    $list = $this->query_reader->get_list('monitor_staff_report', array('start_date'=>format_date($specs['startdate']),'end_date'=>format_date($specs['enddate']) ));
                break;

            }
        }

    
        return $list;
    }
}