<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
ini_set('memory_limit', '256M');
require('connect.php');
include('header.php');
class ResizeImage
{
	private $ext;
	private $image;
	private $newImage;
	private $origWidth;
	private $origHeight;
	private $resizeWidth;
	private $resizeHeight;

	/**
	 * Class constructor requires to send through the image filename
	 *
	 * @param string $filename - Filename of the image you want to resize
	 */
	public function __construct( $filename )
	{
		if(file_exists($filename))
		{
			$this->setImage( $filename );
		} else {
			throw new Exception('Image ' . $filename . ' can not be found, try another image.');
		}
	}

	/**
	 * Set the image variable by using image create
	 *
	 * @param string $filename - The image filename
	 */
	private function setImage( $filename )
	{
		$size = getimagesize($filename);
		$this->ext = $size['mime'];

		switch($this->ext)
	    {
	    	// Image is a JPG
	        case 'image/jpg':
	        case 'image/jpeg':
	        	// create a jpeg extension
	            $this->image = imagecreatefromjpeg($filename);
	            break;

	        // Image is a GIF
	        case 'image/gif':
	            $this->image = @imagecreatefromgif($filename);
	            break;

	        // Image is a PNG
	        case 'image/png':
	            $this->image = @imagecreatefrompng($filename);
	            break;

	        // Mime type not found
	        default:
	            throw new Exception("File is not an image, please use another file type.", 1);
	    }

	    $this->origWidth = imagesx($this->image);
	    $this->origHeight = imagesy($this->image);
	}

	/**
	 * Save the image as the image type the original image was
	 *
	 * @param  String[type] $savePath     - The path to store the new image
	 * @param  string $imageQuality 	  - The qulaity level of image to create
	 *
	 * @return Saves the image
	 */
	public function saveImage($savePath, $imageQuality="100", $download = false)
	{
	    switch($this->ext)
	    {
	        case 'image/jpg':
	        case 'image/jpeg':
	        	// Check PHP supports this file type
	            if (imagetypes() & IMG_JPG) {
	                imagejpeg($this->newImage, $savePath, $imageQuality);
	            }
	            break;

	        case 'image/gif':
	        	// Check PHP supports this file type
	            if (imagetypes() & IMG_GIF) {
	                imagegif($this->newImage, $savePath);
	            }
	            break;

	        case 'image/png':
	            $invertScaleQuality = 9 - round(($imageQuality/100) * 9);

	            // Check PHP supports this file type
	            if (imagetypes() & IMG_PNG) {
	                imagepng($this->newImage, $savePath, $invertScaleQuality);
	            }
	            break;
	    }

	    if($download)
	    {
	    	header('Content-Description: File Transfer');
			header("Content-type: application/octet-stream");
			header("Content-disposition: attachment; filename= ".$savePath."");
			readfile($savePath);
	    }

	    imagedestroy($this->newImage);
	}

	/**
	 * Resize the image to these set dimensions
	 *
	 * @param  int $width        	- Max width of the image
	 * @param  int $height       	- Max height of the image
	 * @param  string $resizeOption - Scale option for the image
	 *
	 * @return Save new image
	 */
	public function resizeTo( $width, $height, $resizeOption = 'default' )
	{
		switch(strtolower($resizeOption))
		{
			case 'exact':
				$this->resizeWidth = $width;
				$this->resizeHeight = $height;
			break;

			case 'maxwidth':
				$this->resizeWidth  = $width;
				$this->resizeHeight = $this->resizeHeightByWidth($width);
			break;

			case 'maxheight':
				$this->resizeWidth  = $this->resizeWidthByHeight($height);
				$this->resizeHeight = $height;
			break;

			default:
				if($this->origWidth > $width || $this->origHeight > $height)
				{
					if ( $this->origWidth > $this->origHeight ) {
				    	 $this->resizeHeight = $this->resizeHeightByWidth($width);
			  			 $this->resizeWidth  = $width;
					} else if( $this->origWidth < $this->origHeight ) {
						$this->resizeWidth  = $this->resizeWidthByHeight($height);
						$this->resizeHeight = $height;
					}  else {
						$this->resizeWidth = $width;
						$this->resizeHeight = $height;
					}
				} else {
		            $this->resizeWidth = $width;
		            $this->resizeHeight = $height;
		        }
			break;
		}

		$this->newImage = imagecreatetruecolor($this->resizeWidth, $this->resizeHeight);
    	imagecopyresampled($this->newImage, $this->image, 0, 0, 0, 0, $this->resizeWidth, $this->resizeHeight, $this->origWidth, $this->origHeight);
	}

	/**
	 * Get the resized height from the width keeping the aspect ratio
	 *
	 * @param  int $width - Max image width
	 *
	 * @return Height keeping aspect ratio
	 */
	private function resizeHeightByWidth($width)
	{
		return floor(($this->origHeight/$this->origWidth)*$width);
	}

	/**
	 * Get the resized width from the height keeping the aspect ratio
	 *
	 * @param  int $height - Max image height
	 *
	 * @return Width keeping aspect ratio
	 */
	private function resizeWidthByHeight($height)
	{
		return floor(($this->origWidth/$this->origHeight)*$height);
	}
}

date_default_timezone_set("Europe/Athens");
if(isset($_GET['fid'])){
	$qry = "SELECT picture FROM control_form WHERE id=".$_GET['fid'];
	$res = mysqli_query($dbC, $qry);
	$row = mysqli_fetch_array($res);
	if(isset($_POST['submit'])){
		$sqry = "UPDATE control_form SET picture='".$_POST['picture']."' WHERE id=".$_GET['fid'];
		if(mysqli_query($dbC, $sqry)){
			$url = "$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&status=1";
			echo "<script>alertify.success('Η Ενέργεια ολοκληρώθηκε επιτυχώς!')</script>";
		} else {
			echo "<script>alertify.success('error: ".mysqli_error($dbC)."')</script>";
		}
	}
}
?>
<style>
.okbox{
      background: url('../img/tick.png') no-repeat;
      background-position:95% 50% !important;
      background-size:20px 20px;
  }
#filelist{
  margin-left:auto;
  margin-right:auto;
  max-width:280px;
}
    #main_wrap{
      max-width: 80%;
      margin-left: auto;
      margin-right: auto;
    }

    #main_wrap td,
    #main_wrap th {
      text-align: center !important;
    }
    #imgform {
      margin-left: auto;
      margin-right: auto;
    }
 #piczoom {
      position: fixed;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      background-color: rgba(0, 0, 0, 0.7);
      z-index: 999;
    }

    #piczoom img {
      height: 100%;
      cursor: pointer;
    }

    #pics img:hover {
      filter: brightness(50%);
      cursor: pointer;
    }

    #delphoto{
  color:red;
  position:relative;
   /*top:-5px; */
  left:18%;
}
#delphoto:hover{
  cursor:pointer;
  font-weight: 800;
}
</style>
  <script src="js/plupload.full.min.js"></script>
  <script src="js/jquery.plupload.queue/jquery.plupload.queue.js"></script>


<script>
    function zoom(url) {
      $('#piczoom').html('<img src="uploads/images/' + url + '" />');
      $('#piczoom').show();
    }
    function delphoto(pic){
    	filearr = JSON.parse($('#picinp').val());
    	filearr.splice(filearr.indexOf(pic) ,1);
    	$('#picinp').val(JSON.stringify(filearr));
    	// pic = pic.split('.');
    	// $('#'+pic[0]+' .pic').hide();
			$('#pics').find("[data-name='"+pic+"']").hide();
    }

$(document).ready(function(){
$('#piczoom').on('click', function() {
        $('#piczoom').hide();
      });
var uploader = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4',

        browse_button: 'pickfiles', // you can pass in id...
        container: document.getElementById('upcontainer'), // ... or DOM Element itself

        url: "js/upload.php",
        chunk_size: '1mb',

        filters: {
          max_file_size: '10mb',
          mime_types: [{
            title: "Image files",
            extensions: "jpg,gif,png"
          }, {
            title: "Zip files",
            extensions: "zip"
          }]
        },

        // Flash settings
        flash_swf_url: 'js/Moxie.swf',

        // Silverlight settings
        silverlight_xap_url: 'js/Moxie.xap',


        init: {
          PostInit: function() {
            document.getElementById('filelist').innerHTML = '';

            document.getElementById('uploadfiles').onclick = function() {
              uploader.start();
              return false;
            };
          },


          FilesAdded: function(up, files) {
            var filesarr = new Array();
            if($('#picinp').val()!=''){
              filesarr = JSON.parse($('#picinp').val());
            }
            plupload.each(files, function(file) {
              document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
              	if(filesarr.indexOf(file.name)==-1){
              		filesarr.push(file.name);
          		}
          		uploader.bind('UploadComplete', function() {
            		// if (uploader.files.length == (uploader.total.uploaded + uploader.total.failed)) {
                		$("#"+file.id).css({"color":"green", "font-weight" : "800"});
                		$("#"+file.id).addClass('okbox');
            		// }
        		});
            });
            $('#picinp').val(JSON.stringify(filesarr));
          },

          UploadProgress: function(up, file) {
            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
          },

          Error: function(up, err) {
						document.getElementById('filelist').innerHTML += "\nError #" + err.code + ": " + err.message;
						$("#"+file.id).css({"color":"red", "font-weight" : "800"});
          }
        }
      });

      uploader.init();
});


</script>



<div id="main_wrap">
<div id="piczoom" style="display:none;"></div>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
</form>
<?php

echo '<div id="filelist">Your browser doesn\'t have Flash, Silverlight or HTML5 support.</div>

          <div id="upcontainer">
            <a id="pickfiles" href="javascript:;" class="btn btn-default">Select files</a>
            <a id="uploadfiles" href="javascript:;" class="btn btn-default">Upload files</a>
          </div><br />';
          echo '<form method="POST"><input type="hidden" name="picture" id="picinp" value=\''.$row['picture'].'\' /><input type="submit" class="btn btn-default" name="submit" value="Αποθήκευση" /></form>';
 $pics = json_decode($row['picture']);
 if(sizeof($pics)>0){
echo "<div class='panel panel-default'>
				<div class='panel-heading'>
					Φωτογραφίες
				</div>
				<div class='panel-body'>";
 	 $ii=1;
 echo "<div id='pics'><div class'row'>";
 foreach($pics as $pic){
 try{
 	$resize = new ResizeImage('uploads/images/'.$pic);
 	$resize->resizeTo(300, 300, 'maxHeight');
 	$resize->saveImage('uploads/images/temp/'.$pic);
 	echo "<div class='pic col-sm-".(12/sizeof($pics))."' data-name='".$pic."'><center>
		<div class='row' style='margin-bottom:1rem;'>
			<div class='col-sm-12'>
				<button class='btn btn-danger' onclick=\"delphoto('".$pic."');\">Διαγραφή <i class='glyphicon glyphicon-remove' style=\"font-size:1rem;\"></i></button>
			</div>
		</div>
		<div class='row'>
			<div class='col-sm-12'>
				<img class='img-responsive' height=\"300\" onclick=\"zoom('".$pic."');\" src=\"uploads/images/temp/".$pic."\" />
			</div>
		</div>

	</center></div>";
 } catch (Exception $e) {
 	// echo 'Caught exception: ',  $e->getMessage(), "\n";
 }

 	if($ii%4==0){
 		echo "</div><div class='row'>";
 	}
 	$ii++;
 }
 echo "</div></div></div>";
 }
?>

</div>
