<?php

	include "library.php";
	
	$cxn = start_code();
	
    $cxn_common = db_common_login();
	

	$pathroot = "/home/academi1/public_html/melbourneparaplanning/workflow";
	
	
		/* get variables */

	$resource_group_id = val( $_SESSION, "resource_group_id" );


	page_header( "", $cxn, $cxn_common );

		/* check the member id  */

	crash_if_missing( $resource_group_id, "resource_group_id is not set in upload files", $cxn );

	if ($_FILES['file']['name'] == "")
		echo black( "No file is selected. Please go back to the Upload Files screen and click on the 'Choose File' button.<br><br>" );
	else
	{
			/* get the new photo number */

		$query = "SELECT MAX(file_number) as num FROM resource_file WHERE resource_group_id = ".$resource_group_id;			
		
		if (query_has_rows( $query, $cxn ))
		{
			$result = run_query( $query, $cxn );

			$data = get_row( $result );

//		$photo_number = $data['max_photo_number'] + 1;

			$file_number = $data['num'] + 1;
		}
		else
			$file_number = 1;


		$query = "SELECT random_file_number FROM resource_groups WHERE id = ".$resource_group_id;

		$result = run_query( $query, $cxn );

		$data = get_row( $result );
		
		$random_file_number = $data['random_file_number'];
		
		if ($random_file_number == "")
		{
			$random_file_number = rand(100000000, 999999999);		
			
			$query = "UPDATE resource_groups SET random_file_number = ".$random_file_number." WHERE id = ".$resource_group_id;
				
			$result = run_query( $query, $cxn );
		}		
		

		$filename = $_FILES['file']['name'];



			/* upload the file */

		$new_dir = $pathroot."/resource_files/resource_group_".$resource_group_id."_".$random_file_number;
		
		if (! file_exists( $new_dir))
			mkdir( $new_dir );
		
		$destfile = $new_dir."/".$filename;

        if (file_exists( $destfile ))
            echo black( "<br>File already exists on the server. To upload a new version, rename the old file first.<br><br><br>" );
        else
        {
    		if (move_uploaded_file( $_FILES['file']['tmp_name'], $destfile ))
    			chmod( $destfile, 0744 );
    		else
    		{
    			echo black( "The file that you've selected could not be uploaded" );
    			exit();
    		}
    
    
    		$datetime_uploaded = date("Y-m-d H:i:s");
    
    
    		$query = "INSERT INTO resource_file (resource_group_id, file_number, filename, datetime_uploaded) values (".$resource_group_id.", ".$file_number.", '".$filename."', '".$datetime_uploaded."')";
    
    		$result = run_query( $query, $cxn );
    

    		echo black( "<br>File uploaded successfully<br><br><br>" );
        }
	}


	echo show_home_link();
	

	echo "</body>";
?>

