<?php
/**
 * Created by Hurasoft.
 * Date: 28-May-2022
 * Description: Use this class to send local files to the cdn host (endpoint: cdn.host/file_upload_handle.php). The cdn host also has a copy of Hura8 main class to receive the uploaded files
 */

namespace Hura8\System;


class CDNFileUpload {

    //protected $upload_handle = 'http://local.hura8/file_upload_handle.php';
    protected $upload_handle = STATIC_DOMAIN . '/file_upload_handle.php';

    protected $user_id = 0;

    protected $target_path_item_type_mapping = [
        'product'   => 'media/product', // media/product
        'article'   => 'media/news', // media/news
        'brand'     => 'media/brand',
        'category'  => 'media/category',
        'banner'    => 'media/banner',
        'lib'       => 'media/lib/',
        'user_upload' => 'media/user_upload',
    ];

    public function __construct($user_id) {
        $this->user_id = $user_id;
    }

    /**
     * @description: an implementation of start method to upload an item's image
     * @param $item_type string
     * @param $content string
     * @param $file_name string
     * @return array | boolean
     */
    public function uploadFile($item_type, $file_name, $content, $set_target_path = '')
    {
        //$file_name  = substr(strrchr($img_url, "/"), 1);
        //$content    = get_url_content($img_url);

        $header_setting = [
            // 'Authorization' => "Basic ". base64_encode(API_KEY),
        ];

        if($set_target_path) {
            $target_path = $set_target_path;
        }else{
            $target_path = (isset($this->target_path_item_type_mapping[$item_type])) ? $this->target_path_item_type_mapping[$item_type] : '';
        }

        $multipart_settings = [
            [
                'name'     => 'upload_method',
                'contents' => 'content',
            ],
            [
                'name'     => 'file_name',
                'contents' => $file_name,
            ],
            [
                'name'     => 'target_path',
                'contents' => $target_path,
            ],
            [
                'name'     => 'file_content',
                'contents' => $content,
            ],

            //for upload server
            [
                'name'     => 'uid',
                'contents' => $this->user_id,
            ],
            [
                'name'     => 'time',
                'contents' => CURRENT_TIME,
            ],
            [
                'name'     => 'token',
                'contents' => $this->createToken($this->user_id, CURRENT_TIME),
            ],
            [
                'name'     => 'item_type',
                'contents' => $item_type ,
            ],
        ];

        return $this->start($header_setting, $multipart_settings);
    }

    /*
    let settings = {
        element : '',//element id to click on
        holder      : '', //id file holder
        form_name   : '',
        item_type   : '',
        item_id     : '',
        file_type   : '', //what is the file type: doc, photo, video ?
        file_field : '', //what field in the item table this file is used for ?
        resize : '200,400,600' //sizes to resize
        square: '200,400', //sizes to be square
        keep_width : '400', //sizes to keep the width
        max_file: 1
    }
    */

    /**
     * @description: a general method for upload
     * @param array $header_setting
     * @param array $multipart_settings
     * @return array | boolean
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    protected function start(array $header_setting = [], array $multipart_settings = []) {
        $client = new \GuzzleHttp\Client();

        $request = $client->request('POST', $this->upload_handle, [
            'headers' => $header_setting,
            'multipart' => $multipart_settings
        ]);

        return $request->getBody()->getContents();
    }


    // return string | boolean
    protected function getAssetType($file_name) {
        $ext = strtolower(strrchr($file_name, "."));

        if( $ext == '.css') return 'css';

        if( $ext == '.js') return 'js';

        if( \in_array($ext, ['.jpg', '.jpeg', '.gif', '.png', '.ico'])) return 'image';

        return false;
    }


    // this salt and createToken must be the same ones as in Hura8/Base/CDNFileUploadHandle
    // and different per project (or else others will use it to upload forbidden files on our clients' hosting)
    const SECURITY_SALT = 'ahss@3asdaaSDFSD';

    protected function createToken($id, $time) {
        return sha1(join("-", [$id , $time , static::SECURITY_SALT]));
    }

}

