<?php

namespace App\Controller;


use App\Model\Entity\Log;
use Cake\I18n\FrozenTime;
use Cake\Database\Expression\QueryExpression;
use Cake\I18n\FrozenDate;


/**
 * Student Controller
 *
 * @property \App\Model\Table\FeedBacksTable $Feedbacks
 * @property \App\Model\Table\StudentsTable $Students
 * @property \App\Model\Table\StudentSessionsTable $StudentSessions
 * @property \App\Model\Table\StudentCoursesTable $StudentCourses
 * @property \App\Model\Table\CoursesTable $Courses
 * @property \App\Model\Table\SessionsTable $Sessions
 * @property \App\Model\Table\PersonalizesTable $Personalizes
 * @property \App\Model\Table\AgentsTable $Agents
 * @property \App\Model\Table\CourseSemesterFeesTable $CourseSemesterFees
 * @property \App\Model\Table\CourseSemesterSubjectsTable $CourseSemesterSubjects
 */
class LearninghubController extends AppController
{

    public function index()
    {
        $this->viewBuilder()->layout("customer_layout");
    }
    public function about()
    {
        $this->viewBuilder()->layout("customer_layout");
    }
    public function acreditation()
    {

        $this->viewBuilder()->layout("customer_layout");
    }
    public function accomodation()
    {

        $this->viewBuilder()->layout("customer_layout");
    }
    public function applicationProcess()
    {
        $this->viewBuilder()->layout("customer_layout");

    }
    public function applyForm()
    {

        $this->loadModel('Students');
        $this->loadModel('StudentSessions');
        $this->loadModel('StudentCourses');
        $this->loadModel('Courses');
        $this->loadModel('Sessions');
        $sessions = $this->Sessions->find('list', [
            'keyField' => 'id',
            'valueField' => 'name'
        ])->where(['status'=>1])->toArray();
        $courses = $this->Courses->find('list', [
            'keyField' => 'id',
            'valueField' => 'name'
        ])->where(['status'=>1])->toArray();

        if ($this->request->is('post')) {

            $student = $this->Students->newEntity();
            $student_request = $this->request->getData();
            $student_request['date_of_birth'] = $student_request["date_year"]."-".$student_request["date_month"]."-".$student_request["date_day"];
//            $student_request['reference_number'] = STUDENT_ID_PREFIX . time() . rand(0, 9999);
            $student = $this->Students->patchEntity($student, $student_request);
            $student['updated_at'] = FrozenTime::now();
            $student['created_at'] = FrozenTime::now();
            $student['current_checklist_id'] = 1;
            $errors = $student->errors();

            if (empty($errors)) {
                if ($this->Students->save($student)) {

                    $student_session = $this->StudentSessions->newEntity();
                    $student_session_request['student_id'] = $student['id'];
                    $student_session_request['session_id'] = $student_request['session_id'];
                    $student_session = $this->StudentSessions->patchEntity($student_session, $student_session_request);
                    $this->StudentSessions->save($student_session);

                    $student_course = $this->StudentCourses->newEntity();
                    $student_course_request['student_id'] = $student['id'];
                    $student_course_request['course_id'] = $student_request['course_id'];
                    $student_course_request['enrollment_date'] = FrozenTime::now();
                    $student_course = $this->StudentCourses->patchEntity($student_course, $student_course_request);
                    $this->StudentCourses->save($student_course);

                    $session = $sessions[$student_request['session_id']];
                    $course = $courses[$student_request['course_id']];
                    $this->registration_email($student,$session,$course);

                    $this->Flash->success(__('Registration Successful!'));
                }
            }else {
                $errorMessages = [];
                foreach ($errors as $field => $fieldErrors) {
                    foreach ($fieldErrors as $error) {
                        $errorMessages[] = ucfirst($field) . ': ' . $error;
                    }
                }
                $allErrors = implode(' ', $errorMessages);
                $this->log(['request'=> $this->request->getData(),'Student Registration failed'=> $errors]);
                $this->Flash->error(__($allErrors), ['escape' => false]);
            }
        }
        $this->set(compact('sessions','courses'));
        $this->viewBuilder()->layout("customer_layout");

    }
    public function courses()
    {
        $this->loadModel('Courses');
        $courses = $this->Courses->find('all')
                        ->contain(['CourseCategories', 'QualificationTypes'])
                        ->where(['Courses.status' => 1, 'Courses.course_category_id !=' => ENGLISH_COURSE_CATEGORY_ID]);
        $this->set(compact('courses'));
        $this->viewBuilder()->layout("customer_layout");

    }
    public function verification()
    {
        $message = '';
        $student = [];

        if ($this->request->is('post')) {

            $this->loadModel('Students');
            $this->loadModel('StudentSessions');
            $this->loadModel('StudentCourses');
            $this->loadModel('Courses');
            $this->loadModel('Sessions');
            $student_request = $this->request->getData();
            $dateOfBirth = FrozenDate::createFromFormat('d-m-Y', $student_request['date_of_birth']);
            $student = $this->Students->find()
                ->select(['id', 'reference_number', 'first_name', 'surname', 'nationality','passport_number','date_of_birth'])
                ->where(['status' => 1,'current_checklist_id'=>7, 'reference_number' => $student_request['reference_number'], 'date_of_birth' => $dateOfBirth ])
                ->first();

            $student_session = $this->StudentSessions->find()
                ->select(['id','session_id'])
                ->where(['student_id' => $student['id']])
                ->first();


            $student_course = $this->StudentCourses->find()
                ->select(['id','course_id'])
                ->where(['student_id' => $student['id']])
                ->first();

            $session = $this->Sessions->find()
                ->where(['id' => $student_session['session_id']])
                ->first();

            $course = $this->Courses->find()
                ->where(['id' => $student_course['course_id']])
                ->first();

            if(empty($student)){
                $message = "Sorry! You have not been enrolled ";
            }
            $this->set(compact('student','session','course','message'));
        }
        $this->viewBuilder()->layout("customer_layout");

    }
    public function contact()
    {
        if ($this->request->is('post')) {
            $this->loadModel('Feedbacks');
            $request = $this->request->getData();
            $feedback = $this->Feedbacks->newEntity();
            $feedback = $this->Feedbacks->patchEntity($feedback, $request);
            $errors = $feedback->errors();
            $feedback['created_at'] = FrozenTime::now();
            if (empty($errors)) {
                if ($this->Feedbacks->save($feedback)) {
                    $this->Flash->success(__('Thank you for contacting us!'));
                    return $this->redirect(['action' => 'contact']);
                }
            }
        }

        $this->viewBuilder()->layout("customer_layout");

    }
    private function registration_email($student,$session,$course){
        $this->loadModel('Personalizes');
        $personalize =  $this->Personalizes->find()->where(['member_id'=> DEFAULT_MEMBER_ID])->first();
        $template_content = array(
            'student_name' => $student['title'].' '.$student['first_name'],
            'student_email' => $student['email'],
            'phone_number' => $student['phone_number'],
//            'reference_number' => $student['reference_number'],
            'course_name' => $course,
            'registration_date' => $student['created_at']->i18nFormat('dd MMMM yyyy')
        );

       $this->sendEmail(MANDRILL_TEMPLATE_STUDENT_CONFIRMATION, $template_content, $student->email, 'Registration Confirmation', "", $personalize);
       $this->sendEmail(MANDRILL_TEMPLATE_STUDENT_CONFIRMATION_FOR_ADMIN, $template_content, ADMIN_EMAIL_LEARNING_HUB, 'Registration Confirmation', "", $personalize);
    }

    public function agent()
    {
        $this->loadModel('Agents');
        $agents = $this->Agents->find('all');
        $this->set(compact('agents'));
        $this->viewBuilder()->layout("customer_layout");
    }

    public function viewCourses($slug)
    {

            $slug = str_replace('-', ' ', $slug);

            $this->loadModel('Courses');
            $this->loadModel('CourseSemesterFees');
            $this->loadModel('CourseSemesterSubjects');
            $course = $this->Courses->find()
                ->where(function (QueryExpression $exp) use ($slug) {
                    return $exp->eq(
                        'LOWER(Courses.name)',
                        strtolower($slug)
                    );
                })
                ->andWhere(['Courses.status' => 1])
                ->contain(['CourseCategories', 'QualificationTypes'])
                ->first();
            $course_fee = $this->CourseSemesterFees->find()
                ->where(['course_id' => $course->id])
                ->first();

            $course_subjects = $this->CourseSemesterSubjects->find()
                ->where(['course_id' => $course->id])->all();

        $mandatoryCount =0 ;
        $optionalCount =0;
            if(!empty($course_subjects)) {
                $mandatoryCount = collection($course_subjects)
                    ->filter(function ($subject) {
                        return !empty($subject['is_mandatory']) && $subject['is_mandatory'] == 1;
                    })
                    ->count();
                $optionalCount = collection($course_subjects)
                    ->filter(function ($subject) {
                        return !empty($subject['is_mandatory']) && $subject['is_mandatory'] == 2;
                    })
                    ->count();
            }

            $this->set(compact('course', 'course_fee', 'course_subjects','mandatoryCount','optionalCount'));

            $this->viewBuilder()->layout("customer_layout");
    }

    public function viewEnglishCourses()
    {
        $this->viewBuilder()->layout("customer_layout");
    }





}
