<?php

//  ----------------------------------------------------
// | Crop adjust page called via iframe from manage.php |
//  ----------------------------------------------------

$cms_root_path = "../../";
require_once($cms_root_path."includes/compatibility_includer.php");
$page_meta['title'] = 'Edit Page > Crop Adjust';
include($core_root_path .'admin/templates/adminheader.full.php');
use Mtc\Cms\Models\PageListItemData as PageListItemData;

unset($filename);
if (!empty($_POST['filename'])) {
	$filename = $_POST['filename'];
} elseif (!empty($_GET['filename'])) {
	$filename = $_GET['filename'];
}

// Get page_list_item_data
$page_list_item_data = PageListItemData::find($_GET['page_list_item_data_id']);
// Fetch the settings
$settings = json_decode($page_list_item_data->settings,true);
if ( !empty($settings) ) {
    if ( isset($settings["crop_adjust"]) ) {
    	// This will hold the image $image_folders['cms_images'] sizes that the image can be cropp adjusted
    	// These could have a set width and height that are more than 0
        $crop_adjust = $settings["crop_adjust"];
    }
}

if ( !isset($crop_adjust) ) {
	die("This image can't be adjusted!");
}

// Get first crop adust size
$image_cms_images_size = $crop_adjust[0];
// Check if other is selected via post select box
if ( isset($_POST['image_cms_images_size']) ) {
	for ($i=0; $i < count($crop_adjust); $i++) {
		if ( $crop_adjust[$i] == $_POST['image_cms_images_size'] ) {
			$image_cms_images_size = $_POST['image_cms_images_size'];
		}
	}
}

// ON POST
if (isset($_POST['submitBtn'])) {

	// get selected size params
	$resize = $image_folders['cms_images'][$image_cms_images_size];
	// refresh image unique name by removing old time() prepend and adding a new one
	$new_filename = CropAdjust::refreshImageUniqueName($filename);
	// raname current images with new name of there are no caching issues
	CropAdjust::renameAllImageSizes($image_folders['cms_images'], $filename, $new_filename);
	// save new image name
	$page_list_item_data->value = $new_filename;
	$page_list_item_data->save();

	// if the a specific crop area is selected
	if ( !empty($_REQUEST['jcropX']) || !empty($_REQUEST['jcropY']) || !empty($_REQUEST['jcropW']) || !empty($_REQUEST['jcropH']) ) {

		// crop via settings
		CropAdjust::recrop(
			$new_filename, // image filename
			$image_folders['cms_images']['original']['path'], // path from where to take an uncropped original
			$resize, // selected size params that the image needs to follow (width, height, path)
			$_REQUEST['jcropW'],
			$_REQUEST['jcropH'],
			$_REQUEST['jcropX'],
			$_REQUEST['jcropY']
		);

	} else {

		// resize via usual settings if crop area isn't selected
		k_resize_image(
			SITE_PATH."/".$image_folders['cms_images']['original']['path']."/".$new_filename,
			SITE_PATH."/".$resize['path']."/".$new_filename,
			$resize['width'],
			$resize['height'],
			$resize['crop'],
			0,
			$resize['quality'],
			$resize['crop_position']
		);

	}
	$filename = $new_filename;
}

$settings = json_decode($page_list_item_data->settings,true);
$original_size = get_image_size($image_folders['cms_images']['original']['path'],$filename);

?>

<link rel="stylesheet" href="css/style.css" media="screen" />
<link rel="stylesheet" href="css/style_custom.css" media="screen" />

<div id="cropAdjust">
	<h1>Crop Adjust</h1>
	<p>To adjust how the image is cropped you can click and drag over then original image, select the perfect crop location - then press 'Crop'. To revert to default crop state: don't draw the crop square and press crop.</p>

	<form action="" method="POST" class="el miniselector">
		<fieldset>
			<?php

			if ( count($crop_adjust) > 1 ) {
				?>
				<div class="row" >
			        <label for="image_cms_images_size">Size:</label>
			        <select id="image_cms_images_size" name="image_cms_images_size" onchange="this.form.submit()">
			        	<?php
			        	for ($i=0; $i < count($crop_adjust); $i++) {
			        		?>
			        		<option value="<?=$crop_adjust[$i]?>" <?=($image_cms_images_size == $crop_adjust[$i] ? "selected" : "")?>><?=$crop_adjust[$i]?></option>
			        		<?php
			        	}
			        	?>
			        </select>
			    </div>
		    	<?php
		    }
		    ?>

			<div class="original form-box">
				<h2>Original</h2>
				<div class="container">
					<img src="/<?=$image_folders['cms_images']['original']['path']?>/<?=$filename?>" id="jCropTarget" alt="recrop" style="width: <?=$original_size['width']?>px; max-width: <?=$original_size['width']?>px;" />
				</div>
		    </div>

		    <div class="result form-box">
		    	<h2>Result</h2>
		    	<img id="result-image" data-filename="<?=$filename?>" src="/<?=$image_folders['cms_images'][$image_cms_images_size]['path']?>/<?=$filename?>" style="max-width: 395px; max-height: 325px; height: auto;" />
		    </div>

		    <div class="btn-section">
		   		<input type="submit" class="button submit" name="submitBtn" value="Crop" id="cropButton" />
		   		<input type="button" class="button submit" name="submitBtn" value="Close" id="btn_cancel" onclick="parent.$.fancybox.close();" />
			</div>

		    <input type="hidden" id="aspectratio" value="<?=($image_folders['cms_images'][$image_cms_images_size]['width'] / $image_folders['cms_images'][$image_cms_images_size]['height'])?>" />
		    <input type="hidden" id="minwidth" value="0" />
		    <input type="hidden" id="minheight" value="0" />
		    <input type="hidden" name="image" value="/<?=$image_folders['cms_images']['original']['path']?>/<?=$filename?>" />
		    <input type="hidden" name="filename" value="<?=clean_page($filename)?>" />
		    <input type="hidden" name="jcropX" id="jcropX" value="0" />
		    <input type="hidden" name="jcropY" id="jcropY" value="0" />
		    <input type="hidden" name="jcropW" id="jcropW" value="0" />
		    <input type="hidden" name="jcropH" id="jcropH" value="0" />

	    </fieldset>
	</form>

	<link rel="stylesheet" href="/admin/js/libs/jcrop/jcrop.css" />
	<script type="text/javascript" src="/admin/js/libs/jcrop/jcrop.js"></script>
	<script type="text/javascript">
		// image crop
	    $('#jCropTarget').Jcrop({
	        onChange: updatePreview,
	        onSelect: updatePreview,
	        aspectRatio: $('#aspectratio').val(),
	        boxWidth: 395,
	       	boxHeight: 295,
		});

	    function updatePreview(c) {
	        $('#jcropW').val(c.w);
	        $('#jcropH').val(c.h);
	        $('#jcropX').val(c.x);
	        $('#jcropY').val(c.y);
	    };
	    // end of jCrop
	</script>
</div>
<?php
include($core_root_path .'admin/templates/adminfooter.full.php');
