<?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, ftp_directory
	FROM file_row_update
	INNER JOIN file_row USING(id_file_row)
	INNER JOIN file USING(id_file)
	INNER JOIN company USING(id_company)
	WHERE date_modified > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 7 DAY)
	OR file.date_processed > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 7 DAY)");

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

foreach($companies as $company)
{
	$id_company = $company['id_company'];
	$week_number = date('W');

	//make the csv in memory
	$f = fopen('php://temp/maxmemory:1048576', 'w');
	
	getRowsByCompanyCSV($id_company, $f, $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.\n";
		return;
	}
}

ftp_close($conn);

echo "DONE\n";

?>