<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');

// include composer autoload
require getcwd() . '/vendor/autoload.php';
// import the Intervention Image Manager Class
use Intervention\Image\ImageManager;

require_once(getcwd() . '/_connect.php');

define('PUBLIC_DIR', '/home/webjeban/jeban-2017/public/');
define('PUBLIC_URI', 'https://www.jeban.com/');

$dimension = $_GET['d'];
$dimensions = explode('x', $dimension);

$product_id = (int) $_GET['p'];

$width = (int) $dimensions[0];
$height = (int) $dimensions[1];

if (($width == 0) || ($height == 0) || ($product_id == 0)) {
	die('Invalid dimension.');
}

$imagefolder = PUBLIC_DIR . 'userfiles/thumbs/products';
if (file_exists($imagefolder) == false) {
    mkdir($imagefolder);
    chmod($imagefolder, 0755);
}
$imagefolder .= '/' . $width . 'x' . $height;
if (file_exists($imagefolder) == false) {
    mkdir($imagefolder);
    chmod($imagefolder, 0755);
}

$original_img = 'https://www.jeban.com/images/flower.gif';
$thumb_img = $imagefolder . "/$product_id.jpg";
$thumb_url = str_replace(PUBLIC_DIR, PUBLIC_URI, $thumb_img);

if (file_exists($thumb_img) == true) {
    header("Location: $thumb_url");
} else {
	if ((int) $product_id == 0) {
	    header("Location: $original_img");
	}

    $sql = "SELECT
                product.img as product_image,
                product.pkid_prod as product_id
            FROM
                jb_product product
            WHERE
                product.pkid_prod = :productId
            LIMIT 0, 1";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':productId', $product_id);
    $stmt->execute();
    
    $row = $stmt->fetch();
            
    $product_image = $row['product_image'];

	$original_img = 'https://www.jeban.com/images/flower.gif';
    if ($product_image != '') {
		if (file_exists(PUBLIC_DIR . 'reviews/images/product/' . $product_image)) {
	        $original_img = PUBLIC_DIR . 'reviews/images/product/' . $product_image;
	    }
	}
	
	// create an image manager instance with favored driver
	$manager = new ImageManager(['driver' => 'gd']);

	// Create image instances
	$image = $manager->make($original_img)->resize($width, $height)->encode('jpg');

	// save file as jpg with medium quality
	$image->save($thumb_img, 90);
    
	header("Location: $thumb_url");
}
?>
