<?php
function wosmpl_reduce_image($file_path,$ext,$width,$height,$new_widths) {
    foreach ($new_widths as $new_width) {
        $new_height = $height * ($new_width/$width);
        if ($ext == 'jpeg') {
            $source = imagecreatefromjpeg($file_path);
        } else if ($ext == 'png') {
            $source = imagecreatefrompng($file_path);
        }
        $thumb = imagecreatetruecolor($new_width, $new_height);
        imagecopyresampled($thumb, $source, 0, 0, 0, 0, $new_width,$new_height, $width, $height);
        $reduced_fn = str_replace(".$ext",'-'.$new_width.".$ext",$file_path);
        if ($ext == 'jpeg') {
            imagejpeg($thumb,$reduced_fn);
        } else if ($ext == 'png') {
            imagepng($thumb,$reduced_fn);
        }
    }

}

function wosmpl_upload_file(string $file, bool $isBase64Encoded = true)
{
    if ('' === $file) {
        return [];
    }

    $return = [];

    if ($isBase64Encoded) {
        $file = \substr($file, \strpos($file, ';base64,') + 8);
        $file = \base64_decode(sanitize_text_field($file));
    }

    // @fixby Mathieu Poisbeau (contact@freepius.net) 2020-11-16
    // concat $file with microtime() to make a unique file name
    $name = hash('sha1', $file.\microtime());

    $path = get_option('wosmpl_upload_dir') .'/'. $name;

    if (\file_put_contents($path, $file)) {
        list($type, $ext) = \explode('/', \mime_content_type($path));

        // Add the extension if any
        if ($ext) {
            \rename($path, "$path.$ext");
            $path .= ".$ext";
        }

        $return['file_url'] = \strstr($path, '/wp-content/');

        if (false !== \strpos($type, 'image')) {
            list($width, $height) = $return['img_info'] = \getimagesize($path);
            wosmpl_reduce_image($path, $ext, $width, $height, [125,350]);
        }
    } else {
        $return['error'] = 'File cannot be saved !';
    }

    return $return;
}

function wosmpl_remove_files($pid)
{
    if ($file = get_post_meta($pid, 'wosmpl_partner_pict', true)) {
        $file = ABSPATH.\substr($file, 1);

        wp_delete_file($file);

        // @see in wosmpl_upload_file(), the wosmpl_reduce_image() call
        wp_delete_file(\str_replace('.', '-125.', $file));
        wp_delete_file(\str_replace('.', '-350.', $file));
    }
}
