<?php

use Phalcon\Mvc\Url;

class AttachmentsForStranasPKController extends BaseController
{
    protected $documentFolder;

    public function onConstruct()
    {
        parent::onConstruct();
        $this->documentFolder = 'new-stranas-pk-milestone/document' . 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' => $this->config["allowed_mime_types"],
    //          'max-file-count' => 40,
    //          'max-size-kb' => 200000
    //     ];
    //     $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 uploadDoc(){
        $postParams = $this->request->getPost();

        $params = $this->validate($postParams, [
            'keterangan' => ['validators' => []],
            'metadata' => ['validators' => []],
            'use_secondary' => ['validators' => ['digit']]
        ]);

        $attachmentConfig = [
            'tipe' => Attachments::TIPE_PUBLIC,
        ];

        $validationConfig = [
             'allowed-types' => $this->config["allowed_mime_types"],
             'max-file-count' => 40,
             'max-size-kb' => 200000
        ];
        
        $useSecondary = $params['use_secondary'];
        $service = new AttachmentService($this->shared, $this->minio);
        if ($useSecondary) {
            $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, 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 $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']);
        $db = $this->getDI()->get('databaseNewStranas2024');
        $attachmentFile = Attachments::findOrFail([
                "uuid = :uuid:",
                "bind" => [
                    "uuid" => $uuid
                ]
        ]);

        $sql_verificator = "DELETE FROM t_attachment_kl_verificator WHERE uuid = :uuid";
        $sql_instansi = "DELETE FROM t_attachment_kl_instansi WHERE uuid = :uuid";
        $params = ['uuid' => $uuid];
        $db->execute($sql_verificator, $params);
        $db->execute($sql_instansi, $params);
        
        $deleted = \AttachmentHelper::delete($attachmentFile, false);

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

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