<?php

use Utils\Utils;

error_reporting(-1);
require_once '../vendor/stefangabos/zebra_image/Zebra_Image.php';
require_once '../app/Utils.php';

$config = [
	'thumbSize' => 250
];

if (file_exists('../datas/config.php')) {
	include '../datas/config.php';
	$config = array_merge($config, $userConfig);
}

$getFilename = $_GET['filename'];
$baseDir = getcwd();

if (!Utils::isPathAuthorized($getFilename)) {
	die("ERROR 01: Unauthorized access!");
}

if (!is_dir('../cache/thumbs') && is_writable('.')) {
	mkdir('../cache/thumbs', 0700);
}

$pathInfos = pathinfo($getFilename);
$dirname = '../cache/' . str_replace('photos', 'thumbs', $pathInfos['dirname']);
$filename = $pathInfos['filename'];
$thumbname = '../cache/' . $dirname . '/' . $filename . '.' . $pathInfos['extension'] . '.webp';

if (file_exists($thumbname)) {
	$fd = fopen($thumbname, "r");
	$cacheContent = fread($fd, filesize($thumbname));
	fclose($fd);
	header('Content-type: image/webp');
	echo ($cacheContent);
	exit;
}

if (!is_readable($getFilename) || !is_file($getFilename)) {
	header('Content-type: image/svg+xml');
	$cannotopenImg = file_get_contents('assets/images/cannotopen.svg');
	echo $cannotopenImg;
	exit;
}

if (!file_exists($dirname)) {
	if (!mkdir($dirname, 0700, true)) {
		die('We can\'t create dir, check permission of parent directory.');
	}
}

$image = new Zebra_Image();
$image->auto_handle_exif_orientation = true;
$image->source_path = $getFilename;
$image->target_path = $thumbname;

if (!$image->resize($config['thumbSize'], $config['thumbSize'], ZEBRA_IMAGE_CROP_CENTER)) {
} else {
	header('Content-type: image/webp');
	echo file_get_contents($thumbname);
	exit();
}