<?php

namespace App\Helpers;

use Imagick;
use Illuminate\Support\Facades\Storage;

class NudityHelper
{
    public static function check(
        mixed $fileName,
    ): array {
        try {
            $type = 'jpg';
            $fileNameArr = explode(".", $fileName);
            $filePath = Storage::disk('temp')
                ->path($fileName);

            if ($fileNameArr[1] != $type) {

                $fileTargetPath = Storage::disk('temp')
                    ->path("{$fileNameArr[0]}_check.{$type}");

                $convert = self::jpg($filePath, $fileTargetPath);

                if ($convert[0]) {

                    $check = self::process($fileTargetPath);

                    if (!$check[0]) {
        
                        Storage::disk('temp')
                            ->delete("{$fileNameArr[0]}_check.{$type}");
                        
                        return [
                            false, 
                            $check[1]
                        ];
                    } else {
                        return [
                            true 
                        ];
                    }

                } else {
                    return [
                        false,
                        $convert[1]
                    ];
                }

            } else {
                $check = self::process($filePath);

                if (!$check[0]) {

                    Storage::disk('temp')
                        ->delete($fileName);

                    return [
                        false, 
                        $check[1]
                    ];
                } else {
                    return [
                        true 
                    ];
                }

            }

        } catch (\Exception $e) {

            return [
                false, 
                $e->getMessage()
            ];
        }

    }

    private static function jpg(
        string $filePath, 
        string $fileTargetPath
    ): array {
        try {
            $imagick = new Imagick($filePath);

            $format = 'jpg';
            $compression = Imagick::COMPRESSION_JPEG;

            $imagick->setFormat($format);
            $imagick->setImageFormat($format);

            $imagick->setCompression($compression);
            $imagick->setImageCompression($compression);

            $imagick->setCompressionQuality(100);
            $imagick->setImageCompressionQuality(100);

            $imagick->writeImage($fileTargetPath);

            $imagick->clear();
            $imagick->destroy();

            return [
                true
            ];

        } catch (\ImagickException $e) {

            return [
                false, 
                $e->getMessage()
            ];
        }
    }

    private static function process(
        string $filePath, 
    ): array {
        try {
            $userKey = setting('nudity_user');
            $secretKey = setting('nudity_secret');

            if (!$userKey || !$secretKey) {
                return [
                    false, 
                    __('lang.error')
                ];
            }

            $params = array(
                'media' => new \CurlFile($filePath),
                'models' => 'nudity-2.1',
                'api_user' => $userKey,
                'api_secret' => $secretKey,
            );
            
            $ch = curl_init('https://api.sightengine.com/1.0/check.json');
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            $response = curl_exec($ch);
            curl_close($ch);
            
            $output = json_decode($response, true);

            if ($output['status'] == 'success') {
                if (
                    $output['nudity']['sexual_activity'] > 0.01 
                    || $output['nudity']['sexual_display'] > 0.01 
                    ||$output['nudity']['erotica'] > 0.01
                ) {
                    return [
                        false, 
                        __('lang.cannot_upload_nudity')
                    ];
                } else {
                    return [true];
                }
            } else {
                if (isset($output['error']['message'])) {
                    return [
                        false, 
                        "Nudity API: {$output['error']['message']}"
                    ];
                } else {
                    return [
                        false, 
                        __('lang.error')
                    ];
                }
            }

        } catch (\Exception $e) {
            return [
                false, 
                $e->getMessage()
            ];
        }
    }
}
