<?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 Attachments extends ResourceController
{
    protected $format = 'json';
    protected $modelName = 'App\Models\Attachments';
    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 index()
    {
        $api = Services::api();
        if(!$api->validatePermission('attachments/read')){
            return $api->showError();
        }

        $ticket_id = $this->request->getGet('ticket_id');
        $message_id = $this->request->getGet('msg_id');
        if(!is_numeric($ticket_id) && $ticket_id != round($ticket_id)){
            $this->model->where('ticket_id', $ticket_id);
        }

        if(is_numeric($message_id)){
            $this->model->where('msg_id', $message_id);
        }
        $list = $this->model->select('id, name, filetype, msg_id, filesize as size')
            ->get()
            ->getResult();
        return $api->output(['files' => $list]);
    }

    public function show($id = null)
    {
        $api = Services::api();
        if(!$api->validatePermission('attachments/download')){
            return $api->showError();
        }
        $attachments = Services::attachments();
        if(!$file = $attachments->getRow(['id' => $id])){
            return $api->output(lang('Api.error.attachmentNotFound'), true);
        }
        $file_path = WRITEPATH.'attachments'.DIRECTORY_SEPARATOR.$file->enc;
        if(!file_exists($file_path)){
            return $api->output(lang('Api.attachmentRemoved'), true);
        }
        return $this->respond([
            'success' => 1,
            'name' => $file->name,
            'filetype' => $file->filetype,
            'size' => $file->filesize,
            'content' => base64_encode(file_get_contents($file_path))
        ]);
    }
    public function delete($id = null)
    {
        $api = Services::api();
        if(!$api->validatePermission('attachments/delete')){
            return $api->showError();
        }
        $attachments = Services::attachments();
        if(!$file = $attachments->getRow(['id' => $id])){
            return $api->output(lang('Api.error.attachmentNotFound'), true);
        }
        $attachments->deleteFile($file);
        return $api->output(lang('Api.attachmentRemoved'));
    }
}