<?php

namespace App\Controllers;

/**
 * This class controls viewing profile pages on the system.
 *
 * @author Al Zziwa <azziwa@gmail.com>
 * @version 1.1.0
 * @copyright TMIS
 * @created 01/20/2015
 */

use App\Models\_teacher;
use App\Models\_document;
use App\Models\_person;

class Profile 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();
    }
    
    
    # Update teacher profile
    public function teacher_data()
    {
        $data = filter_forwarded_data($this);
        check_access($this, 'update_my_teacher_profile');
        
        # Set variables to note that the teacher data is being edited
        $data['editing_teacher'] = 'Y';
        $data['id'] = $this->session->get('__user_id');
        
        # 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?
            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'];
                }
            } 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());
                        $this->session->set('msg', (!empty($result['msg'])? $result['msg']: "The teacher data has been updated."));
                        return redirect()->to('profile/teacher_data');
                    }
                } else {
                    $data['msg'] = "WARNING: Your teacher detals could not be resolved for update. ";
                }
            }
            
            # 2. Show the appropriate message
            if (!empty($result)) {
                $this->session->set('msg', (!empty($result['msg'])? $result['msg']: "Your teacher data has been updated."));
            }
        }
        
        #If editing - and for the first time, load the id 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";
        }
        
        # This helps differentiate source of command for shared functions with the teacher's registration functionality
        $this->session->set('is_teacher_updating', 'Y');
        $data['profileuserrole'] = 'teacher';
        echo view('teacher/new_teacher', $data);
    }
    



    # Function to Upgrade a certificate.
    public function upgrade_certificate()
    {
        $data = filter_forwarded_data($this);
        check_access($this, 'upgrade_my_teacher_certificate');
        
        # Set variables to note that the teacher data is being edited
        $data['upgrading_teacher'] = 'Y';
        $data['id'] = $this->session->get('__user_id');
        
        # 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?
            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'];
                }
            } else {
                if ($this->request->getPost('userid')) {
                    $result=$this->teacher->upgrade($this->request->getPost());
                    if ($result['boolean']) {
                        if ($this->session->get('education_list')) {
                            foreach ($this->session->get('education_list') as $educationIndex=>$row) {
                                $result = $this->query_reader->run('add_academic_history', array('person_id'=>$_SESSION['person_id'],
                                'institution'=>$row['institutionname'], 'institution_type'=>$row['institution__institutiontype'],
                                'start_date'=>format_date($row['from__month'].' 01, '.$row['from__pastyear'], 'YYYY-MM-DD'),
                                'end_date'=>format_date($row['to__month'].' 01, '.$row['to__pastyear'], 'YYYY-MM-DD'),
                                'certificate_name'=>$row['certificatename'], 'certificate_number'=>(!empty($row['certificatenumber'])?$row['certificatenumber']:''),
                                'is_highest'=>(!empty($row['highestcertificate'])? 'Y': 'N'),
                                'added_by'=>($this->session->get('__user_id')? $this->session->get('__user_id'): $this->session->get('user_id')) ));
                            }
                        }
                        //$result = $this->person->add_education_and_qualifications($_SESSION['person_id'], $this->request->getPost(NULL, TRUE));
                        $this->session->set('msg', (!empty($result['msg'])? $result['msg']: "Your Certificate Upgrade Application Has been Submitted for evaluation."));
                        return redirect()->to('profile/user_data');
                    }
                } else {
                    $data['msg'] = "WARNING: Your teacher details could not be resolved for update. ";
                }
            }
            
            # 2. Show the appropriate message
            if (!empty($result)) {
                $this->session->set('msg', (!empty($result['msg'])? $result['msg']: "Your teacher data has been updated."));
            }
        }
        
        #If editing - and for the first time, load the id 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";
        }
        
        # This helps differentiate source of command for shared functions with the teacher's registration functionality
        $this->session->set('is_teacher_updating', 'Y');
        $data['profileuserrole'] = 'teacher';

        echo view('register/upgrade_certificate', $data);
    }

    
    
    # Update user profile
    public function user_data()
    {
        $data = filter_forwarded_data($this);
        # Log out the user if the session is not available
        if ($this->session->get('__user_id')) {
            
            #Get Teacher Information
            //check teacher status
            $data['action'] ='approval_status';
            #print_r($_SESSION['__person_id']);
             
            $data['searchstring'] = ' person_id = '.$_SESSION['__person_id'];
            
            $records = $this->teacher->get_list($data);
            #print_r($records); exit();
            $approved = 'N';
            if (!empty($records)) {
                $approved = 'Y';
            }
            
            $data['approved'] = $approved;
            //print_r($data['list']);
            
            if (!empty($_POST)) {
                
                # Process the signature file if one has been uploaded
                if (!empty($_FILES['signature__fileurl']) && file_exists($_FILES['signature__fileurl']['tmp_name'])) {
                    $upload = $this->document->upload($_FILES['signature__fileurl'], array('type'=>'image'));
                    $_POST['signature__fileurl'] = $upload['file'];
                    $this->session->set('signature__fileurl',$upload['file']);
                }
                
                # Process the photo file if one has been uploaded
                if (!empty($_FILES['photo__fileurl']) && file_exists($_FILES['photo__fileurl']['tmp_name'])) {
                    $upload = $this->document->upload($_FILES['photo__fileurl'], array('type'=>'image'));
                    $_POST['photo__fileurl'] = $upload['file'];
                    $this->session->set('photo__fileurl',$upload['file']);
                }
                
                $data['result'] = $this->user->updated($this->session->get('__user_id'), $this->request->getPost());
                $data['msg'] = $data['result']['boolean'] && empty($data['result']['msg'])? "Please check your email for a confirmation code to proceed.": $data['result']['msg'];
            }
            
            $this->user->populate_session($this->session->get('__user_id'), true);
            echo view('profile/user_data', $data);
        } else {
            return redirect()->to("account/logout");
        }
    }
}

/* End of controller file */