<?php
namespace App\Controller;

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

/**
 * Student Controller
 *
 * @property \App\Model\Table\FeedBacksTable $Feedbacks
 * @property \App\Model\Table\StudentSessionsTable $StudentSessions
 * @property \App\Model\Table\StudentCoursesTable $StudentCourses
 * @property \App\Model\Table\CoursesTable $Courses
 * @property \App\Model\Table\SessionsTable $Sessions
 */
class FeedBackController extends AppsController
{

    private  $controller = "feed-back";
    public function initialize(): void
    {
        parent::initialize();
        $this->loadModel('Feedbacks');
        $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 email LIKE '%" . $search . "%' OR phone_number LIKE '%" . $search . "%' OR subject LIKE '%" . $search . "%'" .')' ;
        }
        $feedbacks = $this->Feedbacks->find('all')->where($condition);

        $this->set('page_limit', $page_limit);
        $this->set('feedbacks', $this->paginate($feedbacks));
        $this->set('searchText', $search);

    }

    public function add()
    {
        $sessions = $this->Sessions->find('list', [
            'keyField' => 'id',
            'valueField' => 'name'
        ])->toArray();
        $courses = $this->Courses->find('list', [
            'keyField' => 'id',
            'valueField' => 'name'
        ])->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['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);

                $this->Flash->success(__('The student has been saved.'));
                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('Unable to add the student.'));
        }
        $this->set(compact('sessions','courses'));
        $this->setNextPage();
    }

    public function edit($id=null)
    {

        $feedback = $this->Feedbacks->get($id, [
            'contain' => []
        ]);


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

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

            $feedback = $this->Feedbacks->patchEntity($feedback, $request);

            $errors = $feedback->errors();

            $feedback['response_date'] = FrozenTime::now();

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

        $this->set('feedback', $feedback);
        $this->set('_serialize', ['feedback']);
        $this->setNextPage();
    }

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

        $this->set('feedback', $feedback);
        $this->set('_serialize', ['feedback']);
        $this->setNextPage();

    }

    private function feedback_email($feedback){
        $template_content = array(
            'name' => $feedback->name,
            'from_message' => $feedback->message,
            'reply_message' => $feedback->response_text
        );

        $this->sendEmail(MANDRILL_TEMPLATE_REPLY_MESSAGE, $template_content, $feedback->email, 'Feedback Reply', "", null);

    }

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


}
