<?php
namespace App\Controller;

use Cake\I18n\FrozenTime;

/**
 * LetterSentHistory Controller
 *
 * @property \App\Model\Table\LetterSentHistoriesTable $LetterSentHistories
 * @property \App\Model\Table\LetterSentHistoryDetailsTable $LetterSentHistoryDetails
 * @property \App\Model\Table\ReportFormatsTable $ReportFormats
 */
class LetterSentHistoryController extends AppsController
{
    private  $controller = "letter-sent-history";
    public function initialize(): void
    {
        parent::initialize();
        $this->loadModel('LetterSentHistories');
        $this->loadModel('LetterSentHistoryDetails');
        $this->loadModel('ReportFormats');
        $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' => [
                'LetterSentHistories.id' => 'ASC'
            ]
        ];

        $search = '';
        if (isset($this->request->query['search'])) {
            $search = $this->request->query('search');
            $condition = '(student_email LIKE ' . "'%" . $search  .  "%'" .')' ;
        }
        $report_format_histories = $this->LetterSentHistories->find('all',[
            'contain' => ['ReportFormats','ReportFormatTypes','Students']
        ])->where($condition);


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

    public function add()
    {
        $report_formats = $this->ReportFormats->find('list', [
            'keyField' => 'id',
            'valueField' => 'name'
        ])->where(['status'=>1])->toArray();

        if ($this->request->is('post')) {
            $user_id = $this->Auth->user('id');
            $report_format = $this->LetterSentHistories->newEntity();
            $request = $this->request->getData();
            $request['status'] = 1;
            $request['created_at'] = FrozenTime::now();
            $request['created_by_id'] = $user_id;
            $request['updated_at'] = FrozenTime::now();
            $request['updated_by_id'] = $user_id;
            $report_format = $this->LetterSentHistories->patchEntity($report_format, $request);
            $errors = $report_format->errors();
            if (empty($errors)) {
                if ($this->LetterSentHistories->save($report_format)) {

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

        $this->set(compact('report_formats'));
        $this->setNextPage();
    }

    public function edit($id=null)
    {
        $report_format_generation_history = $this->LetterSentHistories->get($id, [
            'contain' => []
        ]);

        $report_format = $this->ReportFormats->get($report_format_generation_history['report_format_id'], [
            'contain' => []
        ]);

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

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

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

            $report_format = $this->LetterSentHistories->patchEntity($report_format_generation_history, $this->request->data);

            $errors = $report_format->errors();

            $report_format['updated_at'] = FrozenTime::now();
            $report_format['updated_by'] = $user_id;
            if (empty($errors)) {
                if ($this->LetterSentHistories->save($report_format)) {
                    $this->Flash->success(__('The report format generation history has been updated.'));
                    return $this->redirect(['action' => 'index']);
                } else {
                    $this->Flash->error(__('The report format type could not be saved. Please, try again.'));
                }
            }
            $this->set('errors', $errors);
        }


        $this->set('report_format_generation_history', $report_format_generation_history);
        $this->set('report_formats', $report_formats);
        $this->set('report_format', $report_format);
        $this->setNextPage();
    }

    public function view($id)
    {
        $letter_sent_history = $this->LetterSentHistories->get($id,[
            'contain' => ['ReportFormats','ReportFormatTypes','Students']
        ]);

        $letter_sent_history_details = $this->LetterSentHistoryDetails->find()->where(['letter_sent_history_id'=>$letter_sent_history['id']])->first();

        $dynamic_value = json_decode($letter_sent_history_details['column_value'],true);

        $report_variable =  $this->findVariableFromHtmlContent($letter_sent_history->report_format->content);

        $variable_list =  $this->placedReportVariable($dynamic_value,$report_variable);

        $report = $this->reportHTMLReplace($letter_sent_history->report_format->content,$variable_list);

        $this->set('letter_sent_history', $letter_sent_history);
        $this->set('report', $report);
        $this->setNextPage();
    }

    public function download($id)
    {
        $letter = $this->LetterSentHistories->get($id);

        $filePath = WWW_ROOT . $letter->letter_file_path;

        if (!file_exists($filePath)) {
            throw new NotFoundException(__('File not found'));
        }

        return $this->response->withFile(
            $filePath,
            [
                'download' => true,
                'name' => $letter->letter_file_path
            ]
        );
    }

    public function resend($id = null)
    {
        $this->request->allowMethod(['post']);

        $letter = $this->LetterSentHistories->get($id,[
            'contain' => ['ReportFormats','ReportFormatTypes','Students']
        ]);
        $filePath = WWW_ROOT . $letter->letter_file_path;
        $template_content = array(
            'student_name' => $letter->student['first_name'].' '.$letter->student['surname'],
            'course'=> "",
            'letter_type'=> $letter->report_format['name']
        );
        $report_name =  $letter->report_format['name'].".pdf" ;
        $this->sendEmail('send_email_to_client', $template_content, $letter->student['email'], $letter->report_format['name'], [ $report_name => $filePath], null);

        $this->Flash->success(__('The letter has been resent successfully.'));

        return $this->redirect($this->referer());
    }

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

        return $matches[1];

    }

    public function placedReportVariable($dynamic_variable,$report_variables)
    {

        $variable_list = [];

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

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

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

        }
        return $variable_list;
    }

    public function reportHTMLReplace($content, $variableList) {

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

    public function delete($id=null)
    {
        $letter = $this->LetterSentHistories->get($id);
        $letter_path =  $letter->letter_file_path;
        if ($this->LetterSentHistories->delete($letter)) {
            $filePath = WWW_ROOT . $letter_path;
            if (file_exists($filePath)) {
                unlink($filePath);
            }
            $this->Flash->success(__('The LetterSentHistories has been deleted.'));
        } else {
            $this->Flash->error(__('The LetterSentHistories could not be deleted. Please try again.'));
        }

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

}
