<?php
	require_once( "../local.config.inc.php" );
	FNTH_class( "CSV" );

	define( "COL_MONTH" , "Hónap" );
	define( "COL_NUM" , "Ajánlattételek száma" );
	define( "COL_ACCEPTED_NUM" , "Elfogadottak" );
	define( "COL_ACCEPTED_PERCENT" , "Százalékban" );

	$filters = array();
	$filters["job_version"] = "job_id in (select job_id from jobs where job_version = 3 and poster_acknowledged and admin_acknowledged)";

	$query = sprintf( "select
		date_trunc( 'month' , ctstamp ) as ym,count(*) as num from job_quotes where %s group by date_trunc( 'month' , ctstamp ) order by date_trunc( 'month' , ctstamp )",
		implode( " and " , $filters ) );
	$all_results = FNTH_db_get_associative( $query , "ym" , "num" );

	$filters["accepted"]="accepted_at is not null";
	$query = sprintf( "select
		date_trunc( 'month' , ctstamp ) as ym,count(*) as num from job_quotes where %s group by date_trunc( 'month' , ctstamp ) order by date_trunc( 'month' , ctstamp )",
		implode( " and " , $filters ) );

	$accepted_results = FNTH_db_get_associative( $query , "ym" , "num" );
	
	$csv = new FNTHCSV();
	$csv_type = (isset( $_SERVER["HTTP_USER_AGENT"] ) && stripos( $_SERVER["HTTP_USER_AGENT"] , "linux" )!==false) ? "gnumeric" : "excel";
	$csv->setType( $csv_type );

	$csv->addColumn( COL_MONTH );
	$csv->addColumn( COL_NUM );
	$csv->addColumn( COL_ACCEPTED_NUM );
	$csv->addColumn( COL_ACCEPTED_PERCENT );

	header( "Content-Type: application/vnd.ms-excel" );
	foreach ($all_results as $key => $v) {
		$item = array();
		$item[COL_MONTH]=substr( $key , 0 , 7 );
		$item[COL_NUM]=$v;
		$item[COL_ACCEPTED_NUM]=(isset( $accepted_results[$key] )) ? $accepted_results[$key] : 0;
		$item[COL_ACCEPTED_PERCENT]=sprintf( "%d" , ($item[COL_ACCEPTED_NUM] * 100.0 / $item[COL_NUM]) );
		$csv->addRow( $item );
	}

	echo $csv->exportToString();
?>
