<?php

class SPISReportDownloadController extends BaseController
{

    public function createDocumentPost()
    {
        $rawBody = $this->request->getJsonRawBody(true);
        $params = $this->validate(
            $rawBody,
            [
                'email' => [],
                'instansi' => [],
                'instansiname' => [],
                'line' => [],
                'username' => [],
                'year' => [],
            ]
        );
        $client = new ReportDownloadClient($this->config["report_download_prop"]);
        $client->setLogger($this->logger);
        $res = $client->CreateDocumentPost($params);

        return new CollectionPaginatedResponse([$res]);
    }

    public function isDownloadSpiPDFAvailable()
    {
        $params = $this->request->get();
        $client = new ReportDownloadClient($this->config["report_download_prop"]);
        $client->setLogger($this->logger);
        $res = $client->IsDownloadSpiPDFAvailable($params);

        return new CollectionPaginatedResponse([$res]);
    }

    public function DownloadSPIPdf()
    {
        $params = $this->request->get();
        $client = new ReportDownloadClient($this->config["report_download_prop"]);
        $client->setLogger($this->logger);
        $res = $client->DownloadSPIPdf($params);

        return $res;
    }

    public function DownloadSPIPdfUmum()
    {
        $params = $this->request->get();
        $client = new ReportDownloadClient($this->config["report_download_prop"]);
        $client->setLogger($this->logger);
        $res = $client->DownloadSPIPdfUmum($params);

        return $res;
    }

    public function CreateReport()
    {
        $params = $this->request->get();
        $client = new ReportDownloadClient($this->config["report_download_prop"]);
        $client->setLogger($this->logger);
        $res = $client->CreateReport($params);

        return new CollectionPaginatedResponse([$res]);
    }

    public function GetPDFReportNew()
    {
        $params = $this->request->get();
        $params['instansi_id'] = array_key_exists('instansi_id', $params) ? $params['instansi_id'] : 0;
        $params['tahun'] = array_key_exists('tahun', $params) ? $params['tahun'] : null;

        $validatedRequest = $this->validate(
            $params,
            [
                'instansi_id' => ['validators' => ['required','digit']],
                'tahun' => ['validators' => ['required','digit']],
                'lang' => ['validators' => []]
            ]
        );

        $filename = '';
        $key = $validatedRequest['instansi_id'] . '.pdf';

        if($validatedRequest['instansi_id'] > 0) {
            $instansi = Instansi::findFirst($validatedRequest['instansi_id']);
            if(empty($instansi)) {
                throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Instansi tidak valid');
            }

            $filename = $instansi->id . ' - ' . $instansi->nama;
        } else {
            if (array_key_exists('lang', $params) && !empty($params['lang']) && $validatedRequest['lang'] == 'en') {
                $filename = '0 - National';
                $key = $validatedRequest['instansi_id'] . '_en.pdf';
            } else {
                $filename = '0 - Nasional';
            }
        }

        $service = new AttachmentService($this->shared, $this->minio);
        return $service->downloadPublicUsingSecondaryS3(
            'public_content' . DIRECTORY_SEPARATOR . 'file-spi' . DIRECTORY_SEPARATOR . $validatedRequest['tahun'] . DIRECTORY_SEPARATOR . 'pdf' . DIRECTORY_SEPARATOR,
            $key,
            $filename,
            'pdf'
        );
    }

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

        $this->checkOneOfScopes(['spi.view_klop_data']);

        $getParams = $this->request->get();
        $getParams['id_instansi'] = array_key_exists('id_instansi', $getParams) ? $getParams['id_instansi'] : 0;
        $getParams['tahun'] = array_key_exists('tahun', $getParams) ? $getParams['tahun'] : null;

        $params = $this->validate(
            $getParams,
            [
                'id_instansi' => ['validators' => ['required','digit']],
                'tahun' => ['validators' => ['required']]
            ]
        );

        if (empty($this->getIdInstansi())) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'User bukan admin instansi');
        }

        $idInstansi = $params['id_instansi'] ?? $this->shared->user->id_instansi;
        $instansi = Instansi::findFirst($idInstansi);

        if (empty($instansi)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Instansi tidak ditemukan');
        }

        if (!empty($instansi->deleted_at)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Instansi sudah terhapus');
        }

        $ereport = SpiPerluasanEreportFiles::findFirst([
            'conditions' => 'tahun = :tahun: AND id_instansi = :id_instansi:',
            'bind' => [
                'tahun' => $params['tahun'],
                'id_instansi' => $params['id_instansi']
            ]
        ]);

        if (empty($ereport)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Perluasan e-report tidak ditemukan');
        }

        $service = new AttachmentService($this->shared, $this->minio);
        return $service->downloadPublicUsingSecondaryS3(
            'public_content' . DIRECTORY_SEPARATOR . 'file-spi' . DIRECTORY_SEPARATOR . $params['tahun'] . DIRECTORY_SEPARATOR . 'pdf' . DIRECTORY_SEPARATOR . 'e-report' . DIRECTORY_SEPARATOR . 'perluasan' . DIRECTORY_SEPARATOR,
            $ereport->filename . '.rar',
            $ereport->filename,
            'rar'
        );
    }

    public function downloadDataSPI() {
        $request = $this->request->get();
        $request = $this->validate($request, [
            'tahun' => ['validators' => ['required', 'digit']]
        ]);

        $tahun = $request['tahun'];

        $uuid = AppConfig::getValueByKode("DATA_SPI_UUID_$tahun");
        if (!$uuid) {
            throw new CustomErrorException(BaseResponse::DATA_NOT_AVAILABLE, "Data SPI tahun $tahun tidak tersedia.");
        }

        $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) {
                /** @var MinioService $minioService */
                $minioService = $this->minio;
                if ($attachment->tipe == Attachments::TIPE_PRIVATE) {
                    $url = $minioService->base_get_private_url('diskusi_attachment' . DIRECTORY_SEPARATOR . $uuid, $attachment->filename, true);
                } else {
                    if ($minioService->isSecondaryS3Available()) {
                        $url = $minioService->basePublicUrlUsingSecondaryS3('users_profpic' . DIRECTORY_SEPARATOR . $uuid, $attachment->filename, true);
                    } else {
                        $url = $minioService->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");
        }
    }

    public function availableYearsDataSpi() {
        $key = "DATA_SPI_UUID_";
        $configs = AppConfig::findByLikeKode($key);

        $result = [];
        foreach ($configs as $config) {
            $value = str_replace($key, "", $config->kode);
            $result[] = $value;
        }

        return new SimpleResponse($result);
    }



    public function getPDFReportPTNGov()
    {
        $this->checkIsAuthenticated();
        $params = $this->request->get();

        $params['instansi_id'] = array_key_exists('instansi_id', $params) ? $params['instansi_id'] : 0;
        $params['tahun'] = array_key_exists('tahun', $params) ? $params['tahun'] : null;

        $validatedRequest = $this->validate(
            $params,
            [
                'instansi_id' => ['validators' => ['required', 'digit']],
                'tahun' => ['validators' => ['required']],
                'lang' => ['validators' => []]
            ]
        );

        $instansi = Instansi::find([
            'conditions' => 'id = :id:',
            'bind' => [
                'id' => $validatedRequest['instansi_id']
            ]
        ]);
        if (empty($instansi)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Instansi tidak ditemukan');
        }

        $spiPtnInstansiFiles = SpiInstansiPtnFiles::find([
            'conditions' => 'tahun = :tahun: AND instansi_id = :instansi_id:',
            'bind' => [
                'tahun' => $validatedRequest['tahun'],
                'instansi_id' => $instansi[0]->id
            ]
        ]);
        
        if (empty($spiPtnInstansiFiles)) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'File tidak ditemukan');
        }

        $filename = $spiPtnInstansiFiles[0]->filename;
        $key = $spiPtnInstansiFiles[0]->filename;

        $directory = 'public_content' .
            DIRECTORY_SEPARATOR .
            'file-spi' .
            DIRECTORY_SEPARATOR .
            $validatedRequest['tahun'] .
            DIRECTORY_SEPARATOR . 'pdf' .
            DIRECTORY_SEPARATOR . 'ptn' .
            DIRECTORY_SEPARATOR;
        
        $service = new AttachmentService($this->shared, $this->minio);
        return $service->downloadPublicUsingSecondaryS3(
            $directory,
            $key,
            $filename,
            'pdf'
        ); 
    }

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

        $filename = 'Petunjuk Pelaksanaan Penyusunan RTL SPI (untuk semua instansi).pdf';
        $key = 'Petunjuk Pelaksanaan Penyusunan RTL SPI (untuk semua instansi).pdf';

        $directory = 'public_content' .
            DIRECTORY_SEPARATOR .
            'file-spi' .
            DIRECTORY_SEPARATOR .
            '2024' .
            DIRECTORY_SEPARATOR . 'pdf' .
            DIRECTORY_SEPARATOR . 'ptn' .
            DIRECTORY_SEPARATOR;
        
        $service = new AttachmentService($this->shared, $this->minio);
        return $service->downloadPublicUsingSecondaryS3(
            $directory,
            $key,
            $filename,
            'pdf'
        ); 
    }
}
