<?php
/**
 * @package EvolutionScript
 * @author: EvolutionScript S.A.C.
 * @Copyright (c) 2010 - 2020, EvolutionScript.com
 * @link http://www.evolutionscript.com
 */

namespace App\Controllers\Api;


use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
use Config\Services;
use Psr\Log\LoggerInterface;

class Messages extends ResourceController
{
    protected $format = 'json';
    protected $modelName = 'App\Models\TicketsMessage';
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger); // TODO: Change the autogenerated stub
        helper(['form','html','helpdesk','number','filesystem','text']);
    }

    public function create()
    {
        $api = Services::api();
        if(!$api->validatePermission('messages/create')){
            return $api->showError();
        }

        $validation = Services::validation();
        $settings = Services::settings();
        $tickets = Services::tickets();
        $attachments = Services::attachments();
        $validation->setRule('ticket_id', 'ticket_id', 'required|is_natural_no_zero|is_not_unique[tickets.id]',[
            'required' => lang('Api.error.ticketIdMissing'),
            'is_natural_no_zero' => lang('Api.error.ticketNotFound'),
            'is_not_unique' => lang('Api.error.ticketNotFound')
        ]);
        $validation->setRule('message','message', 'required',[
            'required' => lang('Api.error.messageMissing')
        ]);
        $validation->setRule('replier','replier', 'required|in_list[user,staff]',[
            'required' => lang('Api.error.replierMissing'),
            'in_list' => lang('Api.error.replierNotValid')
        ]);
        if($this->request->getPost('replier') == 'staff'){
            $validation->setRule('staff_id', 'staff_id', 'required|is_natural_no_zero|is_not_unique[staff.id,staff.active,1]',[
                'required' => lang('Api.error.staffIdMissing'),
                'is_natural_no_zero' => lang('Api.error.staffIdNotValid'),
                'is_not_unique' => lang('Api.error.staffIdNotFound')
            ]);
        }
        if($settings->config('ticket_attachment')){
            $max_size = $settings->config('ticket_file_size')*1024;
            $allowed_extensions = unserialize($settings->config('ticket_file_type'));
            $allowed_extensions = implode(',', $allowed_extensions);
            $validation->setRule('attachment', 'attachment', 'ext_in[attachment,'.$allowed_extensions.']|max_size[attachment,'.$max_size.']',[
                'ext_in' => lang('Api.error.fileNotAllowed'),
                'max_size' => lang_replace('Api.error.fileIsBig', ['%size%' => number_to_size($max_size*1024, 2)])
            ]);
        }

        if($validation->withRequest($this->request)->run() == false){
            return $api->output(implode(' ',array_values($validation->getErrors())), true);
        }

        if ($settings->config('ticket_attachment')) {
            if ($files_uploaded = $attachments->ticketUpload()) {
                $files = $files_uploaded;
            }
        }

        $ticket = $tickets->getTicket(['id' => $this->request->getPost('ticket_id')]);
        //message
        $staff_id = $this->request->getPost('replier') == 'staff' ? $this->request->getPost('staff_id') : 0;
        $message = $tickets->purifyHTML($this->request->getPost('message'));
        $message_id = $tickets->addMessage($ticket->id, $message, $staff_id, false);
        $tickets->updateTicketReply($ticket->id, $ticket->status, ($staff_id > 0 ? true : false));
        if (isset($files)) {
            $attachments->addTicketFiles($ticket->id, $message_id, $files);
        }
        if($staff_id > 0){
            $tickets->replyTicketNotification($ticket, $message, (isset($files) ? $files : null));
        }else{
            $tickets->staffNotification($ticket);
        }
        if($this->request->getPost('close') === '1' && $staff_id > 0){
            $tickets->updateTicket(['status' => 5], $ticket->id);
        }
        return $api->output(lang('Api.messageCreated'));
    }

    public function show($id = null)
    {
        $api = Services::api();
        if(!$api->validatePermission('messages/read')){
            return $api->showError();
        }
        $tickets = Services::tickets();
        if(!$ticket = $tickets->getTicket('id', $id)){
            return $api->output(lang('Api.error.ticketNotFound'), true);
        }
        $messages = $tickets->getMessages($ticket->id, 'id, date, customer, staff_id, message');
        return $api->output([
            'pages' => $messages['pager']->getLastPage(),
            'total_replies' => $messages['pager']->getDetails()['total'],
            'messages' => $messages['result']
        ]);
    }
}