<?php

namespace Shm\ShmS3;

use Aws\S3\S3Client;
use Shm\ShmUtils\Config;
use Shm\ShmUtils\ShmInit;

class ShmS3
{

    public static function onlyLetters($str)
    {
        $result = preg_replace('/[^a-zа-я]/ui', '*', $str);
        $result = explode('*', $result ?? "");
        $result = array_diff($result, ['']);

        $text = [];
        foreach ($result as $index => $val) {
            if ($index > 0) {
                $val = ucfirst($val);
            }

            $text[] = $val;
        }
        return implode('', $text);
    }

    public static function saveToS3($path, $file, $targetDir = "files")
    {
        // Instantiate an Amazon S3 client.
        $s3 = new S3Client([
            'version' => Config::get("s3.version", 'latest'),
            'region' => Config::get("s3.region"),
            'endpoint' => Config::get("s3.endpoint"),
            'credentials' => [
                'key' => Config::get("s3.credentials.key"),
                'secret' => Config::get("s3.credentials.secret"),
            ],
        ]);

        $rootDir = self::onlyLetters($_SERVER['HTTP_HOST'] ?? "cmd");

        // Check if $path is a URL.
        if (filter_var($path, FILTER_VALIDATE_URL)) {

            $new_path = ShmInit::$rootDir . '/storage/files/s3upload';

            if (!is_dir($new_path)) {
                mkdir($new_path, 0777, true); // создать все вложенные папки
            }


            file_put_contents($new_path, file_get_contents($path));
            $path = $new_path;
        }

        // If $path is not a URL, assume it is a file path and open the file.
        $body = fopen($path, 'r');
        $size = filesize($path);

        $configPutObject = [
            'Bucket' => Config::get("s3.bucket"),
            'Key' => $rootDir . "/" . $targetDir . '/' . $file,
            'Body' => $body,
            'ContentLength' => $size,
            'ACL' => 'public-read',
        ];



        $result = $s3->putObject($configPutObject);

        // If the file was downloaded to a temporary location, delete it.
        if (isset($new_path)) {
            unlink($new_path);
        }

        if (isset($result['ObjectURL'])) {
            return $result['ObjectURL'];
        } else {
            return '';
        }
    }
}
