<?php

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

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

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


	page_header( "", $cxn );



	crash_if_missing( $request_id, "request_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
	{
		$query = "SELECT MAX(file_number) as num FROM attachments WHERE request_id = ".$request_id;			
		
		if (query_has_rows( $query, $cxn ))
		{
			$result = run_query( $query, $cxn );

			$data = get_row( $result );

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


		$query = "SELECT random_file_number2 FROM request WHERE request_id = ".$request_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 task SET random_file_number = ".$random_file_number." WHERE id = ".$id;
//				
//			$result = run_query( $query, $cxn );
//		}		
		


			/* extract the file extension */

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



			/* upload the file */

		$new_dir = $pathroot."/attachments/request_".$request_id."_".$random_file_number2;
		
		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();
    		}
    
    			/* save a record to the database */
    
    		$datetime_uploaded = date("Y-m-d H:i:s");
    
    
    		$query = "INSERT INTO downloads (request_id, file_number, filename, datetime_uploaded) values (".$request_id.", ".$file_number.", '".$filename."', '".$datetime_uploaded."')";
    
    		$result = run_query( $query, $cxn );
    
    		echo black( "<br>File uploaded successfully<br><br><br>" );
        }
	}

	echo show_link( "Back", "attachments.php", "requestid", $request_id );


	echo "</body>";
	
?>