<?php
	require_once '../../autoload.php';

	$result = array (
			"status"	=> 'KO',
			"filename"	=> ''
	);

	error_log ( "=== prepare_new_version ===" );

	$doc_id				= $_POST["doc_id"];

	error_log ( " doc_id : " .$doc_id );

	$pdo = getPDO ();
	
	if ( $pdo )
	{
		$sql = "select sourcefile, folder from document where id = :doc_id";
        
        $s0 = $pdo->prepare ( $sql );
        $s0->bindParam ( ":doc_id", $doc_id );

        if ( $s0->execute () )
        {
            $d0 = $s0->fetchAll ( PDO::FETCH_ASSOC );

            $filename   = $d0[0]['sourcefile'];
            $folder     = $d0[0]['folder'];

            $fullFileName = $GLOBALS["document_storage"] . "/" . $folder ."/" .$filename;

            error_log ( " fullFileName : " .$fullFileName );


            $uploads_dir 	= $GLOBALS["upload_folder"];
            $final_filename = date('YmdHis')."_".basename($filename);
			$upload_file 	= $uploads_dir."/".$final_filename;

			error_log ( "upload_file : " . $upload_file );

			if (!is_dir($uploads_dir)) 
			{
				mkdir($uploads_dir, 0777, true);	
			}

			if ( copy ( $fullFileName, $upload_file) )
			{
				$result['status'] = 'OK';
				$result['filename'] =  $final_filename;
			}
        }
	}

	header('Content-type: application/json');
	
	echo json_encode ( $result );
?>