<?php namespace App\Controllers;

use App\Models\FieldModel;
use App\Models\InvoiceModel;
use App\Models\UserModel;
use App\Models\NewsModel;
use App\Models\ScheduleModel;
use App\Models\FacultyModel;
use App\Models\CourseModel;
use App\Models\CountryModel;
use App\Models\CenterModel;
use App\Models\ApplicationModel;
use App\Models\OnlineApplicationModel;
use App\Models\CourseOutlineModel;
use App\Models\UsersCourses;
use App\Controllers\Proforma;
use App\Controllers\ProformaOnline;
use \Hermawan\DataTables\DataTable;

use CodeIgniter\HTTP\RequestInterface;



class Home extends BaseController {

    private $cats;
    private $course;


    function __construct() {
        $facultyModel = new FacultyModel();
        $this->$cats = $facultyModel->orderBy('facultyName', 'ASC')->findAll();

    }

    public function about_us() {
        $data['cats'] = $this->$cats;
        $data['meta_desc'] ="";
        $data['meta_keywords'] ="";
        $courseModel = new CourseModel();
        $data['trendings'] = $courseModel->join('durationtypes', 'courses.durationType=durationtypes.typeID')->orderBy('courseID', 'ASC')->limit(4)->findAll();

        $courseModel = new CourseModel();
        $data['recents'] = $courseModel->join('durationtypes', 'courses.durationType=durationtypes.typeID')->orderBy('courseID', 'DESC')->limit(4)->findAll();

        $scheduleModel = new ScheduleModel();
        $data['schedules'] = $scheduleModel->getUpcomingSchedules();
        echo view('templates/header', $data);
        echo view('about_view');
        echo view('templates/footer');
    }

//--------------------------------------------------------------------

    public function index() {
       
        $data['cats'] = $this->$cats;
        $data['page_title'] = "Capacity building and consultancy company";
        $data['meta_desc'] = 'We offer informative & practical training on data analysis, Business, Health, Monitoring & evaluation, Project management, IT, Leadership and Management.';
        $data['meta_keywords'] = 'mapinfo pro, usaid rules and regulations training, communication for development training, records management training courses, tot training course online, africa training institute, stata course, stata online course, records management courses, stata courses, records management course, stata course online';
        $courseModel = new CourseModel();
        $data['trendings'] = $courseModel->join('durationtypes', 'courses.durationType=durationtypes.typeID')->orderBy('courseID', 'DESC')->limit(14)->findAll();

        $courseModel = new CourseModel();
        $data['recents'] = $courseModel->join('durationtypes', 'courses.durationType=durationtypes.typeID')->orderBy('courseID', 'DESC')->limit(14)->findAll();

        $scheduleModel = new ScheduleModel();
        $data['schedules'] = $scheduleModel->getUpcomingSchedules();
        echo view('templates/header', $data);
        echo view('templates/slider', $data);
        echo view('home');
        echo view('templates/footer');
    }

   public function ajaxSearch()
    {
        helper(['form', 'url']);
 
        $data = [];
 
        $db      = \Config\Database::connect();
        $builder = $db->table('courses');   
 
        $query = $builder->like('courseName', $this->request->getVar('q'))
                    ->select('courseID, courseName as text')
                    ->limit(10)->get();
        $data = $query->getResult();
         
        echo json_encode($data);
        
    }
    
    

    public function news() {
        $data['cats'] = $this->$cats;
        $newsModel = new NewsModel();
        $data['news'] = $newsModel->orderBy('newsID', 'DESC')->findAll();


        //echo view('templates/header',$data);
        //echo view('news');
        $session = \Config\Services::session();
        $userId = $session->get('userId');
        if ($userId) {
            echo view('templates/admin-header', $data);
            echo view('news', $data);
            echo view('templates/admin-footer');
        } else {
            echo view('templates/header', $data);
            echo view('news', $data);
            echo view('templates/footer');
        }

    }

    public function newItem($newsId) {

        $newsModel = new NewsModel();
        $data['news'] = $newsModel->where('newsID', $newsId)->first();

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


        $session = \Config\Services::session();
        $userId = $session->get('userId');
        if ($userId) {
            echo view('templates/admin-header', $data);
            echo view('newitem');
            echo view('templates/admin-footer');
        } else {
            echo view('templates/header', $data);
            echo view('newitem');
            echo view('templates/footer');
        }


    }


    public function addNews() {
        $title = $this->request->getVar('title');

        if ($title) {
            helper(['form', 'url']);


            $validated = $this->validate([
                'file' => [
                    'uploaded[image]',
                    'mime_in[image,image/jpg,image/jpeg,image/gif,image/png]',
                    'max_size[image,4096]',
                ],
            ]);

            $random = "";
            if ($validated) {
                $random = $this->randomString();
                $avatar = $this->request->getFile('image');
                $fileName = $avatar->getName();
                $nameArray = explode('.', $fileName);
                $ext = $nameArray[1];
                $random = $random . "." . $ext;
                $fileP = $avatar->move(WRITEPATH . 'uploads/');
                rename(WRITEPATH . "uploads/" . $fileName, WRITEPATH . "../public/images/news/" . $random);

                $msg = 'File has been uploaded';
            } else {
                $random = "default.jpg";
            }
            $data = [

                'title' => $this->request->getVar('title'),
                'body' => $this->request->getVar('introtext'),
                'meta_desc' => $this->request->getVar('meta_desc'),
				'meta_keywords' => $this->request->getVar('meta_keywords'),
                'img' => $random,
                'createdBy' => 1
            ];

            $newsModel = new NewsModel();
            $newsId = $newsModel->insert($data);

            $data['saved'] = 1;
            $data['success'] = $newsId;
        }

        $data['cats'] = $this->$cats;
        $data['addCourse'] = 1;
        echo view('templates/admin-header', $data);
        echo view('addnews');
        echo view('templates/admin-footer', $data);
    }

    public function editNews($newsId) {

        $newsModel = new NewsModel();
        $data['news'] = $newsModel->where('newsID', $newsId)->first();
//var_dump($data['news']);
        $data['cats'] = $this->$cats;
        $data['addCourse'] = 1;
        echo view('templates/admin-header', $data);
        echo view('updatenews');
        echo view('templates/admin-footer', $data);
    }

    public function updateNews() {

        helper(['form', 'url']);


        $validated = $this->validate([
            'file' => [
                'uploaded[image]',
                'mime_in[image,image/jpg,image/jpeg,image/gif,image/png]',
                'max_size[image,4096]',
            ],
        ]);

        $random = "";
        if ($validated) {
            $random = $this->randomString();
            $avatar = $this->request->getFile('image');
            $fileName = $avatar->getName();
            $nameArray = explode('.', $fileName);
            $ext = $nameArray[1];
            $random = $random . "." . $ext;
            $fileP = $avatar->move(WRITEPATH . 'uploads/');
            rename(WRITEPATH . "uploads/" . $fileName, WRITEPATH . "../public/images/news/" . $random);

            $msg = 'File has been uploaded';
        }
        $data = [

            'title' => $this->request->getVar('title'),
            'body' => $this->request->getVar('introtext'),
            'meta_desc' => $this->request->getVar('meta_desc'),
            'meta_keywords' => $this->request->getVar('meta_keywords'),
            'dateModified' => date('Y-m-d h:i:s a', time()),
            'modifiedBy' => 1
        ];
        if (strlen($random) > 0) {
            $data['img'] = $random;
        }
        $newsId = $this->request->getVar('newsid');

        $newsModel = new NewsModel();
        $res = $newsModel->updateNews($newsId, $data);

        $data['saved'] = 1;
        if ($res) {
            $data['success'] = 1;
        } else {
            $data['success'] = 0;
        }


        $newsModel = new NewsModel();
        $data['news'] = $newsModel->where('newsID', $newsId)->first();
//var_dump($data['news']);
        $data['cats'] = $this->$cats;
        $data['addCourse'] = 1;
        echo view('templates/admin-header', $data);
        echo view('updatenews');
        echo view('templates/admin-footer', $data);
    }


    public function adminPortal() {
        $data['cats'] = $this->$cats;
        $data['cats'] = $this->$cats;
        $courseModel = new CourseModel();
        //  $data['courses'] = $courseModel->orderBy('courseName', 'ASC')->find('courseID','courseName','duration','feeKshs','feeUsd');
        $data['courses'] = $courseModel->getCoursesList();

        $userModel = new UserModel();
        $data['trainers'] = $userModel->where(['userType' => 3, 'userID' > 0])->orderBy('firstName', 'ASC')->limit(4)->findAll();
        $data['students'] = $userModel->where(['userType' => 2, 'userID' > 0])->orderBy('firstName', 'ASC')->limit(4)->findAll();

        $newsModel = new NewsModel();
        $data['news'] = $newsModel->orderBy('newsID', 'DESC')->findAll();

        $session = \Config\Services::session();
        $userId = $session->get('userId');
        if ($userId) {
            echo view('templates/admin-header', $data);
            echo view('admin');
            echo view('templates/admin-footer');
        }
    }

    public function logout() {
        $session = \Config\Services::session();
        $sessionItems = ['name', 'email', 'userId', 'userType'];
        $session->remove($sessionItems);
        $session->destroy();

        return redirect()->to(base_url('admin'));
    }

    public function login() {
        $data['cats'] = $this->$cats;
        $email = $this->request->getVar('email');
        $pass = $this->request->getVar('pass');
        if ($email) {
            $passEncrypt = md5($pass);
            //get user from db
            $userModel = new UserModel();
            $user = $userModel->getUserLogin($email, $passEncrypt);

            if ($user == null) {

                $data['saved'] = 1;
                $data['success'] = 0;

                // echo view('templates/admin-header', $data);
                echo view('login', $data);
                echo view('templates/admin-footer');

            } else {
                //redirect to admin


                $login = [
                    'name' => $user->firstName,
                    'email' => $user->email,
                    'userId' => $user->userID,
                    'userType' => $user->userType
                ];

                $session = \Config\Services::session();
                $session->set($login);
                return redirect()->to(base_url('portal'));
                //$name = $session->get('name');


            }

        }

        //echo view('templates/admin-header',$data);
        echo view('login');
        echo view('templates/admin-footer');
    }


    public function addUser() {
        $data['cats'] = $this->$cats;
        echo view('templates/admin-header', $data);
        echo view('adduser');
        echo view('templates/admin-footer');
    }

    public function users() {
        $data['cats'] = $this->$cats;


        $userModel = new UserModel();
        $data['users'] = $userModel->whereIn('userType', [1, 4])->findAll();


        echo view('templates/admin-header', $data);
        echo view('users');
        echo view('templates/admin-footer');
    }

    public function addUserDetails() {


        $pass = $this->request->getVar('pass');
        $passCon = $this->request->getVar('passcon');
        if ($passCon == $pass) {

            //first check if emil already registered
            $userEmail = $this->request->getVar('email');
            $userModel = new UserModel();
            $user = $userModel->where('email', $userEmail)->first();

            if ($user == null) {
                //encrypty user Password
                $passEncrypt = md5($pass);
                //save user to db


                $data = [

                    'firstName' => $this->request->getVar('fname'),
                    'secondName' => $this->request->getVar('sname'),
                    'email' => $this->request->getVar('email'),
                    'password' => $passEncrypt,
                    'userType' => $this->request->getVar('usertype')
                ];
                $userModel = new UserModel();
                $userId = $userModel->insert($data);

                $data['saved'] = 1;
                $data['success'] = $userId;
                if ($userId == 0) {
                    $data['message'] = "Error while adding user to database.Try again!";

                }


            } else {
                $data['saved'] = 1;
                $data['success'] = 0;
                $data['message'] = "User email exists.Use a different email address";

            }


        } else {

            $data['saved'] = 1;
            $data['success'] = 0;
            $data['message'] = "Password Mismatch.Try again";

        }
        $data['cats'] = $this->$cats;


        echo view('templates/admin-header', $data);
        echo view('adduser', $data);
        echo view('templates/admin-footer');
    }

    public function updateUser($userId) {
        $data['cats'] = $this->$cats;

        $userModel = new UserModel();
        $data['user'] = $userModel->where('userID', $userId)->first();
        //var_dump($data['user']);

        echo view('templates/admin-header', $data);
        echo view('updateuser', $data);
        echo view('templates/admin-footer');
    }

    public function updateUserDetails() {

        $userId = $this->request->getVar('userid');

        $data = [

            'firstName' => $this->request->getVar('fname'),
            'secondName' => $this->request->getVar('sname'),
            'email' => $this->request->getVar('email'),

        ];

        $userType = $this->request->getVar('usertype');
        if ($userType) {
            $data ['userType'] = $this->request->getVar('usertype');
        } else {
            $data ['userType'] = 4;

        }

        $pass = $this->request->getVar('pass');
        $passCon = $this->request->getVar('passcon');

        if (strlen(trim($pass)) > 0 && $passCon == $pass) {

            $passEncrypt = md5($pass);
            $data['password'] = $passEncrypt;

        }

        $userModel = new UserModel();
        $res = $userModel->updateUser($userId, $data);
        if ($res) {
            $data['success'] = 1;
        } else {

            $data['success'] = 0;
        }
        $data['saved'] = 1;


        $userModel = new UserModel();
        $data['user'] = $userModel->where('userID', $userId)->first();
        //var_dump($data['user']);

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

        echo view('templates/admin-header', $data);
        echo view('updateuser', $data);
        echo view('templates/admin-footer');
    }


    public function addCourse() {
        $data['cats'] = $this->$cats;
        $facultyModel = new FacultyModel();
        $data['cats'] = $facultyModel->orderBy('facultyName', 'ASC')->findAll();
        $data['addCourse'] = 1;


        echo view('templates/admin-header', $data);
        echo view('addcourse', $data);
        echo view('templates/admin-footer', $data);

    }

    public function editCourse($courseId) {
        $data['cats'] = $this->$cats;
        $facultyModel = new FacultyModel();
        $data['cats'] = $facultyModel->orderBy('facultyName', 'ASC')->findAll();
        $data['addCourse'] = 1;

        $courseModel = new CourseModel();
        $data['course'] = $courseModel->getCourseDetails($courseId);
        $courseOutlineModel = new CourseOutlineModel();
        $data['contents'] = $courseOutlineModel->where('courseID', $courseId)->findAll();
        //var_dump($data['contents']);
        echo view('templates/admin-header', $data);
        echo view('updatecourse', $data);
        echo view('templates/admin-footer');

    }

    public function updateCourse() {

        helper(['form', 'url']);
        //$facultyModel=new FacultyModel();
        //$data['cats'] = $facultyModel->orderBy('facultyName', 'ASC')->findAll();

        $courseId = $this->request->getVar('courseid');
        $courseOutlineModel = new CourseOutlineModel();
        $contents = $courseOutlineModel->where('courseID', $courseId)->findAll();


        $courseModel = new CourseModel();

        $validated = $this->validate([
            'file' => [
                'uploaded[image]',
                'mime_in[image,image/jpg,image/jpeg,image/gif,image/png]',
                'max_size[image,4096]',
            ],
        ]);

        $random = "";
        if ($validated) {
            $random = $this->randomString();
            $avatar = $this->request->getFile('image');
            $fileName = $avatar->getName();
            $nameArray = explode('.', $fileName);
            $ext = $nameArray[1];
            $random = $random . "." . $ext;
            $fileP = $avatar->move(WRITEPATH . 'uploads/');
            rename(WRITEPATH . "uploads/" . $fileName, WRITEPATH . "../public/images/courses/" . $random);

            $msg = 'File has been uploaded';
        }
        $data = [

            'facultyID' => $this->request->getVar('category'),
            'courseName' => $this->request->getVar('coursename'),
            'introText' => $this->request->getVar('introtext'),
            'duration' => $this->request->getVar('duration'),
            'durationType' => $this->request->getVar('durationtype'),
            'targetAudience' => $this->request->getVar('targetgroup'),
            'methodology' => $this->request->getVar('methodology'),
            'courseObjectives' => $this->request->getVar('objectives'),
            'feeKshs' => $this->request->getVar('feekshs'),
            'feeUsd' => $this->request->getVar('feeusd'),
            'meta_desc' => $this->request->getVar('meta_desc'),
            'meta_keywords' => $this->request->getVar('meta_keywords'),
            'createdBy' => 1,
        ];
        if (strlen($random)) {
            $data['imgUrl'] = $random;

        }
        $courseId = $this->request->getVar('courseid');
        $courseModel = new CourseModel();
        $res = $courseModel->updateCourse($courseId, $data);

        //update or add course outlineItem

        $mod1 = $this->request->getVar('moduleone');
        $mod1items = $this->request->getVar('moduleoneitems');
        $mod2 = $this->request->getVar('moduletwo');
        $mod2items = $this->request->getVar('moduletwoitems');
        $mod3 = $this->request->getVar('modulethree');
        $mod3items = $this->request->getVar('modulethreeitems');
        $mod4 = $this->request->getVar('modulefour');
        $mod4items = $this->request->getVar('modulefouritems');

        if ($contents && $contents[0]) {
            //update the module contents
            $content = $contents[0];
            $contentId = $content['outlineID'];


            $data = [

                'courseID' => $courseId,
                'outlineItem' => $mod1,
                'outlineItems' => $mod1items,
                'dateModified' => date('Y-m-d h:i:s a', time()),
                'modifiedBy' => 1
            ];

            $courseOutlineModel = new CourseOutlineModel();
            $courseOutlineModel->updateOutline($contentId, $data);


        } else {
            //insert module 1 contents
            if (strlen($mod1) > 0) {
                $data = [

                    'courseID' => $courseId,
                    'outlineItem' => $mod1,
                    'outlineItems' => $mod1items,
                    'createdBy' => 1,
                ];
                $courseOutlineModel = new CourseOutlineModel();
                $courseItemID = $courseOutlineModel->insert($data);
            }
        }

        if ($contents && $contents[1]) {
            //update the module contents
            $content = $contents[1];
            $contentId = $content['outlineID'];


            $data = [

                'courseID' => $courseId,
                'outlineItem' => $mod2,
                'outlineItems' => $mod2items,
                'dateModified' => date('Y-m-d h:i:s a', time()),
                'modifiedBy' => 1
            ];

            $courseOutlineModel = new CourseOutlineModel();
            $courseOutlineModel->updateOutline($contentId, $data);


        } else {
            //insert module 1 contents
            if (strlen($mod2) > 0) {
                $data = [

                    'courseID' => $courseId,
                    'outlineItem' => $mod2,
                    'outlineItems' => $mod2items,
                    'createdBy' => 1,
                ];
                $courseOutlineModel = new CourseOutlineModel();
                $courseItemID = $courseOutlineModel->insert($data);
            }
        }
        if ($contents && $contents[2]) {
            //update the module contents
            $content = $contents[2];
            $contentId = $content['outlineID'];

            $data = [

                'courseID' => $courseId,
                'outlineItem' => $mod3,
                'outlineItems' => $mod3items,
                'dateModified' => date('Y-m-d h:i:s a', time()),
                'modifiedBy' => 1
            ];

            $courseOutlineModel = new CourseOutlineModel();
            $courseOutlineModel->updateOutline($contentId, $data);


        } else {
            //insert module 1 contents
            if (strlen($mod3) > 0) {
                $data = [

                    'courseID' => $courseId,
                    'outlineItem' => $mod3,
                    'outlineItems' => $mod3items,
                    'createdBy' => 1,
                ];
                $courseOutlineModel = new CourseOutlineModel();
                $courseItemID = $courseOutlineModel->insert($data);
            }
        }
        if ($contents && $contents[3]) {
            //update the module contents
            $content = $contents[3];
            $contentId = $content['outlineID'];

            $data = [

                'courseID' => $courseId,
                'outlineItem' => $mod4,
                'outlineItems' => $mod4items,
                'dateModified' => date('Y-m-d h:i:s a', time()),
                'modifiedBy' => 1
            ];

            $courseOutlineModel = new CourseOutlineModel();
            $courseOutlineModel->updateOutline($contentId, $data);


        } else {
            //insert module 1 contents
            if (strlen($mod4) > 0) {
                $data = [

                    'courseID' => $courseId,
                    'outlineItem' => $mod4,
                    'outlineItems' => $mod4items,
                    'createdBy' => 1,
                ];
                $courseOutlineModel = new CourseOutlineModel();
                $courseItemID = $courseOutlineModel->insert($data);

            }
        }

        $courseModel = new CourseModel();
        $data['course'] = $courseModel->getCourseDetails($courseId);
        $courseOutlineModel = new CourseOutlineModel();
        $data['contents'] = $courseOutlineModel->where('courseID', $courseId)->findAll();
        $data['addCourse'] = 1;

        $data['saved'] = 1;
        if ($res) {
            $data['success'] = 1;
        } else {
            $data['success'] = 0;
        }
        $data['cats'] = $this->$cats;
        echo view('templates/admin-header', $data);
        echo view('updatecourse', $data);
        echo view('templates/admin-footer');

    }

    public function storeCourse() {
        $data['cats'] = $this->$cats;
        helper(['form', 'url']);


        $courseModel = new CourseModel();

        $validated = $this->validate([
            'file' => [
                'uploaded[image]',
                'mime_in[image,image/jpg,image/jpeg,image/gif,image/png]',
                'max_size[image,4096]',
            ],
        ]);

        $random = "";
        if ($validated) {
            $random = $this->randomString();
            $avatar = $this->request->getFile('image');
            $fileName = $avatar->getName();
            $nameArray = explode('.', $fileName);
            $ext = $nameArray[1];
            $random = $random . "." . $ext;
            $fileP = $avatar->move(WRITEPATH . 'uploads/');
            rename(WRITEPATH . "uploads/" . $fileName, WRITEPATH . "../public/images/courses/" . $random);

            $msg = 'File has been uploaded';
        } else {
            $random = "default.jpg";
        }


        $data = [

            'facultyID' => $this->request->getVar('category'),
            'courseName' => $this->request->getVar('coursename'),
            'introText' => $this->request->getVar('introtext'),
            'duration' => $this->request->getVar('duration'),
            'durationType' => $this->request->getVar('durationtype'),
            'targetAudience' => $this->request->getVar('targetgroup'),
            'methodology' => $this->request->getVar('methodology'),
            'courseObjectives' => $this->request->getVar('objectives'),
            'feeKshs' => $this->request->getVar('feekshs'),
            'feeUsd' => $this->request->getVar('feeusd'),
            'meta_desc' => $this->request->getVar('meta_desc'),
            'meta_keywords' => $this->request->getVar('meta_keywords'),
            'imgUrl' => $random,
            'createdBy' => 1,
        ];


        $courseID = $courseModel->insert($data);
        $data['success'] = $courseID;
        if ($courseID > 0) {
            $mod1 = $this->request->getVar('moduleone');
            $mod1items = $this->request->getVar('moduleoneitems');
            $mod2 = $this->request->getVar('moduletwo');
            $mod2items = $this->request->getVar('moduletwoitems');
            $mod3 = $this->request->getVar('modulethree');
            $mod3items = $this->request->getVar('modulethreeitems');
            $mod4 = $this->request->getVar('modulefour');
            $mod4items = $this->request->getVar('modulefouritems');


            if (strlen($mod1) > 0) {
                $data = [

                    'courseID' => $courseID,
                    'outlineItem' => $mod1,
                    'outlineItems' => $mod1items,
                    'createdBy' => 1,
                ];
                $courseOutlineModel = new CourseOutlineModel();
                $courseItemID = $courseOutlineModel->insert($data);

            }
            if (strlen($mod2) > 0) {
                $data = [

                    'courseID' => $courseID,
                    'outlineItem' => $mod2,
                    'outlineItems' => $mod2items,
                    'createdBy' => 1,
                ];
                $courseOutlineModel = new CourseOutlineModel();
                $courseItemID = $courseOutlineModel->insert($data);

            }
            if (strlen($mod3) > 0) {
                $data = [

                    'courseID' => $courseID,
                    'outlineItem' => $mod3,
                    'outlineItems' => $mod3items,
                    'createdBy' => 1,
                ];
                $courseOutlineModel = new CourseOutlineModel();
                $courseItemID = $courseOutlineModel->insert($data);

            }
            if (strlen($mod4) > 0) {
                $data = [

                    'courseID' => $courseID,
                    'outlineItem' => $mod4,
                    'outlineItems' => $mod4items,
                    'createdBy' => 1,
                ];
                $courseOutlineModel = new CourseOutlineModel();
                $courseItemID = $courseOutlineModel->insert($data);

            }

        }


        $data['saved'] = 1;
        $data['success'] = $courseID;

        $facultyModel = new FacultyModel();
        $data['cats'] = $facultyModel->orderBy('facultyName', 'ASC')->findAll();
        $data['addCourse'] = 1;

        echo view('templates/admin-header', $data);
        echo view('addcourse', $data);
        echo view('templates/admin-footer');

    }


    public function addSchedule() {
        $data['cats'] = $this->$cats;
        $centerModel = new CenterModel();
        $data['centers'] = $centerModel->orderBy('centerName', 'ASC')->findAll();
        $userModel = new UserModel();
        $data['trainers'] = $userModel->where('userType', 3)->orderBy('firstName', 'ASC')->findAll();
        $courseModel = new CourseModel();
        $data['courses'] = $courseModel->orderBy('courseName', 'ASC')->findAll();

        echo view('templates/admin-header', $data);
        echo view('addschedule');
        echo view('templates/admin-footer');

    }

    public function storeSchedule() {

        helper(['form', 'url']);


        $scheduleModel = new ScheduleModel();

        $data = [

            'courseID' => $this->request->getVar('course'),
            'location' => $this->request->getVar('location'),
            'fees'      => $this->request->getVar('fees'),
            'centerID' => $this->request->getVar('center'),
            'trainerID' => $this->request->getVar('trainer'),
            'startDate' => $this->request->getVar('datefrom'),
            'endDate' => $this->request->getVar('dateto'),
            'createdBy' => 1,
        ];


        $save = $scheduleModel->insert($data);
        $data['success'] = $save;
        $data['saved'] = 1;
        $data['cats'] = $this->$cats;
        $centerModel = new CenterModel();
        $data['centers'] = $centerModel->orderBy('centerName', 'ASC')->findAll();
        $userModel = new UserModel();
        $data['trainers'] = $userModel->where('userType', 3)->orderBy('firstName', 'ASC')->findAll();
        $courseModel = new CourseModel();
        $data['courses'] = $courseModel->orderBy('courseName', 'ASC')->findAll();

        //return redirect()->to( base_url('/public/addschedule') );


        echo view('templates/admin-header', $data);
        echo view('addschedule', $data);
        echo view('templates/admin-footer');

    }

    public function updateSchedule($scheduleId) {
        $data['cats'] = $this->$cats;

        $scheduleModel = new ScheduleModel();
        $data['schedule'] = $scheduleModel->getScheduleDetails($scheduleId);

        $centerModel = new CenterModel();
        $data['centers'] = $centerModel->orderBy('centerName', 'ASC')->findAll();
        $userModel = new UserModel();
        $data['trainers'] = $userModel->where('userType', 3)->orderBy('firstName', 'ASC')->findAll();
        $courseModel = new CourseModel();
        $data['courses'] = $courseModel->orderBy('courseName', 'ASC')->findAll();


        echo view('templates/admin-header', $data);
        echo view('updateschedule');
        echo view('templates/admin-footer');

    }

    public function updateScheduleDetails() {

        //get the schdule id from the form
        $scheduleId = $this->request->getVar('scheduleid');
        $data = [

            'courseID' => $this->request->getVar('course'),
            'location' => $this->request->getVar('location'),
            'fees'      => $this->request->getVar('fees'),
            'centerID' => $this->request->getVar('center'),
            'trainerID' => $this->request->getVar('trainer'),
            'startDate' => $this->request->getVar('datefrom'),
            'endDate' => $this->request->getVar('dateto'),
            'modifiedAt' => date('Y-m-d h:i:s a', time()),
            'modifiedBy' => 1,
        ];

        $scheduleModel = new ScheduleModel();
        $res = $scheduleModel->updateSchedule($scheduleId, $data);
      

        $data['saved'] = 1;
        if ($res) {
            $data['success'] = 1;

        } else {
            $data['success'] = 0;

        }


        $centerModel = new CenterModel();
        $data['centers'] = $centerModel->orderBy('centerName', 'ASC')->findAll();
        $userModel = new UserModel();
        $data['trainers'] = $userModel->where('userType', 3)->orderBy('firstName', 'ASC')->findAll();
        $courseModel = new CourseModel();
        $data['courses'] = $courseModel->orderBy('courseName', 'ASC')->findAll();
        $data['cats'] = $this->$cats;
        $scheduleModel = new ScheduleModel();
        $data['schedule'] = $scheduleModel->getScheduleDetails($scheduleId);


        echo view('templates/admin-header', $data);
        echo view('updateschedule');
        echo view('templates/admin-footer');

    }


    public function viewSchedules() {

        $data['cats'] = $this->$cats;
        $courseModel = new CourseModel();
        $data['courses'] = $courseModel->orderBy('courseName', 'ASC')->findAll();

        $courseId = $this->request->getVar('course');
        if ($courseId) {
            $dateFrom = $this->request->getVar('datefrom');
            $dateTo = $this->request->getVar('dateto');
            $data['courseid'] = $courseId;
            $data['centerName'] = $centerName;
            $data['datefrom'] = $dateFrom;
            $data['dateto'] = $dateTo;
            $data['fetched'] = 1;

            //fetch schedules here
            $scheduleModel = new ScheduleModel();
            $data['schedules'] = $scheduleModel->getCourseSchedules($courseId, $dateFrom, $dateTo);
        }
        echo view('templates/admin-header', $data);
        echo view('schedules', $data);
        echo view('templates/admin-footer');
    }
    
     public function popdeleteschedule($scheduleId = null){
        
        $scheduleModel = new ScheduleModel();
        $res = $scheduleModel->where($scheduleId, $data)->delete('scheduleID');
        
        // $data['schedules'] = $model->where('scheduleID', $scheduleId)->delete('scheduleID');
        $data['success'];
        return redirect()->to( base_url('index.php/schedules') );
    }
    public function deleteschedule($scheduleId = null){
		$model = new ScheduleModel();
		$data['schedules'] = $model->where('scheduleId', $scheduleId)->delete();
		return redirect()->to( base_url('schedules') );
    }


    public function viewCourses() {
        $data['cats'] = $this->$cats;
        $courseModel = new CourseModel();
        //  $data['courses'] = $courseModel->orderBy('courseName', 'ASC')->find('courseID','courseName','duration','feeKshs','fees');
        $data['courses'] = $courseModel->getCoursesList();


        $session = \Config\Services::session();
        $userId = $session->get('userId');
        if ($userId) {
            echo view('templates/admin-header', $data);
            echo view('admin-courses', $data);
            echo view('templates/admin-footer');
        } else {
            echo view('templates/header', $data);
            echo view('courses', $data);
            echo view('templates/footer');
        }

    }

    public function viewCatCourses($catId) {
        $data['cats'] = $this->$cats;
        $data['meta_desc'] = $meta_desc;
        $data['meta_keywords'] = $meta_keywords;
        $facultyModel = new FacultyModel();
        $data['cat'] = $facultyModel->where('facultyID', $catId)->first();
        $courseModel = new CourseModel();
        $data['courses'] = $courseModel->getCategoryCourses($catId);
        //var_dump($data['courses']);

        // $model = new courseModel();
        // $data = [
        //       'courses' => $model->paginate(10),
        //       'pager' => $model->pager
        //     ];



        $session = \Config\Services::session();
        $userId = $session->get('userId');
        if ($userId) {
            echo view('templates/admin-header', $data);
            echo view('catcourses', $data);
            echo view('templates/admin-footer');
        } else {
            echo view('templates/header', $data);
            echo view('catcourses', $data);
            echo view('templates/footer');
        }


    }


    public function deletecourse($courseId = null){
        $model = new courseModel();
        $data['courses'] = $model->where('courseId', $courseId)->delete();
        return redirect()->to( base_url('index.php/allcourses') );
    }

     public function deletestudent($userId = null){
        $model = new userModel();

        // $data['student'] = $userModel->where('userID', $studentId)->first();
        $data['users'] = $model->where('userId', $userId)->delete();
        $data['success'];
        return redirect()->to( base_url('index.php/students') );
    }


    public function viewCourse($courseId) {
        $data['cats'] = $this->$cats;
        $courseModel = new CourseModel();
        $data['course'] = $courseModel->getCourseDetails($courseId);
        $courseOutlineModel = new CourseOutlineModel();
        $data['contents'] = $courseOutlineModel->where('courseID', $courseId)->findAll();
        //get date today
        $date = date('Y-m-d', time());
        $scheduleModel = new ScheduleModel();
        $data['schedules'] = $scheduleModel->where('courseID', $courseId)->where('startDate >=', "$date")->findAll();
        $model = new CourseModel();

        $data['courses'] = $model->getCourse();

        //var_dump($data['contents']);
        //echo view('templates/header',$data);
        //echo view('course',$data);
        $session = \Config\Services::session();
        $userId = $session->get('userId');
        if ($userId) {
            echo view('templates/admin-header', $data);
            echo view('course', $data);
            echo view('templates/admin-footer');
        } else {
            echo view('templates/header', $data);
            echo view('course', $data);
            echo view('templates/footer');
        }
    }

    public function CourseView($slug = null) {
        $model = new CourseModel();

        $data['courses'] = $model->getCourse($slug);
    }
    
    
    public function studentSearch()
    {
        helper(['form', 'url']);
 
        $data = [];
 
        $db      = \Config\Database::connect();
        $builder = $db->table('users');   
 
        $query = $builder->like('firstName', $this->request->getVar('q'))
                    ->select('userID, firstName, secondName as text')
                    ->limit(10)->get();
        $data = $query->getResult();
         
        echo json_encode($data);
    }

    public function viewStudents() {
        $data['cats'] = $this->$cats;
        $courseModel = new CourseModel();
        $data['courses'] = $courseModel->orderBy('courseName', 'DESC')->findAll();
        $data['recents'] = $courseModel->join('durationtypes', 'courses.durationType=durationtypes.typeID')->orderBy('courseID', 'DESC')->limit(4)->findAll();


        //$model = new TrainerModel();
        //$userModel= new UserModel();
        //$data['students'] = $userModel->where('userType', 3)->orderBy('firstName', 'ASC')->findAll();

        $courseId = $this->request->getVar('course');
        if ($courseId) {
            $dateFrom = $this->request->getVar('datefrom');
            $dateTo = $this->request->getVar('dateto');
            $status = $this->request->getVar('status');
            $data['courseid'] = $courseId;
            $data['datefrom'] = $dateFrom;
            $data['dateto'] = $dateTo;
            $data['status'] = $status;
            $data['fetched'] = 1;

            //fetch schedules here
            $appModel = new ApplicationModel();
            $data['students'] = $appModel->getSearchedStudents($courseId, $dateFrom, $dateTo, $status);
            //var_dump($data['students']);


        } else {

            $userModel = new UserModel();
           // $data['students'] = $userModel->where('userType', 2)->orderBy('userID', 'DESC')->findAll();
            $data['students'] = $userModel->join('courses', 'users.course_id = courses.courseID')->where('userType', 2)->orderBy('userID ASC')->findAll();
           


            // POSTING TO DB


            // ->orderBy('userID', 'DESC')->findAll();
            // $data['course']   = CourseModel->where('courseID', $course_id);

        }
        
        


        //var_dump($data['trainers']);
        echo view('templates/admin-header', $data);
        echo view('students', $data);
        echo view('templates/admin-footer');

    }

    public function viewTrainers() {
        $data['cats'] = $this->$cats;
        //$model = new TrainerModel();
        $userModel = new UserModel();
        $data['trainers'] = $userModel->where(['userType' => 3, 'userID' > 0])->orderBy('firstName', 'ASC')->findAll();


        //var_dump($data['trainers']);
        echo view('templates/admin-header', $data);
        echo view('trainers', $data);
        echo view('templates/admin-footer');

    }

    public function viewTrainer($trainerId) {
        $data['cats'] = $this->$cats;
        $userModel = new UserModel();
        $data['trainer'] = $userModel->where('userID', $trainerId)->first();
        //var_dump($data['trainer']);
        echo view('templates/admin-header', $data);
        echo view('trainer', $data);
        echo view('templates/admin-footer');

    }

    public function viewStudent($studentId) {
        $data['cats'] = $this->$cats;
        $userModel = new UserModel();
        // $data['student'] = $userModel->where('userID', $studentId)->first();

         $data['student'] = $userModel->join('courses', 'users.course_id = courses.courseID')->where('userID', $studentId)->orderBy('userID', 'DESC')->first();
        
         $UsersCourses = new UsersCourses();
         
          $data['courses'] = $UsersCourses->where('user_id', $studentId)->findAll();
          
        // var_dump($data['courses']);
        echo view('templates/admin-header', $data);
        echo view('student', $data);
        echo view('templates/admin-footer');

    }

    public function searchStudent() {
        $data['cats'] = $this->$cats;
        $userModel = new UserModel();
        $email = $this->request->getVar('email');
        if ($email) {
            $data['student'] = $userModel->where(['email' => $email, 'userType' => 2])->first();
            $data['email'] = $email;
            $data['fetched'] = 1;
        }
        //var_dump($data['trainer']);
        echo view('templates/admin-header', $data);
        echo view('searchstudent', $data);
        echo view('templates/admin-footer');

    }


    public function searchTrainer() {
        $data['cats'] = $this->$cats;
        $userModel = new UserModel();
        $email = $this->request->getVar('email');
        if ($email) {
            $data['trainer'] = $userModel->where(['email' => $email, 'userType' => 3])->first();
            $data['email'] = $email;
            $data['fetched'] = 1;
        }

        echo view('templates/admin-header', $data);
        echo view('searchtrainer', $data);
        echo view('templates/admin-footer');

    }

    public function registerTrainer() {
        $data['cats'] = $this->$cats;
        $fieldModel = new FieldModel();
        $data['fields'] = $fieldModel->findAll();

        echo view('templates/header', $data);
        echo view('registertrainer', $data);
        echo view('templates/footer');

    }

    public function applyTrainer() {


        helper(['form', 'url']);
        //$avatar = $this->request->getFile('file');
        //var_dump($avatar);

        $validated = $this->validate([
            'file' => [
                'uploaded[file]',
                'mime_in[application/pdf,application/x-pdf]',
                'max_size[file,4096]',
            ],
        ]);
        $validated = true;

        /*$validated = $this->validate([
        'file' => [
            'uploaded[image]',
            'mime_in[image,image/jpg,image/jpeg,image/gif,image/png]',
            'max_size[image,4096]',
        ],
    ]); */

        $random = "";
        if ($validated) {
            $random = $this->randomString();
            $avatar = $this->request->getFile('file');
            var_dump($avatar);
            $fileName = $avatar->getName();
            $nameArray = explode('.', $fileName);
            $ext = $nameArray[1];
            $random = $random . "." . $ext;
            $fileP = $avatar->move(WRITEPATH . 'uploads/');
            rename(WRITEPATH . "uploads/" . $fileName, WRITEPATH . "../public/images/cvs/" . $random);

            $msg = 'File has been uploaded';
        } else {
            echo 'Fongoe';
            $random = "default.txt";
        }


        $data = [

            'firstName' => $this->request->getVar('fname'),
            'secondName' => $this->request->getVar('sname'),
            'surName' => $this->request->getVar('tname'),
            'title' => $this->request->getVar('title'),
            'qualification' => $this->request->getVar('academiclevel'),
            'specialization' => $this->request->getVar('specialisation'),
            'yearsOfExperience' => $this->request->getVar('experience'),
            'phone' => $this->request->getVar('phone'),
            'email' => $this->request->getVar('email'),
            'cv' => $random,
            'userType' => $this->request->getVar('usertype'),
            'gender' => $this->request->getVar('gender'),
            'organisationName' => $this->request->getVar('organisation'),
            'nationality' => $this->request->getVar('nationality'),
            // 'accomodation' => $this->request->getVar('accomodation'),
            'accomodation' => $accom,
            'pickAirport' => $airport,
            'employerName' => $this->request->getVar('orgname'),
            'employerPhone' => $this->request->getVar('orgphone'),
            'employerEmail' => $this->request->getVar('orgemail'),
            'comment' => $this->request->getVar('comment'),
            'createdBy' => 0,
        ];


        $userEmail = $this->request->getVar('email');
        $userModel = new UserModel();
        $user = $userModel->where('email', $userEmail)->first();


        $userId = 0;
        if ($user == null) {
            //add user and get id

            $userModel = new UserModel();
            $userId = $userModel->insert($data);
            //echo $userId;

        } else {
            //update user details
            $userId = $user['userID'];
            $userModel = new UserModel();
            $save = $userModel->updateUser($userId, $data);

        }

        $data['saved'] = 1;
        $data['success'] = $userId;

        $fieldModel = new FieldModel();
        $data['fields'] = $fieldModel->findAll();
        $data['cats'] = $this->$cats;

        echo view('templates/header', $data);
        echo view('registertrainer', $data);
        echo view('templates/footer');

    }

    public function registerStudent($scheduleId) {
        $data['cats'] = $this->$cats;
        $scheduleModel = new ScheduleModel();
        $data['schedule'] = $scheduleModel->getScheduleDetails($scheduleId);
        $countryModel = new CountryModel();
        $data['countries'] = $countryModel->findAll();
        //  var_dump($schedule);
        echo view('templates/header', $data);
        echo view('registerstudent', $data);
        echo view('templates/footer');

    }

    public function onlineStudent($scheduleId){
              $data['cats']=$this->$cats;
        $scheduleModel = new ScheduleModel();
        $data['schedule']= $scheduleModel->getScheduleDetails($scheduleId);
        $countryModel=new CountryModel();
        $data['countries']=$countryModel->findAll();
      //  var_dump($schedule);
         echo view('templates/header',$data);
       echo view('onlinestudent',$data);
       echo view('templates/footer');

    }

    public function googleCaptachStore() {
 
      $model = new UserModel();
      $data = array('name' => $this->request->getVar('name'),
                    'email' => $this->request->getVar('email'), 
                    'contact_no' => $this->request->getVar('mobile_number'), 
                   );
       
      $recaptchaResponse = trim($this->request->getVar('g-recaptcha-response'));
       
      $userIp=$this->request->ip_address();
         
      $secret='ENTER_YOUR_SECRET_KEY';
       
      $credential = array(
            'secret' => $secret,
            'response' => $this->request->getVar('g-recaptcha-response')
        );
 
      $verify = curl_init();
      curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
      curl_setopt($verify, CURLOPT_POST, true);
      curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($credential));
      curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
      $response = curl_exec($verify);
 
      $status= json_decode($response, true);
       
      if($status['success']){ 
       $model->save($data);
       $session->setFlashdata('msg', 'Form has been successfully submitted');
      }else{
       $session->setFlashdata('msg', 'Something goes to wrong');
      }
         
      return redirect()->to('/');
    }
    
    public function registerStudentDetails() 
    {
    //  echo "<pre>"; print_r($_POST); echo "</pre>"; exit;
        $accom = $this->request->getVar('accomodation');
        $airport = $this->request->getVar('pickAirport');
        if ($accom == "on") {
            $accom = 'Yes';
        } else {
            $accom = 'No';
        }
        if ($airport == "on") {
            $airport = 'Yes';
        } else {
            $airport = 'No';
        }

        $data_stud = [
            'firstName' => $this->request->getVar('fname'),
            'secondName' => $this->request->getVar('sname'),
            'surName' => $this->request->getVar('tname'),
            'title' => $this->request->getVar('title'),
            'qualification' => $this->request->getVar('academiclevel'),
            'specialization' => $this->request->getVar('specialisation'),
            'yearsOfExperience' => $this->request->getVar('experience'),
            'phone' => $this->request->getVar('phone'),
            'email' => $this->request->getVar('email'),
            'userType' => $this->request->getVar('usertype'),
            // 'coursesName' => $this->request->getVar('coursesName'),
            'course_id'   => $this->request->getVar('course_id'),
            'classType'   => $this->request->getVar('classType'),
            'gender'      => $this->request->getVar('gender'),
            'organisationName' => $this->request->getVar('organisation'),
            'nationality' => $this->request->getVar('nationality'),
            'accomodation' => $accom,
            'pickAirport' => $airport,
            'employerName' => $this->request->getVar('orgname'),
            'employerPhone' => $this->request->getVar('orgphone'),
            'employerEmail' => $this->request->getVar('orgemail'),
            'comment' => $this->request->getVar('comment'),
            'date' => date('d/m/Y', time()),
            'createdBy' => 0,
        ];

        $recaptchaResponse = trim($this->request->getVar('g-recaptcha-response'));
       
    //   $userIp=$this->request->ip_address();
         
      $secret='6Lc0sJ4hAAAAAPqN2gHQ3FHILU0TiT_OyBH-qfYP';
       
      $credential = array(
            'secret' => $secret,
            'response' => $this->request->getVar('g-recaptcha-response')
        );
 
      $verify = curl_init();
      curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
      curl_setopt($verify, CURLOPT_POST, true);
      curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($credential));
      curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
      $response = curl_exec($verify);
 
      $status= json_decode($response, true);

        // exit;
        $userEmail = $this->request->getVar('email');
        $userModel = new UserModel();
        $user      = $userModel->where('email', $userEmail)->first();
        
        $scheduleModel = new ScheduleModel();
        $dataSchedule = $scheduleModel->getScheduleDetails($this->request->getVar('schedule'));
        
            
        $usrCourseObject = new UsersCourses();
        $usrCourseData   = array();
        $userId = 0;
        
        if ($user === null) 
        {
            //add user and get id
            //echo 'insert';
            //$userModel = new UserModel();
            $userModel->insert($data_stud);
            
            $lastID = $userModel->insertID();
      
            $usrCourseData = [
                'user_id'       => intVal($lastID),
                'courseName'    => $this->request->getVar('courseName'),
                'scheduleID'    => $dataSchedule->scheduleID,
                'course_id'     => $this->request->getVar('course_id'),
                'gender'        => $this->request->getVar('gender'),
                'startDate'     => $dataSchedule->startDate,
                'endDate'       => $dataSchedule->endDate,
                'dateModified'  => date('d/m/Y', time()),
            ];
            
            $usrCourseObject->insert($usrCourseData);
             //var_dump($this->request->getVar('courseName'));
           
            //echo $userId;

            // if($userId)
            // {
            //  $usrInfo = $userModel->where('userID', $userId);
            //  echo "<pre>"; print_r($usrInfo); echo "</pre>";exit;
            // }


        } else {
            //echo 'update'.$user['userID'];
           // $userId = $user['userID'];
           // $userObj = new UserModel();
           // $save = $userObj->updateUser($userId, $data_stud);
             //$usrCourseObject->insert($usr_course_data);

             $usrCourseInfo = [
                'user_id'       => $user['userID'],
                'courseName'    => $this->request->getVar('courseName'),
                'scheduleID'    => $dataSchedule->scheduleID,
                'course_id'     => $this->request->getVar('course_id'),
                'startDate'     => $dataSchedule->startDate,
                'endDate'       => $dataSchedule->endDate,
            ];

            $usrCourseObject->insert($usrCourseInfo);

        }
        // exit;

        //add to the schedule
        $appModel = new ApplicationModel();
        $dataSchd = [
            'scheduleID' => $this->request->getVar('schedule'),
            'courseID' => $this->request->getVar('course'),
            'studentID' => $userId
        ];
        $appSchId = $appModel->insert($dataSchd);
        //add  invoice here
        $invoiceId = 0;
        if ($appSchId > 0) {
            // $feeKsh = trim($this->request->getVar('feekshs'));
            $fees = trim($this->request->getVar('fees'));
            $courseId = $this->request->getVar('course');
            $noStudents = 1;
            // $totalKshs = $feeKsh * $noStudents;
            $totalUsd = $fes * $noStudents;

            $invoiceModel = new InvoiceModel();
            $dataInv = [
                'applicationID' => $appId,
                'courseID' => $courseId,
                'studentID' => $userId,
                'noOfStudents' => $noStudents,
                // 'feeKshs' => $feeKsh,
                'fees' => $fees,
                'totalFeeKshs' => $totalKshs,
                'totalfees' => $totalUsd,
                'createdBy' => 1,

            ];

            $invoiceId = $invoiceModel->insert($dataInv);

        }

        $name = $this->request->getVar('fname') . " " . $this->request->getVar('sname') . " " . $this->request->getVar('tname');

        //get schedule details
        $scheduleId = $this->request->getVar('schedule');
        $schduleModel = new ScheduleModel;
        $schedule = $schduleModel->getScheduleDetails($scheduleId);
        $startDate = explode('-', $schedule->startDate);
        $startDate = $startDate[2] . '/' . $startDate[1] . '/' . $startDate[0];

        $endDate = explode('-', $schedule->endDate);
        $endDate = $endDate[2] . '/' . $endDate[1] . '/' . $endDate[0];

        $dat['appId'] = $appId;
        $dat['invoiceId'] = $invoiceId;

        $profoInfo = array(
            'appId' => $appId,
            'invoiceId' => $invoiceId,
            'date' => date('d/m/Y', time()),
            'name' => $name,
            'courseName' => $schedule->courseName,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'duration' => $schedule->duration,
            'fees' => $schedule->fees,
            'feeKsh' => $schedule->feeKsh,
            'totalUsd' => $dataInv['totalUsd'],
            'durationIn' => $schedule->typeName,
            'email' => $data_stud['email'],
            'country' => $data_stud['nationality'],
            'org' => $data_stud['organisationName'],
            'studentID' => $data_stud['studentID'],
            'classType' => $data_stud['classType'],
            'totalUsd' => $dataInv['totalUsd'],
            'accomodation' => $accom,
            'airport' => $airport,
        );

       
        // exit;

        $fname = $this->request->getVar('fname');
        $sname = $this->request->getVar('sname');

        $fileName = "application" . $appId . "_" . $fname . "_" . $sname . "_" . $userId . ".pdf";
        $proforma = new Proforma();
        //$this->response->setHeader('Content-Type', 'application/pdf');
        $proforma->createProforma($profoInfo, $fileName);
        //send emailAddress

        $mail = array(
            'emailAddress' => $this->request->getVar('email'),
            'file' => "../public/images/apps/" . $fileName,
            'courseName' => $schedule->courseName,
            'name' => $name,
            'startDate' => $startDate,
            'endDate' => $endDate

        );

        $mailer = new Sender();
        $res = $mailer->sendEmail($mail);
        //var_dump($res);


        $data['cats'] = $this->$cats;
        echo view('templates/header', $data);
        echo view('success', $data);
        echo view('templates/footer');

    }



    /* Testing for Online Application Details*/


    public function onlineStudentDetails() {

        $accom = $this->request->getVar('accomodation');
        $airport = $this->request->getVar('pickAirport');
        if ($accom == "on") {
            $accom = 'Yes';
        } else {
            $accom = 'No';
        }
        if ($airport == "on") {
            $airport = 'Yes';
        } else {
            $airport = 'No';
        }

        $data_stud = [

            'firstName' => $this->request->getVar('fname'),
            'secondName' => $this->request->getVar('sname'),
            'surName' => $this->request->getVar('tname'),
            'title' => $this->request->getVar('title'),
            // 'coursesName' => $this->request->getVar('coursesName'),
            'course_id' => $this->request->getVar('course_id'),
            'classType' => $this->request->getVar('classType'),
            'qualification' => $this->request->getVar('academiclevel'),
            'specialization' => $this->request->getVar('specialisation'),
            'yearsOfExperience' => $this->request->getVar('experience'),
            'phone' => $this->request->getVar('phone'),
            'email' => $this->request->getVar('email'),
            'userType' => $this->request->getVar('usertype'),
            'classType' => $this->request->getVar('classType'),
            'gender' => $this->request->getVar('gender'),
            'organisationName' => $this->request->getVar('organisation'),
            'nationality' => $this->request->getVar('nationality'),
            'accomodation' => $accom,
            'pickAirport' => $airport,
            'employerName' => $this->request->getVar('orgname'),
            'employerPhone' => $this->request->getVar('orgphone'),
            'employerEmail' => $this->request->getVar('orgemail'),
            'comment' => $this->request->getVar('comment'),
            'createdBy' => 0,
        ];

        // exit;
        $userEmail = $this->request->getVar('email');
        $userModel = new UserModel();
        $user = $userModel->where('email', $userEmail)->first();
        
        $scheduleModel = new ScheduleModel();
        $dataSchedule = $scheduleModel->getScheduleDetails($this->request->getVar('schedule'));
        
        
        $course = new CourseModel;
        $csData = $course->getCourseDetails($this->request->getVar('course'));
        
        $usrCourseObject = new UsersCourses();
        $usrCourseData   = array();
          
        $userId = 0;
        if ($user === null) 
        {
            //add user and get id
            //echo 'insert';
            //$userModel = new UserModel();
            
            $userModel->insert($data_stud);
            
            $lastID = $userModel->insertID();

            $usrCourseData = [
                'user_id'       => intVal($lastID),
                'courseName'    => $csData->courseName,
                'scheduleID'    => $dataSchedule->scheduleID,
                'course_id'     => $this->request->getVar('course_id'),
                'startDate'     => $dataSchedule->startDate,
                'endDate'       => $dataSchedule->endDate,
                'gender'        =>$this->request->getVar('gender'),
                'dateModified'  => date('d/m/Y', time()),
            ];
            
            $usrCourseObject->insert($usrCourseData);
            

        } else {
            //echo 'update'.$user['userID'];
            /*$userId = $user['userID'];
            $userModel = new UserModel();
            $save = $userModel->updateUser($userId, $data_stud);

            if ($save) {
                var_dump($save);
            }
            */
            $usrCourseInfo = [
                'user_id'       => $user['userID'],
                'courseName'    => $csData->courseName,
                'scheduleID'    => $dataSchedule->scheduleID,
                'course_id'     => $this->request->getVar('course_id'),
                'startDate'     => $dataSchedule->startDate,
                'endDate'       => $dataSchedule->endDate,
            ];

            $usrCourseObject->insert($usrCourseInfo);
     
        }

        //add to the schedule
        $appModel = new ApplicationModel();
        $dataSchd = [
            'scheduleID' => $this->request->getVar('schedule'),
            'courseID' => $this->request->getVar('course'),
            'studentID' => $userId
        ];
        $appSchId = $appModel->insert($dataSchd);
        //add  invoice here
        $invoiceId = 0;
        if ($appSchId > 0) {
            // $feeKsh = trim($this->request->getVar('feekshs'));
            $fees = trim($this->request->getVar('fees'));
            $courseId = $this->request->getVar('course');
            $noStudents = 1;
            // $totalKshs = $feeKsh * $noStudents;
            // $totalUsd = $fees * $noStudents;
            $totalUsd = 1200;

            $invoiceModel = new InvoiceModel();
            $dataInv = [
                'applicationID' => $appId,
                'courseID' => $courseId,
                'studentID' => $userId,
                'noOfStudents' => $noStudents,
                // 'feeKshs' => $feeKsh,
                'fees' => $fees,
                'totalFeeKshs' => $totalKshs,
                'totalFeeUsd' => $totalUsd,
                'createdBy' => 1,

            ];

            $invoiceId = $invoiceModel->insert($dataInv);

        }

        $name = $this->request->getVar('fname') . " " . $this->request->getVar('sname') . " " . $this->request->getVar('tname');

        //get schedule details
        $scheduleId = $this->request->getVar('schedule');
        $schduleModel = new ScheduleModel;
        $schedule = $schduleModel->getScheduleDetails($scheduleId);
        $startDate = explode('-', $schedule->startDate);
        $startDate = $startDate[2] . '/' . $startDate[1] . '/' . $startDate[0];

        $endDate = explode('-', $schedule->endDate);
        $endDate = $endDate[2] . '/' . $endDate[1] . '/' . $endDate[0];

        $dat['appId'] = $appId;
        $dat['invoiceId'] = $invoiceId;

        $profoInfo = array(
            'appId' => $appId,
            'invoiceId' => $invoiceId,
            'date' => date('d/m/Y', time()),
            'name' => $name,
            'courseName' => $schedule->courseName,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'duration' => $schedule->duration,
            'fees' => $schedule->fees,
            'feeKsh' => $schedule->feeKsh,
            'totalUsd' => $dataInv['totalUsd'],
            'durationIn' => $schedule->typeName,
            'email' => $data_stud['email'],
            'country' => $data_stud['nationality'],
            'classType' => $data_stud['classType'],
            'org' => $data_stud['organisationName'],
            'studentID' => $data_stud['studentID'],
            'totalUsd' => $dataInv['totalUsd'],
            'accomodation' => $accom,
            'airport' => $airport,
        );

        // echo "<pre>"; print_r($data_stud['nationality']); echo "</pre>";

        // exit;

        $fname = $this->request->getVar('fname');
        $sname = $this->request->getVar('sname');

        $fileName = "application" . $appId . "_" . $fname . "_" . $sname . "_" . $userId . ".pdf";
        $proforma = new ProformaOnline();
        //$this->response->setHeader('Content-Type', 'application/pdf');
        $proforma->createProformaOnline($profoInfo, $fileName);
        //send emailAddress

        $mail = array(
            'emailAddress' => $this->request->getVar('email'),
            'file' => "../public/images/apps/" . $fileName,
            'courseName' => $schedule->courseName,
            'name' => $name,
            'startDate' => $startDate,
            'endDate' => $endDate

        );

        $mailer = new Sender();
        $res = $mailer->sendEmail($mail);
        //var_dump($res);


        $data['cats'] = $this->$cats;
        echo view('templates/header', $data);
        echo view('success', $data);
        echo view('templates/footer');

    }

    /*Testing for Online Application Ends Here*/

    public function viewApplicants() {
        $data['cats'] = $this->$cats;

        echo view('templates/header', $data);
        echo view('applicants');
        echo view('templates/footer');

    }

    function randomString($length = 12) {
        $key = '';
        $keys = array_merge(range('a', 'z'), range('A', 'Z'));
        for ($i = 0; $i < $length; $i++) {
            $key .= $keys[array_rand($keys)];
        }
        return $key;
    }


}
