<?php

namespace Hura8\System;


use Hura8\Interfaces\AppResponse;
use Hura8\Interfaces\FileHandleResponse;
use Hura8\System\Controller\bFileHandle;


class CopyFileFromUrl extends bFileHandle
{

    /**
     * @param string $file_url
     * @param int $max_file_size max file size in bytes accepts, default = 1MB
     * @param string $fixed_file_name set uploaded name to this fixed name (ie. [item_id].jpg) so old file will be replaced
     * @return FileHandleResponse
     */
    public function start(string $file_url, string $fixed_file_name='', int $max_file_size = 1000000) : FileHandleResponse
    {

        if(!Url::isUrlValid($file_url)) {
            return new FileHandleResponse(AppResponse::ERROR, $file_url." is not a valid url");
        }

        if(!$this->setup_success) {
            return new FileHandleResponse(AppResponse::ERROR, "Fail to setup");
        }

        $original_file_name = substr($file_url, strrpos($file_url, "/"));
        $original_file_path = $this->tmp_folder . "/". $original_file_name;

        $url_content = Url::getUrlContent($file_url);
        if(!$url_content || !@file_put_contents($original_file_path, $url_content)) {
            return new FileHandleResponse(AppResponse::ERROR, "Fail to copy");
        }

        /*if(!@copy($file_url, $original_file_path)) {
            return new FileHandleResponse(AppResponse::ERROR, "Fail to copy");
        }*/

        $result = $this->processFile(
            $original_file_name,
            $original_file_path,
            $fixed_file_name,
            $max_file_size
        );

        unset($url_content);

        return $result;
    }


}
