<?php

class StranaspkNewAttachmentController extends BaseController{

    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",
                "image/jpg",
                "image/jpeg",
                "image/png",
                "image/x-windows-bmp",
                "image/x-ms-bmp",
                "image/bmp",
                "image/gif",
                "image/tiff", //.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 downloadDoc($uuid)
    {
//        $this->checkScopes(['pak.view.isiansekolah']);

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

        if (!empty($attachment)) {
            if (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::MINIO) {
                $minioService = $this->minio;
                $key = $this->documentFolder . DIRECTORY_SEPARATOR . $uuid;
                $url = $minioService->base_get_public_url('users_profpic' . DIRECTORY_SEPARATOR . $key, $attachment->filename, true);
                if(!MinioService::checkFileExist($url)) {
                    if($minioService->isSecondaryS3Available()) {
                        $url = $minioService->basePublicUrlUsingSecondaryS3('users_profpic' . DIRECTORY_SEPARATOR . $key, $attachment->filename, true);
                    }
                }
                $response = new \Phalcon\Http\Response();
                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 downloadDocFile($uuid)
    {
//        $this->checkScopes(['pak.view.isiansekolah']);

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

        if (!empty($attachment)) {
            if (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::MINIO) {
                $minioService = $this->minio;
                $key = $this->documentFolder . DIRECTORY_SEPARATOR . $uuid;
                $url = $minioService->base_get_public_url('users_profpic' . DIRECTORY_SEPARATOR . $key, $attachment->filename, false);
                if(!MinioService::checkFileExist($url)) {
                    if($minioService->isSecondaryS3Available()) {
                        $url = $minioService->basePublicUrlUsingSecondaryS3('users_profpic' . DIRECTORY_SEPARATOR . $key, $attachment->filename, true);
                    }
                }
                $response = new \Phalcon\Http\Response();
                return $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 uploadBannerAction()
    {
        if (!$this->request->hasFiles()) {
            return $this->response->setJsonContent([
                'success' => false,
                'message' => 'Tidak ada file'
            ]);
        }

        $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/uploads/';

        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $file = $this->request->getUploadedFiles()[0];

        // ambil extension asli dari nama file
        $ext = strtolower(pathinfo($file->getName(), PATHINFO_EXTENSION));

        // whitelist extension
        $allowed = ['png'];

        if (!in_array($ext, $allowed)) {
            return $this->response->setJsonContent([
                'success' => false,
                'message' => 'Format tidak didukung'
            ]);
        }

        $filename = 'kontak-untuk-jaga.' . $ext;

        $file->moveTo($uploadDir . $filename);

        return $this->response->setJsonContent([
            'success' => true,
            'image' => '/uploads/' . $filename
        ]);
    }

    public function getBannerAction()
    {
        $baseUrl = (isset($_SERVER['HTTPS']) ? "https" : "http")
            . "://$_SERVER[HTTP_HOST]";

        return $this->response->setJsonContent([
            'success' => true,
            'data' => [
                'image' => $baseUrl . '/uploads/kontak-untuk-jaga.png'
            ]
        ]);
    }

    public function uploadBannerActionBispro()
    {
        if (!$this->request->hasFiles()) {
            return $this->response->setJsonContent([
                'success' => false,
                'message' => 'Tidak ada file'
            ]);
        }

        $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/uploads/';

        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $file = $this->request->getUploadedFiles()[0];

        // ambil extension asli dari nama file
        $ext = strtolower(pathinfo($file->getName(), PATHINFO_EXTENSION));

        // whitelist extension
        $allowed = ['png'];

        if (!in_array($ext, $allowed)) {
            return $this->response->setJsonContent([
                'success' => false,
                'message' => 'Format tidak didukung'
            ]);
        }

        $filename = 'bispro.' . $ext;

        $file->moveTo($uploadDir . $filename);

        return $this->response->setJsonContent([
            'success' => true,
            'image' => '/uploads/' . $filename
        ]);
    }

    public function getBannerActionBispro()
    {
        $baseUrl = (isset($_SERVER['HTTPS']) ? "https" : "http")
            . "://$_SERVER[HTTP_HOST]";

        return $this->response->setJsonContent([
            'success' => true,
            'data' => [
                'image' => $baseUrl . '/uploads/bispro.png'
            ]
        ]);
    }
}
