<?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);

$user_id = (int) $_GET['u'];

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

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

$imagefolder = PUBLIC_DIR . 'userfiles/thumbs/members';
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 . "/$user_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) $user_id == 0) {
	    header("Location: $original_img");
	}

    $sql = "SELECT avatar_url FROM users WHERE id = :userId LIMIT 0, 1";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':userId', $user_id);
    $stmt->execute();
    
    $row = $stmt->fetch();
            
    $product_image = $row['avatar_url'];
    $value = $user_id % 4;
	switch ($user_id % 4) {
		case 1:
			$original_img = 'https://www.jeban.com/uploads/avatars/-default-avatar-01.png';
			break;
		case 2:
			$original_img = 'https://www.jeban.com/uploads/avatars/-default-avatar-02.png';
			break;
		case 3:
			$original_img = 'https://www.jeban.com/uploads/avatars/-default-avatar-03.png';
			break;
		default:
			$original_img = 'https://www.jeban.com/uploads/avatars/-default-avatar-04.png';
			break;
	}
    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");
}
?>
