<?php
namespace App\Controller;


use App\Utility\PdfWriter;
use Cake\I18n\FrozenTime;
use Cake\I18n\FrozenDate;
use Cake\ORM\TableRegistry;
use Cake\View\View;


/**
 * Student Controller
 *
 * @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\CheckListsTable $CheckLists
 * @property \App\Model\Table\RegistrationPaymentsTable $RegistrationPayments
 * @property \App\Model\Table\ReportFormatsTable $ReportFormats
 * @property \App\Model\Table\ReportFormatVariablesTable $ReportFormatVariables
 * @property \App\Model\Table\ReportFormatGenerationHistoriesTable $ReportFormatGenerationHistories
 * @property \App\Model\Table\ReportFormatVariableValuesTable $ReportFormatVariableValues
 * @property \App\Model\Table\StudentCheckListsTable $StudentCheckLists
 * @property \App\Model\Table\PassportDetailsTable $PassportDetails
 * @property \App\Model\Table\LetterSentHistoriesTable $LetterSentHistories
 * @property \App\Model\Table\LetterSentHistoryDetailsTable $LetterSentHistoryDetails
 * @property \App\Model\Table\CmsusersTable $Cmsusers
 * @property \App\Model\Table\AgentsTable $Agents
 */
class StudentController extends AppsController
{

    public function initialize(): void
    {
        parent::initialize();
        $this->loadModel('Students');
        $this->loadModel('StudentSessions');
        $this->loadModel('StudentCourses');
        $this->loadModel('Courses');
        $this->loadModel('Sessions');
        $this->loadModel('CheckLists');
        $this->loadModel('RegistrationPayments');
        $this->loadModel('ReportFormats');
        $this->loadModel('ReportFormatVariables');
        $this->loadModel('StudentCheckLists');
        $this->loadModel('PassportDetails');
        $this->loadModel('Agents');

    }

    public function index()
    {
        $agents = $this->Agents->find('list',[
            'keyField' => 'id',
            'valueField' => function ($agent) {
                return $agent->first_name . ' ' . $agent->last_name;
            }
        ])->where(['status'=>1])->toArray();
        $page_limit = 10;
        if (isset($this->request->query['page_limit'])) {
            $page_limit = $this->request->query('page_limit');
        }

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

        $search = '';

        if (isset($this->request->query['search'])) {
            $search = $this->request->query('search');
            $condition = '(Students.first_name LIKE ' . "'%" . $search . "%' OR Students.surname LIKE '%" . $search . "%' "
                . "OR Students.gender LIKE '%" . $search . "%' OR Students.title LIKE '%" . $search . "%' OR Students.email LIKE '%" . $search . "%' OR Students.reference_number like '%".$search."%'"
                ."OR Students.phone_number LIKE '%" . $search . "%'" . "OR Students.gender LIKE '%" . $search . "%'" .
                "OR Students.nationality LIKE '%" . $search . "%'" .')'   ;
        }
        if (isset($this->request->query['agent_id'])) {
            $agent_id = $this->request->query('agent_id');
            $condition .= " AND Students.referring_agent_id = " . (int)$agent_id;
        }

        $students = $this->Students->find('all')->where($condition);

        $user_permissions = $this->request->session()->read('user_permissions');
        $this->set('student_permission', $user_permissions);
        $this->set('bulk_actions', [BULK_ACTION_DELETE => "Move to trash"]);
        $this->set('students', $this->paginate($students));
        $this->set('agents', $agents);
        $this->set('searchText', $search);
        $this->set('current_module', $this->getModules());
        $this->set('page_list', $this->getPages());
        $this->set('module_pages', $this->getPages());
        $nav_arr[0] = array('action' => 'add', 'page_id' => '3046', 'icon' => '<i class="fa fa-plus-circle"></i>', 'label' => 'Add');
        $this->set('nav_arr', $nav_arr);
        $this->set('page_limit', $page_limit);
        $this->viewBuilder()->layout("custom_layout");
    }

    public function add()
    {
        $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();
        $user_id = $this->Auth->user('user_id');
        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']= $this->generateReferenceNumber($student_request['date_of_birth'],$student_request['session_id']);
            $student_request['reference_number'] = STUDENT_ID_PREFIX . time() . rand(0, 9999);
            $student = $this->Students->patchEntity($student, $student_request);
            $student['created_by'] = $user_id;
            $student['updated_by'] = $user_id;
            $student['updated_at'] = FrozenTime::now();
            $student['created_at'] = FrozenTime::now();
            $student['current_checklist_id'] = 1;
            $student['status'] = 1;
            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!'));
                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('Unable to registration.'));
        }
        $this->set(compact('sessions','courses'));
        $this->viewBuilder()->layout("custom_layout");

    }

    public function edit($id=null)
    {
        $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();
        $user_id = $this->Auth->user('id');
        $Student = $this->Students->get($id, [
            'contain' => []
        ]);
        $student_session = $this->StudentSessions->find()
            ->where(['student_id' => $id])
            ->first();
        $student_course = $this->StudentCourses->find()
            ->where(['student_id' => $id])
            ->first();

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

            $request = $this->request->data;

            $Student = $this->Students->patchEntity($Student, $request);

            $errors = $Student->errors();

            $Student['updated_at'] = FrozenTime::now();
            $Student['updated_by'] = $user_id;

            if (empty($errors)) {
                if ($this->Students->save($Student)) {
                    $this->Flash->success(__('The Student has been updated.'));
                    return $this->redirect(['action' => 'index']);
                } else {
                    $this->Flash->error(__('The Student could not be saved. Please, try again.'));
                }
            }
        }

        $user_permissions = $this->request->session()->read('user_permissions');
        $this->set('user_permission', $user_permissions);
        $this->set(compact('sessions','courses','student_session','student_course'));
        $this->set('Student', $Student);
        $this->set('_serialize', ['Student']);
        $this->set('current_module', $this->getModules());
        $nav_arr[0] = array('action' => 'index', 'page_id' => '3045', 'icon' => '<i class="fa fa-list"></i>', 'label' => 'List');
        $this->set('nav_arr', $nav_arr);
        $this->viewBuilder()->layout("custom_layout");
    }

    public function view($id=null)
    {
        $student = $this->Students->get($id, [
            'contain' => []
        ]);

        $student_session = $this->StudentSessions->find()
            ->where(['student_id' => $id])
            ->first();
        $student_course = $this->StudentCourses->find()
            ->where(['student_id' => $id])
            ->first();

        $sessions = $this->Sessions->find()
            ->where(['id' => $student_session['session_id']])
            ->first();
        $courses = $this->Courses->find()
            ->where(['id' => $student_course['course_id']])
            ->first();

        $this->set(compact('sessions','courses','student_session','student_course'));
        $this->set('student', $student);
        $this->set('_serialize', ['student']);

        $user_permissions = $this->request->session()->read('user_permissions');
        $this->set('languages', $this->languages);
        $this->set('module_pages', $this->getPages());
        $this->set('user_permission', $user_permissions);
        $this->viewBuilder()->layout("custom_layout");
    }

    public function verification()
    {
        $student = [];
        if ($this->request->is('post')) {
            $student_request = $this->request->getData();
            $student = $this->Students->find()
                ->select(['id', 'reference_number', 'first_name', 'surname', 'nationality'])
                ->where(['status' => 1, 'reference_number' => $student_request['reference_number'], 'passport_number' => $student_request['passport_number'] ])
                ->first();
            $this->set(compact('student'));
        }

        $this->viewBuilder()->layout('outside/layout');
    }

    public function registration($id=null)
    {
        $Student = $this->Students->get($id, [
            'contain' => ['RegistrationPayments','PassportDetails']
        ]);

        $check_lists = $this->CheckLists->find('all')->where(['status'=>1]);

        $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();

        $agents = $this->Agents->find('list',[
            'keyField' => 'id',
            'valueField' => function ($agent) {
                return $agent->first_name . ' ' . $agent->last_name;
            }
        ])->where(['status'=>1])->toArray();

        $student_session = $this->StudentSessions->find()
            ->contain(['Sessions'])
            ->where(['student_id' => $id])
            ->first();
        $Student['session'] = $student_session;

        $student_course = $this->StudentCourses->find()
            ->contain(['Courses'])
            ->where(['student_id' => $id])
            ->first();
        $Student['course'] = $student_course;

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

        if($student_course['course_id'] == 2) {
            $report_format =  $this->ReportFormats->find()->where(['report_format_type_id' => 5])->first();
            $visa_report_format =  $this->ReportFormats->find()->where(['report_format_type_id' => 6])->first();
        }else{
            $report_format =  $this->ReportFormats->find()->where(['report_format_type_id' => 1])->first();
            $visa_report_format =  $this->ReportFormats->find()->where(['report_format_type_id' => 2])->first();
        }

        $offer_variable_list =  $this->reportGenerate($report_format['id'],$report_format['content'],$Student);

        $report_replaced_data = $this->reportHTMLReplace($report_format['content'],$offer_variable_list);

        $visa_variable_list =  $this->reportGenerate($visa_report_format['id'],$visa_report_format['content'],$Student);

        $visa_report_replaced_data = $this->reportHTMLReplace($visa_report_format['content'],$visa_variable_list);

        if ($this->request->is(['patch', 'post', 'put'])) {
            $request = $this->request->data;
            $key = array_search($request['step'], FORM_SEQUENCE);

            if (empty($request['last_join_date']) || !empty($Student['last_join_date']) ) {
                $request['last_join_date'] = $Student['last_join_date']; ;
            } else {
                $request['last_join_date'] = new FrozenTime($request['last_join_date']); // or default value if needed
            }
            $Student = $this->Students->patchEntity($Student, $request);
            $errors = $Student->errors();

            if($request['step'] == (FORM_SEQUENCE)[1] && empty($Student['reference_number'])) {
                $random = mt_rand(100, 999);
                $idPadded = str_pad($Student->id, 3, '0', STR_PAD_LEFT);
                $Student['reference_number'] = STUDENT_ID_PREFIX . $random . $idPadded;
            }

            if ( $key == $Student['current_checklist_id'] && $key < count(FORM_SEQUENCE)) {
                $Student['current_checklist_id'] = $Student['current_checklist_id'] + 1;
            }
            $Student['updated_at'] = FrozenTime::now();
            $Student['updated_by'] = $user_id;

            if (empty($errors)) {
                if ($this->Students->save($Student)) {
                    $this->Flash->success(__('The Student has been updated.'));
                } else {
                    $this->Flash->error(__('The Student could not be saved. Please, try again.'));
                }
            }


            if($request['step'] == (FORM_SEQUENCE)[4]) {
                $registration_payment = $this->RegistrationPayments->find()->where(['student_id' => $Student['id']])->first();
                $registration_payment_request = [
                    'student_id' => $Student['id'],
                    'letter_type' => $request['letter_type'],
                    'registration_fee' => $request['registration_fee'],
                    'tuition_fees' => $request['tuition_fees'],
                    'total_fees' => $request['total_fees'],
                    'total_fees_paid' => $request['total_fees_paid'],
                    'outstanding_fees' => $request['outstanding_fees'],
                    'bank_details' => $request['bank_details'],
                    'iban' => $request['iban'],
                    'account_no' => $request['account_no'],
                    'updated_by_id' => $user_id,
                    'updated_at' => FrozenTime::now()
                ];
                if ($registration_payment) {
                    $registration_payment = $this->RegistrationPayments->patchEntity($registration_payment, $registration_payment_request);
                } else {
                    $registration_payment_request['created_by_id'] = $user_id;
                    $registration_payment_request['created_at'] = FrozenTime::now();
                    $registration_payment = $this->RegistrationPayments->newEntity();
                    $registration_payment = $this->RegistrationPayments->patchEntity($registration_payment, $registration_payment_request);
                }
                $errors = $registration_payment->errors();

                if (empty($errors)) {
                    if ($this->RegistrationPayments->save($registration_payment)) {
                        $this->user_add($Student);
                        $this->Flash->success(__('The Registration Payment has been updated.'));
                        return $this->redirect(array('action' => 'registration/'.$id));

                    } else {
                        $this->Flash->error(__('The Registration Payment could not be saved. Please, try again.'));
                    }

                }
            }

            if($request['step'] == (FORM_SEQUENCE)[5]) {
                $offer_report_value = $this->placedReportVariable($report_format['content'],$request['content']);
                $report_replaced_data = str_replace(['<em>', '</em>','<p>&nbsp;</p>'], '', $request['content']);
                $report_replaced_data = str_replace(['[', ']'], '', $report_replaced_data);
//                $report_replaced_data = $this->offerLetterTemplate($report_replaced_data);
                $filename = uniqid('offer_letter_', true).'.pdf';
                $folder =  'reports' . DS. $Student['id'] ;
                $file_path =  $this->reportSaveInStorage($folder, $filename, $report_replaced_data);
                $this->letterSentHistory($report_format['id'],$report_format['report_format_type_id'],$Student,$folder.DS.$filename,$offer_report_value,$user_id);
//                $this->reportGenerationHistory($report_format['id'], $Student['first_name'].' '.$Student['surname'],$Student['email'],$folder.DS.$filename,$user_id);
                $template_content = array(
                    'student_name' => $Student['first_name'].' '.$Student['surname'],
                    'course'=> $Student->course->course['name'],
                    'letter_type'=> 'Conditional Offer'
                );
                $this->sendEmail('send_email_to_client', $template_content, $Student['email'], 'Conditional Offer Letter', ["Offer_Letter.pdf"=>$file_path], null);
            }

            if($request['step'] == (FORM_SEQUENCE)[6]) {
                $passport_details = $this->PassportDetails->find()->where(['student_id' => $Student['id']])->first();

                $passport_details_request = [
                    'student_id' => $Student['id'],
                    'passport_no' => $Student['passport_number'],
                    'verification_link' => $request['verification_link'],
                    'verification_code_img_path' => $request['verification_code_img_path'],
                    'visa_type' => $request['visa_type'],
                    'living_costs' => $request['living_costs'],
                    'duration' => $request['duration'],
                    'total_fees' => ($request['living_costs']*$request['duration']),
                    'updated_by_id' => $user_id,
                    'updated_at' => FrozenTime::now()
                ];
                if ($passport_details) {
                    $passport_details = $this->PassportDetails->patchEntity($passport_details, $passport_details_request);
                } else {
                    $passport_details_request['created_by_id'] = $user_id;
                    $passport_details_request['created_at'] = FrozenTime::now();
                    $passport_details = $this->PassportDetails->newEntity();
                    $passport_details = $this->PassportDetails->patchEntity($passport_details, $passport_details_request);
                }
                $errors = $passport_details->errors();
                if (empty($errors)) {
                    if ($this->PassportDetails->save($passport_details)) {
                        $this->Flash->success(__('The Passport Details has been updated.'));
                        return $this->redirect(array('action' => 'registration/'.$id));

                    } else {
                        $this->Flash->error(__('The Passport Details could not be saved. Please, try again.'));
                    }
                }
            }

            if($request['step'] == (FORM_SEQUENCE)[7]) {
                $visa_report_value = $this->placedReportVariable($visa_report_format['content'],$request['visa_content']);
                $report_replaced_data = str_replace(['<em>', '</em>','<p>&nbsp;</p>'], '', $request['visa_content']);
                $report_replaced_data = str_replace(['[', ']'], '', $report_replaced_data);
                $filename = uniqid('visa_letter_', true).'.pdf';
                $folder =  'reports' . DS. $Student['id'] ;
//                $report_replaced_data = $this->visaLetterTemplate($report_replaced_data);
                $file_path =  $this->reportSaveInStorage($folder, $filename, $report_replaced_data);
                $this->letterSentHistory($visa_report_format['id'],$visa_report_format['report_format_type_id'],$Student,$folder.DS.$filename,$visa_report_value,$user_id);
//                $this->reportGenerationHistory($visa_report_format['id'], $Student['first_name'].' '.$Student['surname'],$Student['email'],$folder.DS.$filename,$user_id);
                $template_content = array(
                    'student_name' => $Student['first_name'].' '.$Student['surname'],
                    'course'=> $Student->course->course['name'],
                    'letter_type'=> 'Visa '
                );
               $this->sendEmail('send_email_to_client', $template_content, $Student['email'], 'Visa Letter', ["Visa_Letter.pdf"=>$file_path], null);
            }
        }

        $this->set(compact('agents','check_lists','Student','user_id','sessions','courses','student_session','student_course','report_format','report_replaced_data','visa_report_replaced_data'));

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

    private function user_add($Student)
    {
        $this->loadModel('Cmsusers');
        $this->loadModel('cmsuser_usergroups');
        $cmsuser = $this->Cmsusers->find()->where(['crm_contact_user_id' => $Student['id']])->first();
        if(empty($cmsuser)) {
            $cmsuser = $this->Cmsusers->newEntity();
            $cmsuser->crm_contact_user_id = $Student['id'];
            $cmsuser->user_type = USER_TYPE['STUDENT'];
            $cmsuser->username = $Student['email'];
            $cmsuser->password = DEFAULT_USER_PASSWORD;
            $cmsuser->email = $Student['email'];
            $cmsuser->created_on = FrozenTime::now();
            $cmsuser->updated_on = FrozenTime::now();
            $cmsuser->reset_password_token = '';
            $cmsuser->status = STATUS_ACTIVE;
            $cmsuser->language = 'en';
            $cmsuser->last_active_date = FrozenTime::now();
            $cmsuser->company_id = $this->Auth->user('company_id');
            $cmsuser->updated_at = FrozenTime::now();

            $isUnique = $this->checkUniqueEmail($cmsuser->email);
            if ($isUnique) {
                $cmsuser = $this->Cmsusers->save($cmsuser);
                if ($cmsuser) {
                    $this->addUserToUserGroup($cmsuser->id,DEFAULT_STUDENT_USER_GROUP);
                }
                $this->sendUserInfo($Student, DEFAULT_USER_PASSWORD);

            }
        }

    }

    private function addUserToUserGroup($user_id, $usergroup_id)
    {
        $table_user_groups_user = TableRegistry::get("CmsuserUsergroups");
        $entity = $table_user_groups_user->newEntity();
        $entity->cms_user_id = $user_id;
        $entity->usergroup_id = $usergroup_id;
        $table_user_groups_user->save($entity);
    }

    private function checkUniqueEmail($email)
    {
        $result = true;

        $this->loadModel('Cmsusers');
        $cmsuser = $this->Cmsusers->find()->where(['email' => $email])->first();

        if (!empty($cmsuser)) {
            return false;
        }
        return $result;

    }
    public function enrollstudent($id = null)
    {

        $user_id = $this->Auth->user('id');
        if ($this->request->allowMethod(['post', 'delete'])) {

            $Student = $this->Students->get($id, [
                'contain' => []
            ]);
            $Student['status'] = 1;
            $Student['updated_at'] = FrozenTime::now();
            $Student['updated_by'] = $user_id;

            if ($this->Students->save($Student)) {
                $this->Flash->success(__('The Student has been enrolled successfully.'));
                return $this->redirect(['action' => 'index']);
            }
            else {
                $this->Flash->error(__('The Student could not be enrolled. Please, try again.'));
            }

        }

    }

    private function sendUserInfo($student,$password){

        $template_content = array(
            'student_name' => $student['title'].' '.$student['first_name'],
            'student_email' => $student['email'],
            'user_name' => $student['email'],
            'password' => $password
        );
        $this->sendEmail('user_info_for_student', $template_content, $student->email, 'Portal Information', "",null);

    }

    public function reportHTMLReplace($content, $variableList) {

        if (!empty($variableList)) {
            foreach ($variableList as $key => $value) {
                $content = str_replace("[$key]", "[$value]", $content);
            }
        }
        return $content;
    }

    public function findVariableFromHtmlContent($html_content)
    {
        preg_match_all('/\[(.*?)\]/', $html_content, $matches);

        return $matches[1];

    }

    public function getVariableValue($base_content, $variable_values){
        $data = [];
        foreach ($base_content as $key => $value) {
            $data[$value] = $variable_values[$key] ;
        }
        return $data;
    }
    public function reportFormatVariableUpdate($report_values,$report_format_id,$receiver_email){
        $this->loadModel('ReportFormatVariableValues');
        $this->loadModel('ReportFormatVariables');
        $this->loadModel('ReportFormatGenerationHistories');

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

        $report_format_generation_history = $this->ReportFormatGenerationHistories->find()->where(['report_format_id' => $report_format_id,'receiver_emails' => $receiver_email])->first();

        $report_format_generation_history_request = [
            'name' => "Offer Letter",
            'report_format_id' => $report_format_id,
            'status' => 1,
            'updated_by_id' => $user_id,
            'updated_at' => FrozenTime::now()
        ];

        if (empty($report_format_generation_history)) {
            $report_format_generation_history_request['receiver_emails'] = $receiver_email;
            $report_format_generation_history_request['created_by_id'] = $user_id;
            $report_format_generation_history_request['created_at'] = FrozenTime::now();
            $report_format_generation_history = $this->ReportFormatGenerationHistories->newEntity();
            $report_format_generation_history = $this->ReportFormatGenerationHistories->patchEntity($report_format_generation_history, $report_format_generation_history_request);
            $this->ReportFormatGenerationHistories->save($report_format_generation_history);

        }

        foreach ($report_values as $key => $value) {
            if(!in_array($key,AVOID_FROM_REPORT)) {
                $report_format_variable = $this->ReportFormatVariables->find()->where(['report_format_id' => $report_format_id, 'variable_name' => $key])->first();
                $report_format_variable_value = $this->ReportFormatVariableValues->find()->where(['report_format_variable_id' => $report_format_variable['id']])->first();
                $ReportFormatVariableValueRequest = [
                    'report_format_id' => $report_format_id,
                    'value' => $value,
                    'report_format_variable_id' => $report_format_variable['id'],
                    'report_format_generation_history_id' => $report_format_generation_history['id'],
                    'status' => 1,
                    'updated_by_id' => $user_id,
                    'updated_at' => FrozenTime::now()
                ];
                if (empty($report_format_variable_value)) {
                    $ReportFormatVariableValueRequest['created_by_id'] = $user_id;
                    $ReportFormatVariableValueRequest['created_at'] = FrozenTime::now();
                    $report_format_variable_value = $this->ReportFormatVariableValues->newEntity();
                    $report_format_variable_value = $this->ReportFormatVariableValues->patchEntity($report_format_variable_value, $ReportFormatVariableValueRequest);
                }
                $report_format_variable_value = $this->ReportFormatVariableValues->patchEntity($report_format_variable_value, $ReportFormatVariableValueRequest);
                $this->ReportFormatVariableValues->save($report_format_variable_value);
            }
        }


    }

    public function reportSaveInStorage($folder,$filename,$content)
    {
        $folder =  WWW_ROOT .$folder;
        if (!is_dir($folder)) {
            mkdir($folder, 0775, true);
        }
        $path = $folder . DS . $filename;

        if (file_exists($path)) {
            unlink($path);
        }

        $this->mpdfWrite($content, $folder,$filename);

        return $path;
    }
    public function reportGetFromStorage($student_id,$report_format_id)
    {
        $content = null;
        $filename = $report_format_id.'.doc';

        $folder = WWW_ROOT . 'reports' . DS. $student_id ;
        $filePath = $folder . DS . $filename;
        if (file_exists($filePath)) {
            $content = file_get_contents($filePath);
        }

        return $content;
    }

    public function reportGenerate($report_format_id,$base_content,$student)
    {
        $report_variables = $this->findVariableFromHtmlContent($base_content);

        $report_format_variable =  $this->ReportFormatVariables->find()
            ->select(['variable_name', 'column_name', 'table_name'])
            ->where(['report_format_id' => $report_format_id])->toArray();

        $report_format_variable_value = [];

        foreach ($report_format_variable as $variable) {
            if ($variable->table_name === 'Students') {
                $column_value = $student->get($variable->column_name);
                if($variable->column_name == 'date_of_birth'){
                    $column_value = $column_value->format('d-m-Y');
                }
                if($variable->column_name == 'last_join_date'){
                    if(!empty($column_value) ) {
                        $column_value = $column_value->format('jS F Y');
                    }
                }
                if($variable->column_name == 'mod_of_study'){
                    $column_value = STUDY_MOD[$column_value];
                }
                if($variable->column_name == 'first_name'){
                    $column_value = $column_value.' '.$student->get('surname');
                }
                $report_format_variable_value[$variable->variable_name] = $column_value;
            }
            if ($variable->table_name === 'Sessions') {
                $column_value = $student->session->session->get($variable->column_name);
                if($variable->column_name == 'start_date' || $variable->column_name == 'end_date'){
                    $column_value = $column_value->format('jS F Y');

                }
                $report_format_variable_value[$variable->variable_name] = $column_value;
            }
            if ($variable->table_name === 'Courses') {
                $column_value = $student->course->course->get($variable->column_name);
                if($variable->column_name == 'course_category_id'){
                    $column_value = $this->setCourseCategory($column_value);
                }
                $report_format_variable_value[$variable->variable_name] = $column_value;

            }
            if ($variable->table_name === 'RegistrationPayments' && !empty($student->registration_payment)) {
                $column_value = $student->registration_payment->get($variable->column_name);
                if($variable->column_name == 'letter_type'){
                    $column_value = OFFER_LETTER_TYPE[$column_value];
                }
                if(in_array($variable->column_name,DECIMAL_COLUMN)){
                    $column_value = number_format($column_value, 2);
                }
                $report_format_variable_value[$variable->variable_name] = $column_value;
            }
            if ($variable->table_name === 'PassportDetails' && !empty($student->passport_detail)) {
                $column_value = $student->passport_detail->get($variable->column_name);
                if(in_array($variable->column_name,DECIMAL_COLUMN)){
                    $column_value = number_format($column_value, 2);
                }
                $report_format_variable_value[$variable->variable_name] = $column_value;
            }
        }

        $variable_list = [];

        foreach ($report_variables as $key => $value) {

            if(array_key_exists($value,$report_format_variable_value)) {
                $variable_list[$value] = $report_format_variable_value[$value];

            }
            if(array_key_exists($value,FIXED_REPORT_VARIABLE)) {
                $variable_list[$value] = FIXED_REPORT_VARIABLE[$value];
            }

        }

        return $variable_list;

    }

    public function placedReportVariable($base_content,$dynamic_content)
    {
        $report_variables = $this->findVariableFromHtmlContent($base_content);
        $report_value_variables = $this->findVariableFromHtmlContent($dynamic_content);

        $variable_list = [];

        foreach ($report_variables as $key => $value) {

            if(array_key_exists($key,$report_value_variables)) {
                $variable_list[$value] = $report_value_variables[$key];

            }
            if(array_key_exists($key,FIXED_REPORT_VARIABLE)) {
                $variable_list[$value] = FIXED_REPORT_VARIABLE[$value];
            }

        }
        return $variable_list;
    }

    public function mpdfWrite($html,$file_path,$file_name,$extra = []){
        $pdfWriter = new PdfWriter();
//        $pdfWriter->Write($html, $file_path. '/' . $file_name);

        $bg_image = WWW_ROOT.'/reports/report_pad.jpg';
        $backgroundStyle = 'style="background: url('. $bg_image .') no-repeat top center; background-size: 100% 100%;"';
        $html = str_replace('class="page"', $backgroundStyle, $html);

        $imagePath =  WWW_ROOT.'/reports/verification_link.png';
        $newImgTag = '<img class="qrcode" src="'.$imagePath.'" alt="QR Code" />';
        $html = preg_replace('/<img class="qrcode"[^>]*>/', $newImgTag, $html);

        $pdfWriter->mpdfWrite($html, $file_path.DS, $file_name);
    }

    public  function  offerLetterTemplate($content)
    {
        $view = new View($this->request, $this->response);
        return $view->element('offer_letter_template', compact('content'));

    }

    public  function  visaLetterTemplate($content)
    {
        $view = new View($this->request, $this->response);
        return $view->element('visa_letter', compact('content'));

    }

    public  function  reportGenerationHistory($report_format_id,$student_name,$student_email,$file_path,$user_id){
        $this->loadModel('ReportFormatGenerationHistories');
        $report_format_generation_history = $this->ReportFormatGenerationHistories->newEntity();
        $report_format_generation_history_request = [
            'report_format_id' => $report_format_id,
            'name' => $student_name,
            'receiver_emails' => $student_email,
            'file_path' => $file_path,
            'expiration_at' => frozenTime::now()->addMonths(2),
            'status' => 1,
            'updated_by_id' => $user_id,
            'updated_at' => FrozenTime::now(),
            'created_by_id' => $user_id,
            'created_at' => FrozenTime::now()
        ];
        $report_format_generation_history = $this->ReportFormatGenerationHistories->patchEntity($report_format_generation_history, $report_format_generation_history_request);
        $this->ReportFormatGenerationHistories->save($report_format_generation_history);
    }

    public  function  letterSentHistory($report_format_id,$report_type_id,$student,$file_path,$column_value,$user_id){
        $this->loadModel('LetterSentHistories');
        $letter_sent_history = $this->LetterSentHistories->newEntity();
        $letter_sent_history_request = [
            'report_type_id' => $report_type_id,
            'report_format_id' => $report_format_id,
            'student_id' => $student['id'],
            'student_email' => $student['email'],
            'sent_date' => FrozenTime::now(),
            'letter_file_path' => $file_path,
            'updated_by_id' => $user_id,
            'updated_at' => FrozenTime::now(),
            'created_by_id' => $user_id,
            'created_at' => FrozenTime::now()
        ];
        $letter_sent_history = $this->LetterSentHistories->patchEntity($letter_sent_history, $letter_sent_history_request);
        $this->LetterSentHistories->save($letter_sent_history);
        $this->letterSentHistoryDetails($letter_sent_history['id'],json_encode($column_value),$user_id);
    }

    public  function  letterSentHistoryDetails($letter_sent_history_id,$column_value,$user_id){
        $this->loadModel('LetterSentHistoryDetails');
        $letter_sent_history_detail = $this->LetterSentHistoryDetails->newEntity();
        $letter_sent_history_detail_request = [
            'letter_sent_history_id' => $letter_sent_history_id,
            'column_value' => $column_value,
            'updated_by_id' => $user_id,
            'updated_at' => FrozenTime::now(),
            'created_by_id' => $user_id,
            'created_at' => FrozenTime::now()
        ];
        $letter_sent_history_detail = $this->LetterSentHistoryDetails->patchEntity($letter_sent_history_detail, $letter_sent_history_detail_request);
        $this->LetterSentHistoryDetails->save($letter_sent_history_detail);
    }

    public function delete($id=null)
    {
        $student = $this->Students->get($id);

        if ($this->Students->delete($student)) {

            $this->Flash->success(__('The Student has been deleted.'));
        } else {
            $this->Flash->error(__('The Student could not be deleted. Please try again.'));
        }

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

    private function setCourseCategory($id){
        $categories = [
            1 => 'Business Management',
            2 => 'English Language',
            3 => 'Health and Social Care',
            4 => 'Hospitality and Tourism Management',
            5 => 'Business Innovation and Entrepreneurship',
            6 => 'Information Technology',
            7 => 'Nursing and Midwifery'
        ];

        return $categories[$id];
    }

}
