<?php

namespace App\Controllers;

use CodeIgniter\Files\File;
use Aws\S3\S3Client;


class Upload extends BaseController
{
    protected $helpers = ['form'];

    public function index()
    {
        return view('test', ['errors' => []]);
    }

    public function upload()
    {
        $validationRule = [
            'userfile' => [
                'label' => 'Image File',
                'rules' => 'uploaded[userfile]'
                . '|is_image[userfile]'
                . '|mime_in[userfile,image/jpg,image/jpeg,image/gif,image/png,image/webp]'
                . '|max_size[userfile,5000]'
                . '|max_dims[userfile,9000,9000]',
            ],
        ];
        if (! $this->validate($validationRule)) {
            $data = ['errors' => $this->validator->getErrors()];

            return view('test', $data);
        }

        $img = $this->request->getFile('userfile');
        if (! $img->hasMoved()) {
            $filepath = WRITEPATH . 'uploads/' . $img->store();

            $data = ['uploaded_flleinfo' => new File($filepath)];

            // Inisiasi helper S3
            $s3Client = new S3Client([
                'version' => 'latest',
                'region' => 'Global',
                'url' => 'https://is3.cloudhost.id/texapp/api/',
                'use_path_style_endpoint' => true,
                'endpoint' => 'https://is3.cloudhost.id/',
                'credentials' => [
                    'key' => '4Y7M0354JXFYU8YNZLQO',
                    'secret' => 'ouVVphb4YbQ3YSazWQJngEY7DDm92nQfIUzGzHPQ'
                ]
            ]);

            $bucket = 'texapp';
            $key = basename($filepath);

            try {
                // Proses upload ke object storage dengan permission file public
                $result = $s3Client->upload($bucket,$key,fopen($filepath, 'r'),'public-read');
                $data = ['result' => $result->toArray()];
                return view('upload_success', $data);
            } catch (Aws\S3\Exception\S3Exception $e) {
                $data = ['errors' => $e->getMessage()];
            }

        }
        return view('test', $data);
    }
}