<?php

if (!empty($_FILES['upload'])) {
    require_once '../vendor/autoload.php';

    // Load environment variables.
    $dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../');
    $dotenv->safeLoad();
    upload($_FILES['upload'], $_ENV['UPLOAD_TMP_FQ_PATH'], isset($_POST['filename']) ? $_POST['filename'] : null);
}

function delete_dir($dir)
{
    if (!is_dir($dir)) return false;

    if (substr($dir, strlen($dir) - 1, 1) != '/') {
        $dir .= '/';
    }
    $files = glob($dir . '*', GLOB_MARK);
    foreach ($files as $file) {
        if (is_dir($file))
            delete_dir($file);
        else
            delete_file($file);
    }
    rmdir($dir);
}

function delete_file($file)
{
    if (!file_exists($file)) return false;

    unlink($file);
}

function upload($input, $dest_dir, $filename = null)
{
    $filetype = strtolower(pathinfo($input['name'], PATHINFO_EXTENSION));

    switch ($filetype) {
        case 'png':
        case 'jpg':
        case 'jpeg':
            if (check_image_upload($dest_dir, $filetype, $input))
                move_uploaded_file($input['tmp_name'], $dest_dir . ($filename ? $filename . '.' . $filetype : $input['name']));
            else
                return '';
            break;
        case 'csv':
            if (check_csv_upload($input))
                move_uploaded_file($input['tmp_name'], $dest_dir . ($filename ? $filename . '.' . $filetype : $input['name']));
            else
                return '';

            break;
        default:
            # code...
            break;
    }

    if ($filename)
        return basename($filename . '.' . $filetype);
    else
        return basename($input['name'] . '.' . $filetype);
}

function crop_image($img_path, $x, $y, $height, $width)
{
    //$dest = $_ENV['UPLOAD_TMP_FQ_PATH'];
    $dest = '/tmp/';
    // Get the image type
    $imageType = exif_imagetype($img_path);

    // Create an image resource from the source image
    switch ($imageType) {
        case IMAGETYPE_JPEG:
            $sourceImage = imagecreatefromjpeg($img_path);
            break;
        case IMAGETYPE_PNG:
            $sourceImage = imagecreatefrompng($img_path);
            break;
        default:
            return false; // Unsupported image type
    }

    if (!$sourceImage)
        return false; // Failed to create image resource

    // Create a new image resource for the cropped image
    $croppedImage = imagecreatetruecolor($width, $height);

    // Copy the cropped portion from the source image to the destination image
    imagecopy($croppedImage, $sourceImage, 0, 0, $x, $y, $width, $height);

    // Save the cropped image to the destination path
    switch ($imageType) {
        case IMAGETYPE_JPEG:
            imagejpeg($croppedImage, $img_path);
            break;
        case IMAGETYPE_PNG:
            imagepng($croppedImage, $dest);
            break;
        case IMAGETYPE_GIF:
            imagegif($croppedImage, $dest);
            break;
    }

    // Free up memory
    imagedestroy($sourceImage);
    imagedestroy($croppedImage);

    return true; // Cropping successful
}

/*
 * Reads in file contents and stores as a single string.
 */
function read_file_one_string($file_path)
{
    $fs = fopen($file_path, 'r');
    $string = fread($fs, filesize($file_path));
    return $string;
}

function read_file($file_path)
{
    $fs = fopen($file_path, 'r');
    return $fs;
}

function extract_content_from_tag($string, $start, $end)
{
    $ini = strpos($string, $start);
    if ($ini != 0)
        return "nope";

    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

function check_image_upload($target, $filetype, $image)
{
    return true;
}

function check_csv_upload($target)
{
    return true;
}

function pretty_dump($arr)
{
    echo '
    <pre>
        ' . print_r($arr) . '
    </pre>
    ';
}
