<?php

include '../db.php';


//connect
$conn = ftp_connect(FTP_HOST, FTP_PORT);

if(!ftp_login($conn, FTP_USER, FTP_PASS)) 
{
	echo "Unable to login to FTP\n";
	return;
}

ftp_pasv($conn, true);
ftp_chdir($conn, FTP_DIR);



$stmt = $dbh->prepare(
	"SELECT DISTINCT id_company, name, ftp_directory
	FROM company
	WHERE id_company IN
	(
		SELECT DISTINCT(id_company)
		FROM file_row_update
		INNER JOIN file_row USING(id_file_row)
		INNER JOIN `file` USING(id_file)
		WHERE date_modified > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 7 DAY)
		OR file.date_processed > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 7 DAY)
		
		UNION
		
		SELECT DISTINCT(id_company)
		FROM `file`
		INNER JOIN file_row USING(id_file)
		WHERE id_file_row IN
		(
			SELECT id_file_row
			FROM file_row_update
			WHERE WEEK(date_modified) = WEEK(CURRENT_TIMESTAMP)
			AND YEAR(date_modified) = YEAR(CURRENT_TIMESTAMP)
		
			UNION
			
			SELECT id_file_row
			FROM file_row
			WHERE WEEK(date_processed) = WEEK(CURRENT_TIMESTAMP)
			AND YEAR(date_processed) = YEAR(CURRENT_TIMESTAMP)
		)
	)");

$stmt->execute();
$companies = $stmt->fetchAll(PDO::FETCH_ASSOC);


$num_companies_processed = 0;

foreach($companies as $company)
{
	$num_companies_processed++;
	echo "processing company $company[name]...";
	
	$id_company = $company['id_company'];
	$year = date('Y');
	$week_number = date('W');

	//make the csv in memory
	$f = fopen('php://temp/maxmemory:1048576', 'w');
	
	getRowsByCompanyCSV($id_company, $f, $year, $week_number);
	
	rewind($f);


	$remote_filename = $company['ftp_directory'] . '-' . date('Y-W') . '.csv';

	if(!ftp_fput($conn, $remote_filename, $f, FTP_ASCII))
	{
		echo "ERROR uploading file to ftp.\n";
		return;
	}
	
	echo "SUCCESS\n";
}

ftp_close($conn);

echo "DONE\n";

?>