<?php 
api::uploadfileapi(function($data){
	$uploads_dir = $_SERVER["DOCUMENT_ROOT"].'/public/uploads';
	if (!is_dir(dirname($uploads_dir))) mkdir(dirname($uploads_dir));
	if (!is_dir($uploads_dir)) mkdir($uploads_dir);
	$rEFileTypes = "/^\.(jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx|ppt|pptx|mp3|mp4){1}$/i";
	if($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
		if (preg_match($rEFileTypes, strrchr($_FILES["file"]["name"], '.'))) {
			$tmp_name = $_FILES["file"]["tmp_name"];
			$name = uniqid()."-".app::slug($_FILES["file"]["name"]);
			move_uploaded_file($tmp_name, "$uploads_dir/$name");
			return "/public/uploads/$name";
		}
	}
});
Route::isJs(function(){
ob_start();
?>
<div class="uploadfiletpl" ng-click="selectfile()">
<style type="text/css">
	.uploadfiletpl{
		display: inline-flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		width: 100px;
		height: 100px;
		border: 1px solid #aaa;
		color: #aaa;
		margin:5px;
		cursor: pointer;
	}
	.uploadfiletpl:hover{
		border: 1px solid #555;
		color: #555;
	}
</style>
<span ng-hide="etat!=''" style="font-size: 36px;" class="glyphicon glyphicon-upload"></span>
<span ng-show="etat!=''"> <span class="glyphicon glyphicon-{{etat}}"></span> {{progress}} %</span>
</div>
<?php
$code=ob_get_clean();
?>
<script>
app.directive('uploadfile', [function () {
	return {
		restrict: 'EA',
		template:<?= json_encode($code) ?>,
		replace:true,
		scope:{ngModel:"=?"},
		link: function ($scope, iElement, iAttrs) {
			$scope.etat = "";
			$scope.progress = 0;
			var file = $("<input name='file' type='file'>");
			HTMLInputElement.prototype.upload = function(api){
		        $scope.etat = "upload";
		        $scope.progress = 0;
		        $scope.$apply();
				var file = this.files[0];
				var xhr = new XMLHttpRequest();
				(xhr.upload || xhr).addEventListener('progress', function(e) {
				    var done = e.position || e.loaded
				    var total = e.totalSize || e.total;
					$scope.progress = Math.round(done/total*100)-1;
					if($scope.progress<0) $scope.progress = 0;
					$scope.$apply();
				});
				xhr.addEventListener('load', function(e) {
					try{
						response = JSON.parse(this.responseText);
					}catch(e){
						console.error(e);
						console.log(this.responseText);
					}
					$scope.etat = "";
					$scope.progress_up = 0;
					$scope.progress_down = 0;
					window.apiResponce(response,function(rep){
						$scope.ngModel = rep;
					});
					$scope.$apply();
				});
				xhr.open('post', '?api='+api, true);
				var formData = new FormData();
				formData.append('file', file);
				xhr.send(formData);
			}
			file.change(function(){
				this.upload("uploadfileapi");
			});
			$scope.selectfile = function(){
				if ($scope.etat == "") {
					file.trigger("click");
				}
			};
		}
	};
}])	
</script>	
<?php
});
