<?php

try
{
  //error_reporting(E_ALL); ini_set('display_errors', 1);
	require_once "./pineapple.php";
  require_once "./mysql/helper.php";
	
  pineapple_html_begin("Pineapple PNP", "Pineapple BOM Extraction");

  $db = db_connect("pontech_pineapplepnp");
  //print ("<pre>"); print_r($GLOBALS); print ("</pre>");

	$error = "Unknown error while downloading a file.";
	if( !pineapple_user_session_no_feedback() )
	{
		$error = "You must be logged in as a valid user to use this feature.";
		goto error_file;
	}
	$email = $_SESSION['email'];
	
	if(isset($_GET['id'])) 
	{
		require_once "./pineapple_bom_tools.php";
		// if id is set then get the file with the id from database
		$id    = $_GET['id'];
		if(isset($_GET['order_id'])) {
			$order_id = $_GET['order_id'];
		}
		else{
			$order_id = "none";			
		}
		if( pineapple_admin_session_no_feedback() ) {
			$sql = "SELECT name, type, size, content FROM upload WHERE id = ?";
			$prepared_array = array( $id );
		}
		else {
			$sql = "SELECT name, type, size, content FROM upload WHERE id = ? and email = ?";
			$prepared_array = array( $id, $email );
		}
		
		$sth = $db->prepare($sql);
		$success = $sth->execute($prepared_array);
		$row_count = $sth->rowCount();

		if( $row_count <= 0 ) {
			$error = "The database return zero files associated with the account that has the e-mail address $email.";
			goto error_file;
		}
		
		$row = $sth->fetch(PDO::FETCH_NUM);
		$name = $row[0];
		$type = $row[1];
		$size = $row[2];
		//$content = $row[3];
		extract_bom_from_zip($row[0], $row[3]);
		
		goto exit_page;
	}
	else {
		$error = "The file id was not specified.  Account email: $email";
	}
error_file:

	$size = strlen($error);
	$type = "text/csv";
	$name = "pineapplepnp_download_error.txt";
	
	echo($error);
	goto exit_page;

exit_page:
  $db = NULL;
	pineapple_script_end();
	pineapple_html_end();
}
catch (PDOException $e)
{
  //print ("<br />$e");
}
