<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . '../vendor/autoload.php';
use Aws\S3\S3Client;

class R2Storage {

    protected $s3;
    protected $bucket;

    public function __construct()
    {
        $CI = &get_instance();
        $CI->config->load('r2');
        $cfg = $CI->config->item('r2');

        $this->bucket = $cfg['bucket']; // webtrix-24-CRM

        $this->s3 = new S3Client([
            'version' => 'latest',
            'region'  => 'auto',
            'endpoint'=> $cfg['endpoint'],
            'credentials' => $cfg['credentials'],
            'use_path_style_endpoint' => true
        ]);
    }

    public function upload(string $key, string $tmpFile, string $contentType)
    {
        return $this->s3->putObject([
            'Bucket'      => $this->bucket,
            'Key'         => ltrim($key, '/'),
            'SourceFile'  => $tmpFile,
            'ContentType' => $contentType,
            'ACL'         => 'private'
        ]);
    }

    public function delete(string $key)
    {
        return $this->s3->deleteObject([
            'Bucket' => $this->bucket,
            'Key'    => ltrim($key, '/')
        ]);
    }

    public function presign(string $key, string $expires = '+10 minutes')
    {
        $cmd = $this->s3->getCommand('GetObject', [
            'Bucket' => $this->bucket,
            'Key'    => ltrim($key, '/')
        ]);

        return (string) $this->s3
            ->createPresignedRequest($cmd, $expires)
            ->getUri();
    }

    public function get($key)
    {
        return $this->s3->getObject([
            'Bucket' => $this->bucket,
            'Key'    => $key
        ]);
    }
}
