<?php

//namespace Jaga\Controllers;
use Phalcon\Mvc\Model\Query;
use Jaga\Models\PAK\PAKIsianSekolah;
use Jaga\Models\PAK\PAKIsianSekolahAttachment;

class PAKIsianSekolahAttachmentController extends BaseController
{
	protected $documentFolder;
	protected $imageFolder;

    public function onConstruct()
    {
        parent::onConstruct();
        $this->documentFolder = 'pak-isian-sekolah-attachment/document' . DIRECTORY_SEPARATOR;
        $this->imageFolder = 'pak-isian-sekolah-attachment/image' . DIRECTORY_SEPARATOR;
    }

    public function uploadDoc()
    {
        $this->checkIsAuthenticated();
        $this->checkScopes(['pak.manage.isiansekolah']);

        $postRequest = $this->request->getPost();

        $validatedRequest = $this->validate($postRequest, [
            'keterangan' => ['validators' => []],
            'metadata' => ['validators' => []]
        ]);

        $minioService = $this->minio;
        $service = new AttachmentService($this->shared, $minioService);
        $validationConfig = [
            'allowed-types' => [
                "application/pdf", //.pdf
                "application/msword", //.doc
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document", //.docx
                "application/vnd.ms-excel", //.xls
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", //.xlsx
                "application/vnd.ms-powerpoint", //.ppt
                "application/vnd.openxmlformats-officedocument.presentationml.presentation", //.pptx
                "text/plain", //.txt
            ],
             'max-file-count' => 10,
             'max-size-kb' => 10000
        ];
        $attachmentConfig = [
            'tipe' => Attachments::TIPE_PUBLIC,
        ];

        if ($minioService->isSecondaryS3Available()) {
            $attachments = $service->uploadUsingSecondaryS3(
                getenv("FILESYSTEM_CLOUD"),
                $validationConfig,
                $attachmentConfig,
                $this->request,
                $this->documentFolder
            );
        }
        else {
            $attachments = $service->upload(
                getenv("FILESYSTEM_CLOUD"),
                $validationConfig,
                $attachmentConfig,
                $this->request,
                $this->documentFolder
            );
        }

        return new CollectionPaginatedResponse($attachments);
    }

    public function uploadImage()
    {
        $this->checkIsAuthenticated();
        $this->checkScopes(['pak.manage.isiansekolah']);

        $postRequest = $this->request->getPost();

        $validatedRequest = $this->validate($postRequest, [
            'keterangan' => ['validators' => []],
            'metadata' => ['validators' => []]
        ]);

        $minioService = $this->minio;
        $service = new AttachmentService($this->shared, $minioService);
        $validationConfig = [
            'allowed-types' => [
                "image/jpg",
                "image/jpeg",
                "image/png",
                "image/x-windows-bmp",
                "image/x-ms-bmp",
                "image/bmp",
                "image/gif",
                "image/tiff",
            ],
            'max-file-count' => 10,
            'max-size-kb' => 10000
        ];
        $attachmentConfig = [
            'tipe' => Attachments::TIPE_PUBLIC,
        ];

        if ($minioService->isSecondaryS3Available()) {
            $attachments = $service->uploadUsingSecondaryS3(
                getenv("FILESYSTEM_CLOUD"),
                $validationConfig,
                $attachmentConfig,
                $this->request,
                $this->imageFolder
            );
        }
        else {
            $attachments = $service->upload(
                getenv("FILESYSTEM_CLOUD"),
                $validationConfig,
                $attachmentConfig,
                $this->request,
                $this->imageFolder
            );
        }

        return new CollectionPaginatedResponse($attachments);
    }

    public function presignedUrlUpload() {
        $this->checkScopes(['pak.manage.isiansekolah']);

        $rawBody = $this->request->get();
        $validatedRequest = $this->validate($rawBody, [
            'tipe' => ['validators' => [['params' => ['image', 'doc'], 'name' => 'inclusion_in']]],
            'amount' => ['validators' => ['required', 'digit']],
        ]);

        $tipe = $validatedRequest['tipe'];
        $amount = (int) $validatedRequest['amount'];
        if ($tipe == 'image') $subFolder = $this->imageFolder;
        elseif ($tipe == 'doc') $subFolder = $this->documentFolder;
        else throw new CustomErrorException(BaseResponse::INVALID_REQUEST, "Tipe lampiran tidak valid!");

        $service = new AttachmentService($this->shared, $this->minio);
        $presignedUrls = [];
        for ($i = 0; $i < $amount; $i++) {
            $presignedUrls[] = $service->presignedUrlUpload($subFolder);
        }

        return new CollectionPaginatedResponse($presignedUrls);
    }

    public function downloadDoc($uuid)
    {
//        $this->checkScopes(['pak.view.isiansekolah']);

        /** @var Attachments $attachment */
        $attachment = Attachments::findOrFail([
                "uuid = :uuid:",
                "bind" => [
                    "uuid" => $uuid
                ]
            ]);

        if (!empty($attachment)) {
            if (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::MINIO) {
                /** @var MinioService $minioService */
                $minioService = $this->minio;
                $filename = $attachment->filename;
                $filekey = 'users_profpic' . DIRECTORY_SEPARATOR . $this->documentFolder . DIRECTORY_SEPARATOR . $uuid;

                $url = $attachment->validPresignedUrl();
                if (!$url) {
                    $url = $minioService->checkAndDownloadPublicWithLongExpDuration(
                        LogAttachments::PAKIsianSekolahAttachment,
                        $attachment->created_at,
                        $filekey,
                        $filename,
                        true
                    );
                    if ($url) {
                        $attachment->updatePresignedUrl($url);
                    }
                }

                return new SimpleResponse(str_replace('"', '', $url));
            }
            else if (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::LOCAL) {
                $filename = AttachmentHelper::getLocalPath($attachment, $this->attachmentFolder);

                if (!file_exists($filename)) {
                    throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "File Not Found");
                }

                return MediaHelper::fileResponse($filename, $attachment->filename, true);
            }
        }
        else {
            throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "File Not Found or Not active");
        }
    }

    public function downloadImage($uuid)
    {
//        $this->checkScopes(['pak.view.isiansekolah']);

        $urlOnly = $this->request->get('urlOnly', null, true);

        /** @var Attachments $attachment */
        $attachment = Attachments::findOrFail([
                "uuid = :uuid:",
                "bind" => [
                    "uuid" => $uuid
                ]
            ]);

        if (!empty($attachment)) {
            if (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::MINIO) {
                /** @var MinioService $minioService */
                $minioService = $this->minio;
                $filename = $attachment->filename;
                $filekey = 'users_profpic' . DIRECTORY_SEPARATOR . $this->imageFolder . DIRECTORY_SEPARATOR . $uuid;

                $url = $attachment->validPresignedUrl();
                if (!$url) {
                    $url = $minioService->checkAndDownloadPublicWithLongExpDuration(
                        LogAttachments::PAKIsianSekolahAttachment,
                        $attachment->created_at,
                        $filekey,
                        $filename,
                        true
                    );
                    if ($url) {
                        $attachment->updatePresignedUrl($url);
                    }
                }

                $response = new \Phalcon\Http\Response();
                return $urlOnly ? new SimpleResponse(str_replace('"', '', $url)) : $response->redirect($url, true, 302);

            }
            else if (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::LOCAL) {
                $filename = AttachmentHelper::getLocalPath($attachment, $this->attachmentFolder);

                if (!file_exists($filename)) {
                    throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "File Not Found");
                }

                return MediaHelper::fileResponse($filename, $attachment->filename, true);
            }
        }
        else {
            throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "File Not Found or Not active");
        }
    }

    public function deleteAttachment($uuid)
    {
        $this->checkIsAuthenticated();
        $this->checkScopes(['pak.manage.isiansekolah']);

        $attachmentFile = Attachments::findOrFail([
                "uuid = :uuid:",
                "bind" => [
                    "uuid" => $uuid
                ]
            ]);
        $attachment_id = $attachmentFile->id;
        $attachment = PAKIsianSekolahAttachment::findFirst([
                "attachment_id = :attachment_id:",
                "bind" => [
                    "attachment_id" => $attachment_id
                ]
            ]
        );

        if (!empty($Attachment)) {
            $attachment->forceDelete();
        }

        $deleted = \AttachmentHelper::delete($attachmentFile, false);

        if (!$deleted) {
            $this->throwValidationException($attachmentFile->getMessages());
        } else {

            return new CollectionPaginatedResponse([$attachmentFile]);
        }
    }
}
