<?php

use Phalcon\Mvc\Url;

class AttachmentsController extends BaseController
{
    public function publicUpload()
    {
        return $this->upload(['tipe' => Attachments::TIPE_PUBLIC]);
    }

    public function privateUpload()
    {
        return $this->upload(['tipe' => Attachments::TIPE_PRIVATE]);
    }

    private function upload($config)
    {
        $this->checkIsAuthenticated();

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

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

        $useSecondary = $params['use_secondary'];
        $service = new AttachmentService($this->shared, $this->minio);
        if ($useSecondary) {
            $attachments = $service->uploadUsingSecondaryS3(
                getenv("FILESYSTEM_CLOUD"),
                [
                    'allowed-types' => $this->config["allowed_mime_types"],
                ],
                $config,
                $this->request,
                '/'
            );
        } else {
            $attachments = $service->upload(
                getenv("FILESYSTEM_CLOUD"),
                [
                    'allowed-types' => $this->config["allowed_mime_types"],
                ],
                $config,
                $this->request,
                '/'
            );
        }

        return new CollectionPaginatedResponse($attachments);
    }

    public function download($uuid)
    {
        $attachment = Attachments::findFirst(
            [
                "uuid = :uuid:",
                "bind" => [
                    "uuid" => $uuid
                ]
            ]
        );

        if (!empty($attachment)) {
            if ($attachment->tipe == Attachments::TIPE_PRIVATE) {
                $this->checkIsAuthenticated();
            }
        }

        $service = new AttachmentService($this->shared, $this->minio);

        return $service->download(
            DIRECTORY_SEPARATOR,
            $uuid
        );
    }

    public function url($uuid)
    {
        $attachment = Attachments::findFirst(
            [
                "uuid = :uuid: AND deleted_at is NULL",
                "bind" => [
                    "uuid" => $uuid
                ]
            ]
        );

        if (!empty($attachment)) {
            if ($attachment->tipe == Attachments::TIPE_PRIVATE) {
                $this->checkIsAuthenticated();
            }

            if (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::MINIO) {
                $url = "";
                if ($attachment->tipe == Attachments::TIPE_PRIVATE) {
                    $url = $this->minio->base_get_private_url('diskusi_attachment' . DIRECTORY_SEPARATOR . $uuid, $attachment->filename, true);
                } else {
                    $url = $this->minio->base_get_public_url('users_profpic' . DIRECTORY_SEPARATOR . $uuid, $attachment->filename, true);
                }

                return new SimpleResponse([
                    'url' => $url,
                    'filename' => $attachment->filename,
                    'auth' => false
                ]);
            } elseif (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::LOCAL) {
                $filename = AttachmentHelper::getLocalPath($attachment);

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

                $url = $this->config['web_base_url'] . '/api/v5/attachments/download/' . $uuid;

                return new SimpleResponse([
                    'url' => $url,
                    'filename' => $attachment->filename,
                    'auth' => true
                ]);
            }
        } else {
            throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "File Not Found or Not active");
        }
    }

    // TODO change folder directory
    public function mcpUrl($uuid)
    {
        
        $getParams = $this->request->get();
        $validatedParams = $this->validate(
            $getParams,
            [
                'indikator_id' => ['validators' => []],
                'instansi_id' => ['validators' => []]
            ]
        );

        $query = "
           SELECT A.started_at, A.ended_at, B.tahun,
                B.id as template_id, C.id as area_id, 
                D.id as sasaran_id, E.id as aspek_id, 
                F.id as indikator_id
            FROM mcp.periode A
            INNER JOIN mcp.template B
                ON A.template_id = B.id
            INNER JOIN mcp.area C
                ON B.id = C.template_id
            INNER JOIN mcp.sasaran D
                ON C.id = D.area_id
            INNER JOIN mcp.aspek E
                ON D.id = E.sasaran_id
            LEFT JOIN mcp.indikator F
                ON E.id = F.aspek_id
            WHERE F.id = :indikator_id
        ";

        $details = $this->rawQuery($query, [
            'indikator_id' => $validatedParams['indikator_id']
        ]);

        if(count($details) == 0) {
            throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "Data not found");
        }

        $attachment = McpAttachments::findFirst(
            [
                "uuid = :uuid: AND deleted_at is NULL",
                "bind" => [
                    "uuid" => $uuid
                ]
            ]
        );

        if (!empty($attachment)) {
            if ($attachment->tipe == McpAttachments::TIPE_PRIVATE) {
                $this->checkIsAuthenticated();
            }

            if (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::MINIO) {
                $url = "";
                $subFolder = McpAnswerAttachment::getSubfolder($details[0]['tahun'], $validatedParams['instansi_id']);
                $key = $subFolder . DIRECTORY_SEPARATOR . $uuid;
                if ($attachment->tipe == McpAttachments::TIPE_PRIVATE) {
                    $url = $this->minio->base_get_private_url($key, $attachment->filename, true);
                } else {
                    $url = $this->minio->base_get_public_url($key, $attachment->filename, true);
                }

                return new SimpleResponse([
                    'url' => $url,
                    'filename' => $attachment->filename,
                    'auth' => false
                ]);
            } elseif (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::LOCAL) {
                $filename = AttachmentHelper::getMcpLocalPath($attachment);

                echo("filename: " . $filename);
                echo("file_exists: " . file_exists($filename));

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

                $url = $this->config['web_base_url'] . '/api/v5/attachments/mcp-download/' . $uuid;

                return new SimpleResponse([
                    'url' => $url,
                    'filename' => $attachment->filename,
                    'auth' => true
                ]);
            }
        } else {
            throw new CustomErrorException(BaseResponse::DATA_NOT_FOUND, "File Not Found or Not active");
        }
    }

    public function mcpDownload($uuid)
    {
        $attachment = McpAttachments::findFirst(
            [
                "uuid = :uuid:",
                "bind" => [
                    "uuid" => $uuid
                ]
            ]
        );

        if (!empty($attachment)) {
            if ($attachment->tipe == McpAttachments::TIPE_PRIVATE) {
                $this->checkIsAuthenticated();
            }
        }

        $service = new McpAttachmentService($this->shared, $this->minio);

        return $service->download(
            DIRECTORY_SEPARATOR,
            $uuid
        );
    }

    public function panduan_stranas()
    {
        if (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::MINIO) {
            $url = $this->minio->base_get_public_url('users_profpic' . DIRECTORY_SEPARATOR . $this->config["stranas_panduan_file_name"], $this->config["stranas_panduan_file_name"], true);
            $response = new \Phalcon\Http\Response();
            return $response->redirect($url, true, 302);
        } elseif (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::LOCAL) {
            $filename = AttachmentHelper::getLocalPublicPath($this->config["stranas_panduan_file_name"]);

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

            return MediaHelper::fileResponse($filename, "Panduan_Stranas.pdf");
        }
    }

    public function public_download()
    {
        $getParams = $this->request->get();

        $validatedRequest = $this->validate(
            $getParams,
            [
                'filename' => ['validators' => ['required']],
            ]
        );

        $filename = $getParams['filename'];
        if (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::MINIO) {
            $url = $this->minio->base_get_public_url('public_content' . DIRECTORY_SEPARATOR . $filename, $filename, true);

            $response = new \Phalcon\Http\Response();
            return $response->redirect($url, true, 302);
        } elseif (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::LOCAL) {
            $url = $this->config["profile_picture_base_url"] . rawurlencode($filename);

            $response = new \Phalcon\Http\Response();
            return $response->redirect($url, true, 302);
        }
    }

    public function public_view()
    {
        $getParams = $this->request->get();

        $validatedRequest = $this->validate(
            $getParams,
            [
                'filename' => ['validators' => ['required']],
            ]
        );

        $filename = $getParams['filename'];

        if (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::MINIO) {
            $url = $this->minio->base_get_public_url('public_content' . DIRECTORY_SEPARATOR . $filename, $filename, false);

            $response = new \Phalcon\Http\Response();
            return $response->redirect($url, true, 302);
        } elseif (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::LOCAL) {
            $url = $this->config["profile_picture_base_url"] . rawurlencode($filename);

            $response = new \Phalcon\Http\Response();
            return $response->redirect($url, true, 302);
        }
    }

    public function publicContentUpload()
    {
        $this->checkIsAuthenticated();

        $this->checkScopes(['admin.view']);

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

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

        $service = new AttachmentService($this->shared, $this->minio);
        $attachments = $service->uploadPublicContent(
            getenv("FILESYSTEM_CLOUD"),
            [
                'allowed-types' => $this->config["allowed_mime_types"],
            ],
            $this->request,
            '/' . $params['subdir']
        );

        return new CollectionPaginatedResponse($attachments);
    }

    public function publicContentView()
    {
        $getParams = $this->request->get();

        $this->validate(
            $getParams,
            [
                'subdir' => ['validators' => ['required']],
                'filename' => ['validators' => ['required']],
            ]
        );

        $subdir = $getParams['subdir'];
        $filename = $getParams['filename'];

        /** @var MinioService $minioService */
        $minioService = $this->minio;

        if (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::MINIO) {
            if ($minioService->isSecondaryS3Available()) {
                $url = $minioService->basePublicUrlUsingSecondaryS3('public_content' . DIRECTORY_SEPARATOR . $subdir . DIRECTORY_SEPARATOR . $filename, $filename, false);
            } else {
                $url = $minioService->base_get_public_url('public_content' . DIRECTORY_SEPARATOR . $subdir . DIRECTORY_SEPARATOR . $filename, $filename, false);
            }

            $response = new \Phalcon\Http\Response();
            return $response->redirect($url, true, 302);
        } elseif (getenv("FILESYSTEM_CLOUD") == FileSystemCloud::LOCAL) {
            $url = $this->config["profile_picture_base_url"] . $subdir. DIRECTORY_SEPARATOR . rawurlencode($filename);

            $response = new \Phalcon\Http\Response();
            return $response->redirect($url, true, 302);
        }
    }
}
