<?php
/*$im = new imagick('file.pdf[0]');
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;*/
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

include ("config/conf.php");

if (!isset($_GET['f']) || empty($_GET['f'])) {
    header('HTTP/1.0 400 Bad Request');
    die('Missing parameter');
}

// 1. Проверяем в БД images icon на наличие $_GET['f'];
$_GET['f'] = str_replace("https://eurasiangroup.org", "", $_GET['f']);
$_GET['f'] = str_replace("http://eurasiangroup.org", "", $_GET['f']);
$result2 = $db->query("SELECT * FROM icons WHERE patch = '".$_GET['f']."' LIMIT 1");


if ($row2 = $result2->fetch_array()) {
	$img = $row2['img'];

	// 2. Если находим там путь, то просто отображаем тут картинку
	header('Content-Type: image/jpeg');
	$f = file_get_contents('..'.$img);
	echo $f;

} else {
	// 3. Если в БД ее еще нету, то ресайзим

	$im = new Imagick();
	//$im->setResolution(220, 311);     //set the resolution of the resulting jpg
	
	if(substr_count($_GET['f'], 'https://eurasiangroup.org') == 0){
		$im->readImage($_SERVER['DOCUMENT_ROOT'].'/'.$_GET['f'].'[0]');    //[0] for the first page
	} else {
		$_GET['f'] = str_replace("https://eurasiangroup.org", "", $_GET['f']);
		$_GET['f'] = str_replace("http://eurasiangroup.org", "", $_GET['f']);
		$im->readImage($_SERVER['DOCUMENT_ROOT'].'/'.$_GET['f'].'[0]');    //[0] for the first page
	}
	
	//$im->resizeImage(200, 300, Imagick::FILTER_LANCZOS,1, true);
	$im->setImageFormat('jpg');
	

	// 4. Записываем картинку на сервер
	$name_new_img = '/files/images_original/icon_'.microtime().'.jpg';
	$path_new_img = '..'.$name_new_img;
	$im->writeImage($path_new_img);

	// 5. Записываем имя name_new_img в таблицу
	
	$sql = "INSERT INTO icons (patch, img) VALUES ('".$_GET['f']."', '$name_new_img');";
	$result = $db->query($sql);
	$icon_id = $db->insert_id; 
	
	$sql = "INSERT INTO images (module, parent_id, img) VALUES 
	('icons', '$icon_id', '$name_new_img');";
	$result = $db->query($sql);
	
	// 6. Выводим картинку
	header('Content-Type: image/jpeg');
	$f = file_get_contents('..'.$name_new_img);
	echo $f;
}

/*
$im = new Imagick();
$im->setResolution(300, 300);     //set the resolution of the resulting jpg
$im->readImage('file.pdf[0]');    //[0] for the first page
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;*/

?>