<?php
namespace App\Controller;

use App\Utility\Common;
use Cake\I18n\I18n;
use Cake\Cache\Cache;
use Cake\I18n\FrozenTime;

/**
 * Courses Controller
 *
 * @property \App\Model\Table\CoursesTable $Courses
 * @property \App\Model\Table\StudentCoursesTable $StudentCourses
 * @property \App\Model\Table\CourseCategoriesTable $CourseCategories
 * @property \App\Model\Table\QualificationTypesTable $QualificationTypes
 * @property \App\Model\Table\CourseSemesterFeesTable $CourseSemesterFees
 * @property \App\Model\Table\CourseSemesterSubjectsTable $CourseSemesterSubjects
 */
class CourseController extends AppsController
{
    private  $controller = "course";
    public function initialize(): void
    {
        parent::initialize();
        $this->loadModel('Courses');
        $this->set('controller', $this->controller);
        $this->setPermissions();
    }

    public function index()
    {
        $page_limit = 10;
        if (isset($this->request->query['page_limit'])) {
            $page_limit = $this->request->query('page_limit');
        }

        $this->paginate = [
            'limit' => $page_limit,
            'order' => [
                'id' => 'asc'
            ]
        ];

        $search = '';
        if (isset($this->request->query['search'])) {
            $search = $this->request->query('search');
            $condition = '(name LIKE ' . "'%" . $search . "%' OR description LIKE '%" . $search . "%' " .')'   ;
        }

        $courses = $this->Courses->find('all')->where($condition) ;

        $this->set('courses', $this->paginate($courses));
        $this->set('searchText', $search);
        $nav_arr[0] = array('action' => 'add', 'page_id' => '10108', 'icon' => '<i class="fa fa-plus-circle"></i>', 'label' => 'Add');
        $this->set('nav_arr', $nav_arr);
        $this->set('page_limit', $page_limit);
    }

    public function add()
    {
        if ($this->request->is('post')) {
            $user_id = $this->Auth->user('id');
            $course = $this->Courses->newEntity();
            $course_request = $this->request->getData();
            $course_request['status'] = 1;
            $course_request['created_at'] = FrozenTime::now();
            $course_request['created_by'] = $user_id;
            $course_request['updated_at'] = FrozenTime::now();
            $course_request['updated_by'] = $user_id;
            $course = $this->Courses->patchEntity($course, $course_request);
            $errors = $course->errors();

            if (empty($errors)) {
                if ($this->Courses->save($course)) {
                    $course_request['course_id'] = $course->id;
                    $courseFee = $this->courseFee($course_request);
                    $this->courseSubject($course_request);
                    $this->Flash->success(__('The Courses has been saved.'));
                    return $this->redirect(['action' => 'index']);
                }
            }
            $this->set('errors', $errors);
            $this->Flash->error(__('Unable to add the Courses.'));
        }
        $this->setRelatedInfos();
        $this->setNextPage();
    }

    public function edit($id=null)
    {
        $this->loadModel('CourseSemesterFees');
        $this->loadModel('CourseSemesterSubjects');
        $course = $this->Courses->get($id, [
            'contain' => []
        ]);

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

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


        if ($this->request->is(['patch', 'post', 'put'])) {

            $user_id = $this->Auth->user('id');

            $course = $this->Courses->patchEntity($course, $this->request->data);
            $errors = $course->errors();
            $course['updated_at'] = FrozenTime::now();
            $course['updated_by'] = $user_id;
//            dd($this->request->data['course_semester_subjects']);
            if (empty($errors)) {
                if ($this->Courses->save($course)) {
                    $course_fee = $this->CourseSemesterFees->patchEntity($course_semester_fee, $this->request->data);
                    $errors = $course_fee->errors();
                    if(empty($errors)){
                        $this->CourseSemesterFees->save($course_fee);
                    }
                    foreach ($this->request->data['course_semester_subjects'] as $key => $value) {
                        $subject_request = [
                            'course_id' => $course->id,
                            'course_semester_id' => COURSE_SEMESTER_ID,
                            'title' => $value['title'],
                            'level' => $course->level,
                            'credit' => $value['credit'],
                            'is_mandatory' => !empty($value['is_mandatory']) ? $value['is_mandatory'] : 2,
                            'updated_by' => $user_id,
                            'updated_at' => FrozenTime::now()
                        ];
                        if (!empty($value['id'])) {
                            $subject = $this->CourseSemesterSubjects->get($value['id']);
                        }else{
                            $subject = $this->CourseSemesterSubjects->newEntity();
                            $subject_request['created_at'] = FrozenTime::now();
                            $subject_request['created_by'] = $user_id;
                        }

                        $subject = $this->CourseSemesterSubjects->patchEntity($subject, $subject_request);
                        $this->CourseSemesterSubjects->save($subject);
                    }
                    $this->Flash->success(__('The Course has been updated.'));
                    return $this->redirect(['action' => 'index']);
                } else {
                    $this->Flash->error(__('The Course could not be saved. Please, try again.'));
                }
            }
            $this->set('errors', $errors);
        }

        $this->setRelatedInfos();
        $this->set(compact('course_semester_fee','course_semester_subjects'));
        $this->set('course', $course);
        $this->set('_serialize', ['course']);
        $this->setNextPage();
    }

    public function view($id)
    {
        $this->loadModel('CourseSemesterFees');
        $this->loadModel('CourseSemesterSubjects');
        $course = $this->Courses->get($id, [
            'contain' => ['CourseCategories', 'QualificationTypes']
        ]);
        $course_semester_fee =  $this->CourseSemesterFees->find()
            ->where(['course_id' => $course->id])
            ->first();

        $course_semester_subjects = $this->CourseSemesterSubjects->find()
            ->where(['course_id' => $course->id])
            ->all();
        $this->set(compact('course_semester_fee','course_semester_subjects'));
        $this->set('course', $course);
        $this->set('_serialize', ['course']);

        $this->setNextPage();
    }

    public function delete($id=null)
    {
        $this->loadModel('StudentCourses');
        $courses = $this->Courses->get($id);

        $courseCourseCount = $this->StudentCourses->find()
            ->where(['course_id' => $id])
            ->count();

        if ($courseCourseCount > 0) {
            $this->Flash->error(__('Cannot delete Course because it has associated course Courses.'));
        } else {
            if ($this->Courses->delete($courses)) {
                $this->Flash->success(__('The Courses has been deleted.'));
            } else {
                $this->Flash->error(__('The Courses could not be deleted. Please try again.'));
            }
        }

        return $this->redirect(['action' => 'index']);
    }

    private function setNextPage(){
        $nav_arr[0] = array('action' => 'index', 'page_id' => '10105', 'icon' => '<i class="fa fa-list"></i>', 'label' => 'List');
        $this->set('nav_arr', $nav_arr);
    }

    private function setRelatedInfos(){
        $this->loadModel('CourseCategories');
        $this->loadModel('QualificationTypes');
        $course_categories = $this->CourseCategories->find('list', [
            'keyField' => 'id',
            'valueField' => 'name'
        ])->where(['status'=>1])->toArray();

        $qualification_types = $this->QualificationTypes->find('list', [
            'keyField' => 'id',
            'valueField' => 'name'
        ])->where(['status'=>1])->toArray();

        $this->set(compact('qualification_types','course_categories'));
    }

    private function courseFee($inputData){
        $this->loadModel('CourseSemesterFees');
        $course_semester_fee = $this->CourseSemesterFees->newEntity();
        $course_fee = [
            'course_id' => $inputData['course_id'],
            'online_fee' => $inputData['online_fee'],
            'discount' => $inputData['discount'],
            'monthly_installment_amount' => $inputData['monthly_installment_amount'],
            'upfront_deposit' => $inputData['upfront_deposit'],
            'blended_fee' => $inputData['blended_fee'],
            'certificate_fee' => $inputData['certificate_fee'],
            'status' => $inputData['status'],
            'created_by' => $inputData['created_by'],
            'updated_by' => $inputData['updated_by'],
            'created_at' => $inputData['created_at'],
            'updated_at' => $inputData['updated_at']
        ];
        $course_semester_fee = $this->CourseSemesterFees->patchEntity($course_semester_fee, $course_fee);
        $errors = $course_semester_fee->errors();
        if (empty($errors)) {
            return $this->CourseSemesterFees->save($course_semester_fee) ;
        }else{
            return $errors;
        }
    }
    private function courseSubject($inputData){
        $this->loadModel('CourseSemesterSubjects');
        $course_subjects = [];
        if(!empty($inputData['course_semester_subjects'])) {
            foreach ($inputData['course_semester_subjects'] as $key => $value) {
                $course_subject = [
                    'course_id' => $inputData['course_id'],
                    'course_semester_id' => COURSE_SEMESTER_ID,
                    'title' => $value['title'],
                    'level' => $inputData['level'],
                    'credit' => $value['credit'],
                    'is_mandatory' => !empty($value['is_mandatory']) ? $value['is_mandatory'] : 2,
                    'status' => $inputData['status'],
                    'created_by' => $inputData['created_by'],
                    'updated_by' => $inputData['updated_by'],
                    'created_at' => $inputData['created_at'],
                    'updated_at' => $inputData['updated_at']
                ];
                $course_subjects[] = $course_subject;
            }

            $entities = $this->CourseSemesterSubjects->patchEntities([], array_values($course_subjects));
            return $this->CourseSemesterSubjects->saveMany($entities);
        }
    }

}
