<?php 

ini_set('display_errors', '1');
ini_set('max_execution_time', '120');
ini_set('memory_limit','500M');
define('EXCEL_TABLE_START',6);
define('DATE_OUT_FORMAT','d.m.Y');
define('CELL_WIDTH', 12);

require_once("./vendor/autoload.php");
require_once("invoice_helpers.php");

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

if($_SERVER['REQUEST_METHOD'] === "OPTIONS"){ echo json_encode(array("1")); exit(1); }

/* HELPERS */
function nf($amount){
	return number_format($amount, 2, ".", ",");
}

function number_excell($number){
	return round($number, 2);
}

function array_key_exists_array($arr, $keys){
	foreach ($keys as $key) if(!isset($arr[$key])) return false;
	return true;
}

function validate_racuni($racuni){
	$check = ['broj_fakture','datum_fakture','iznos_pdv_hrk','iznos_pdv_eur','iznos_osnovica_hrk','iznos_osnovica_eur'];
	foreach ($racuni as $racun) if(!array_key_exists_array($racun, $check)) return false;
	return true;
}


if(isset($_POST['invoice_user']) &&
isset($_POST['office']) &&
isset($_POST['pos']) &&
isset($_POST['period']) &&
isset($_POST['dodatni_tekst']) &&
isset($_POST['format']) &&
in_array($_POST['format'], [INVOICE_EXPORT_EXCEL, INVOICE_EXPORT_PDF] )&&
isset($_POST['racuni']) &&
!empty($_POST['racuni']) &&
validate_racuni($_POST['racuni']) ){
	$data = $_POST;

	$display_invoice_user = $data['invoice_user'];
	$display_office = $data['office'];
	$display_pos = $data['pos'];
	$display_period = $data['period'];
	$dodatni_tekst = $data['dodatni_tekst'];
	$operater = $data['operater'];
	$format = $data['format'];
	$racuni = $data['racuni'];

} else {

	http_response_code(400);
	exit();

}

$time_created = (new DateTime("now", new DateTimeZone("Europe/Zagreb")))->format("d.m.Y H:i");
$broj_stavaka = count($racuni);

if($format == INVOICE_EXPORT_PDF){

	/* ===== AKO JE FORMAT PDF ===== */
	ob_start();
?><!DOCTYPE html>
<html>
	<head>
		<title>Blagajnicki izvjestaj</title>
		<meta http-equiv="Content-Type" content="text/html; charset=Windows-1250"/>
		<link rel="stylesheet" type="text/css" href="style/report-style.css" />
	</head>
	
<body>
	<script type='text/php'>
		if ( isset($pdf) ) { 
			$size = 9;
			$y = $pdf->get_height() - 30;
			$x = $pdf->get_width() - 60 - 9;
			$pdf->page_text($x, $y,'{PAGE_NUM}/{PAGE_COUNT}', 'helvetica', $size);
		} 
    </script>
    <h3>
    	Blagajnički izvještaj za datum <?=$display_period; ?> 
    	<span class="date-created">Datum kreiranja: <?=$time_created?></span>
    </h3>
    <div>
    	<table class="filters-table">
    		<tr>
				<td> Poslovnica </td>
				<td> POS </td>
				<td> Operater </td>
    		</tr>
    		<tr>
				<td> <?=$display_office; ?> </td>
				<td> <?=$display_pos; ?> </td>	
				<td> <?=$operater; ?> </td>			
    		</tr>
    	</table>
    </div>

    <div>
    	<table class="numbers-table">
    		<tr>
    			<td> R.br. </td>
				<td> Broj fakture </td>
				<td> Ime gosta </td>
				<td> Property </td>
				<td> Period </td>
				<td> Način plaćanja </td>
				<td> Valuta plaćanja </td>
				<td> Total EUR </td>
				<td> Total HRK </td>
    		</tr>
    		<?php 

    		$rbr = 1;
			$total_iznos_pdv_eur = 0;
			$total_iznos_pdv_hrk = 0;
			$total_iznos_osnovica_eur = 0;
			$total_iznos_osnovica_hrk = 0;
			$total_total_eur = 0;
			$total_total_hrk = 0;
    		foreach ($racuni as $racun) {
    			$date = new DateTime($racun['datum_fakture']);
				$broj_fakture = $racun['broj_fakture'];
				$datum_fakture = $date->format(DATE_OUT_FORMAT);
				$iznos_pdv_hrk = $racun['iznos_pdv_hrk'];
				$iznos_pdv_eur = $racun['iznos_pdv_eur'];
				$iznos_osnovica_hrk = $racun['iznos_osnovica_hrk'];
				$iznos_osnovica_eur = $racun['iznos_osnovica_eur'];
				$total_eur = $iznos_pdv_eur + $iznos_osnovica_eur ;
				$total_hrk = $iznos_pdv_hrk + $iznos_osnovica_hrk ;

				$total_iznos_pdv_eur +=  $iznos_pdv_eur;
				$total_iznos_pdv_hrk +=  $iznos_pdv_hrk;
				$total_iznos_osnovica_eur +=  $iznos_osnovica_eur;
				$total_iznos_osnovica_hrk +=  $iznos_osnovica_hrk;
				$total_total_eur +=  $total_eur;
				$total_total_hrk +=  $total_hrk;

				$ime_gosta = $racun["racun_info"]["guest_name"];
				$property = $racun["racun_info"]["property"];
				$property_unit = $racun["racun_info"]["property"];
				$period = $racun["racun_info"]["period"];
				$nacin_placanja = $racun["nacin_placanja"];
				$valuta_placanja =  $racun["valuta_placanja"];
				    			
  			?>
    		<tr>
    			<td> <?=$rbr?></td>
				<td> <?=$broj_fakture?></td>
				<td> <?=$ime_gosta?></td>
				<td> <?=$property?></td>
				<td> <?=$period?></td>
				<td> <?=$nacin_placanja?></td>
				<td> <?=$valuta_placanja?></td>
				<td> <?=nf($total_eur)?></td>
				<td> <?=nf($total_hrk)?></td>
    		</tr>

    		<?php 

    		$rbr += 1;
    	}
    	?>
    		<tr>
    			<td colspan="7"> Ukupno </td>
				<td> <?=nf($total_total_eur)?> </td>
				<td> <?=nf($total_total_hrk)?> </td>
    		</tr>
    	</table>
    </div>


    
	<p class="font-xsmall">
		<?=$dodatni_tekst?>
	</p>

</body>
</html>
<?php
	$html = ob_get_clean();
	if(!isset($_POST['debug'])){
		
		$options = new Dompdf\Options();
		$options->set('isHtml5ParserEnabled', true);
		$options->set('isPhpEnabled', true);

		$dompdf = new Dompdf\Dompdf($options);
		$dompdf->loadHtml($html);
		$dompdf->setPaper('A4', 'portrait');
		$dompdf->render();
		$file_name = "Izvjestaj";
		$dompdf->stream($file_name);
	} else {
		echo $html;
	}
	exit();

} else if( $format == INVOICE_EXPORT_EXCEL ) {
	/* ===== AKO JE FORMAT EXCEL ===== */

	/* postavi headere */
	header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	header('Content-Disposition: attachment;filename="01-simple.xlsx"');
	header('Cache-Control: max-age=0');

	/* === kreiraj sheet ======= */
	$spreadsheet = new Spreadsheet();
	$sheet = $spreadsheet->getActiveSheet();

	/* === postavi info ======= */
	$sheet->setCellValue('A1', 'Blagajniči izvještaj');
	$sheet->setCellValue('G1', 'Vrijeme kreiranja');
	$sheet->setCellValue('J1', $time_created);

	/* === postavi info o filerima tablice ======= */
	$filers = [
		[
			"Tvrtka",
			"Period",
			"Poslovnica",
			"Blagajna"
		], 
		[
			$display_invoice_user,
			$display_period,
			$display_office,
			$display_pos
		]
	];
	$sheet->fromArray(
	        $filers,  // The data to set
	        NULL,        // Array values with this value will not be set
	        'A3'         // Top left coordinate of the worksheet range where
	);



	/* === postavi head tablice ======= */
	$head = [
		[
			"Redni broj",
			"Broj fakture",
			"Ime gosta",
			"Property",
			"Property Unit",
			"Period",
			"Način plaćanja",
			"Valuta plaćanja",
			"Total EUR",
			"Total HRK"
		]
	];
	$sheet->fromArray(
	        $head,  // The data to set
	        NULL,        // Array values with this value will not be set
	        'A6'         // Top left coordinate of the worksheet range where
	);

	/* === POSTAVI VRIJEDNOSTI ======= */
	// postavi pogodno za excell
	$racuni_excell = [];
	foreach ($racuni as $i => $ra) {

		$date = new DateTime($ra['datum_fakture']);
		$godina = $date->format("Y");
		$mjesec = $date->format("m");

		$temp = [
			($i+1), 
			$ra["broj_fakture"],
			$ra["racun_info"]["guest_name"],
			$ra["racun_info"]["property"],
			$ra["racun_info"]["unit"],
			$ra["racun_info"]["period"],
			$ra["nacin_placanja"],
			$ra["valuta_placanja"],
			number_excell(($ra["iznos_osnovica_eur"] + $ra["iznos_pdv_eur"])),
			number_excell(($ra["iznos_osnovica_hrk"] + $ra["iznos_pdv_hrk"]))
		];
		array_push($racuni_excell, $temp);
	}

	$sheet->fromArray(
	        $racuni_excell,  // The data to set
	        NULL,        // Array values with this value will not be set
	        'A7'         // Top left coordinate of the worksheet range where
	    );

	/* === IZRACUNAJ TOTAL === */

	$last_h_col_cell = 'H'.($broj_stavaka+EXCEL_TABLE_START+1);
	$last_i_col_cell = 'I'.($broj_stavaka+EXCEL_TABLE_START+1);
	$last_j_col_cell = 'J'.($broj_stavaka+EXCEL_TABLE_START+1);

	$sheet->setCellValue($last_i_col_cell, '=SUM(I'.EXCEL_TABLE_START.':I'.($broj_stavaka+EXCEL_TABLE_START).')');
	$sheet->setCellValue($last_j_col_cell, '=SUM(J'.EXCEL_TABLE_START.':J'.($broj_stavaka+EXCEL_TABLE_START).')');

	$sheet->setCellValue($last_h_col_cell, 'UKUPNO');

	$sheet->setCellValue( 'I'.($broj_stavaka+EXCEL_TABLE_START+3) , "Operater");
	$sheet->setCellValue( 'J'.($broj_stavaka+EXCEL_TABLE_START+3) , $operater);
	$sheet->setCellValue( 'A'.($broj_stavaka+EXCEL_TABLE_START+4) , $dodatni_tekst);

	$cells = ['A','C','D','E','F','G','H','I','J','K'];


	$styleArray = [
	    'borders' => [
	        'allBorders' => [
	            'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
	            'color' => ['argb' => 'FF000000'],
	        ],
	    ],
	];

	$cells_style = 'A'.EXCEL_TABLE_START.':J'.($broj_stavaka+EXCEL_TABLE_START);

	$sheet->getStyle($cells_style)->applyFromArray($styleArray);

	foreach ($cells as $cell_temp) {
		$sheet->getColumnDimension($cell_temp)->setWidth(CELL_WIDTH);	
	}
	$sheet->getColumnDimension('B')->setWidth(19);

	$writer = new Xlsx($spreadsheet);
	$writer->save('php://output');
	exit();
	
}


?>

