<?php

function send_error_die($msg){
	die(json_encode(array('R'=>'ERR','MSG'=>$msg)));
}

if(!is_user_logged_in()){
	send_error_die(__('You are not logged in.','act'));
}


$upload_dir = wp_upload_dir();
$base_dir = $upload_dir['basedir'].'/profil_avatar';
$front_dir = $upload_dir['baseurl'].'/profil_avatar';

if (!file_exists($base_dir)) {
    mkdir($base_dir, 0777);
}

$base_dir .= '/';
$front_dir .= '/';
$user_id = get_current_user_id();
$new_filename = '';

if(isset($_FILES["myfile"]))
{
	$ret = array();

	$error =$_FILES["myfile"]["error"];
	if(!is_array($_FILES["myfile"]["name"]))
	{
 	 	$fileName = $_FILES["myfile"]["name"];
 	 	$ext = '.'.pathinfo($fileName, PATHINFO_EXTENSION);
 	 	$new_filename = $user_id.'-'.date('YmdHis').$ext;
 		move_uploaded_file($_FILES["myfile"]["tmp_name"],$base_dir.$new_filename);
    	$ret[]= $fileName;
	}
	
	$old = get_user_meta( $user_id, 'avatar_url', true); 

	if(!empty($old) && is_array($old)){
		if (file_exists($old['backend'])) {
		   unlink($old['backend']);
		}
	}


	 update_user_meta( $user_id, 'avatar_url', array('backend' => $base_dir.$new_filename , 'frontend'=> $front_dir.$new_filename)); 
	
    die($front_dir.$new_filename);
} else {
	send_error_die(__('No files found','act'));
}
?>