<?php

define('_JEXEC', 1);

define('JPATH_BASE', dirname(dirname(dirname(dirname(__FILE__)))));
require_once JPATH_BASE . '/includes/defines.php';
require_once JPATH_BASE . '/includes/framework.php';
$app = JFactory::getApplication('site');


use Joomla\CMS\Filesystem\File;


// var_dump(function_exists('gd_info')); // check GD extension installed and enabled on php
// var_dump(function_exists('getimagesize'));
// die();

$filename = __DIR__ . '/log.txt';
// file_put_contents($filename, '$_FILES = ' . print_r($_FILES, True) . "\n", FILE_APPEND);
// file_put_contents($filename, '$_POST = ' . print_r($_POST, True) . "\n", FILE_APPEND);
// file_put_contents($filename, '$_req = ' . file_get_contents( 'php://input' ) . "\n", FILE_APPEND);
// file_put_contents($filename, 'input files = ' . print_r($app->input->files->get('atachedfile'), True) . "\n", FILE_APPEND);



function getName($n)
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $randomString = '';
    for ($i = 0; $i < $n; $i++)
    {
        $index = rand(0, strlen($characters) - 1);
        $randomString .= $characters[$index];
    }
    return $randomString;
}



$file = $app->input->files->get('atachedfile');


$info = pathinfo($file['name']);
if(isset($info['extension']))
{
    $ext = $info['extension']; // get the extension of the file
    $newname = getName(10) . ".$ext";
    $target = dirname(dirname(__FILE__)) . '/files/' . $newname;

    $allowUnsafe = false;

    // if (move_uploaded_file($file['tmp_name'], $target))
    if(JFile::upload($file['tmp_name'], $target, false, $allowUnsafe))
    {
        if(function_exists('gd_info') && !function_exists('compress_image'))
        {
            function compress_image($src, $dest , $quality) 
            {
                $info = getimagesize($src);
             
                if ($info['mime'] == 'image/jpeg') 
                {
                    $image = imagecreatefromjpeg($src);
                }
                elseif ($info['mime'] == 'image/gif') 
                {
                    $image = imagecreatefromgif($src);
                }
                elseif ($info['mime'] == 'image/png') 
                {
                    $image = imagecreatefrompng($src);
                }
                else
                {
                    die('Unknown image file format');
                }
             
                //compress and save file to jpg
                imagejpeg($image, $dest, $quality);
             
                //return destination file
                return $dest;
            }
            compress_image($target, $target, 30);
        }
        echo $newname;
        // file_put_contents($filename, 'File is valid, and was successfully uploaded'. "\n", FILE_APPEND);
    } 
    else
    {
        // file_put_contents($filename, 'Upload failed'. "\n", FILE_APPEND);
    }
}

?>