<?php

require_once dirname(__FILE__) . '/PhpExcell/Classes/PHPExcel/IOFactory.php';


$data = array();
$date_from = date("Y-M-D");
$date_to = date("Y-m-d");

$tmp3 = array();
$vat_id;


// Ustawienia daty
if (!$_GET ['date_from']) {
	$date_from = date("Y-M-01");
} else {
	$date_from = $_GET ['date_from'];
}
if (!$_GET ['date_to']) {
	$date_to = date("Y-m-d");
} else {
	$date_to = $_GET ['date_to'];
}
// formatowanie daty
$Calendar_daFormat = str_replace("d", "%d", str_replace("m", "%m", str_replace("Y", "%Y", $GLOBALS ['timedate']->get_date_format())));
$date_from = $GLOBALS ['timedate']->to_display_date($date_from);
$date_to = $GLOBALS ['timedate']->to_display_date($date_to);
$date = new DateTime ();
$current_date_formatted = $date->format('d.m.Y');


global $app_list_strings;
global $mod_strings;
$db = $GLOBALS ['db'];

$subquery = "SELECT id 
		FROM documents
		WHERE deleted= '0'
		AND register_date >= STR_TO_DATE('" . $date_from . "','%d.%m.%Y')	
		AND register_date <= STR_TO_DATE('" . $date_to . "','%d.%m.%Y') ";

$query = "	SELECT  	
	dcn.id document_id,
	dcn.parent_id,
	dcn.document_number,
	dcn.document_date,
	dcn.category_id, 
	dcn.active_date,
	dcn.register_date,
	acc.name,
	acc.register_address_city,
	acc.register_address_postalcode,
	acc.register_address_street,
	acc.to_vatid
   
FROM
    documents_accounts da
        LEFT JOIN
    documents dcn ON da.document_id = dcn.id

        LEFT JOIN
    accounts acc ON da.parent_id = acc.id
WHERE
    da.parent_type = 'Account'
        AND da.deleted = '0'
        AND (category_id = 'invoice_costs'
        or category_id = 'invoice_goods')
        AND dcn.id IN (SELECT 
            id
        FROM
            documents
        WHERE
            deleted = '0'
                
				
				AND dcn.register_date IS NOT NULL
				AND dcn.id IN (" . $subquery . "))
ORDER BY dcn.document_name";


if (isset($_GET ['category_id'])) {
	foreach ($_GET ['category_id'] as $selectedOption) {
		array_push($category, $selectedOption);
	}
}

$rows = $db->query($query);
while ($r = $db->fetchByAssoc($rows)) {
	$row = array();
	$queryvat = 'SELECT  
			id, 
			document_id, 
			vat_value, 
			vat_id, 
			netto, 
			vat 
	FROM 
			documents_vat where document_id = "' . $r ['document_id'] . '" 
			AND deleted = "0" 
			AND netto > "0"  
			ORDER BY position';

	$rowsv = $db->query($queryvat);
	$row ['vaty'] = array();
	$row ['vatsumapozycja'] = 0;
	$sumabrutto = 0;
	while ($rr = $db->fetchByAssoc($rowsv)) {
		$tmp2 = array();
		$tmp2 ['vat_value'] = $rr ['vat_value'];
		$tmp2 ['vat_id'] = $rr ['vat_id'];
		$tmp2 ['netto'] = $rr ['netto'];
		$tmp2 ['vat'] = $rr ['vat'];
		$tmp2 ['sumabrutto'] += $rr['vat'] + $rr['netto'];
		$row ['vatsumapozycja'] += $rr ['vat'];
		$row ['value'] += $rr ['netto'] + $rr ['vat'];
		$row ['vaty'] [] = $tmp2;
		if (isset($tmp3 [$rr ['vat_value']])) {
			$tmp3 [$rr ['vat_value']] ['sumanetto'] += $rr ['netto'];
			$tmp3 [$rr ['vat_value']] ['sumavat'] += $rr ['vat'];
			$sumanetto += $rr ['netto'];
			$sumavat += $rr['vat'];
			$sumabrutto += $sumanetto + $sumavat;
		} else {
			$tmp3 [$rr ['vat_value']] = array();
			$tmp3 [$rr ['vat_value']] ['sumanetto'] = $rr ['netto'];
			$tmp3 [$rr ['vat_value']] ['sumavat'] = $rr ['vat'];
			$sumanetto += $rr ['netto'];
			$sumavat += $rr['vat'];
			$sumabrutto += $sumanetto + $sumavat;
		}
	}

	$row ['document_id'] = $r ['document_id'];
	$row ['id'] = $r ['id'];
	$row ['document_number'] = $r ['document_number'];
	$row ['name'] = $r ['name'];
	$row ['register_address_postalcode'] = $r ['register_address_postalcode'];
	$row ['register_address_city'] = $r ['register_address_city'];
	$row ['register_address_street'] = $r ['register_address_street'];
	$row ['document_date'] = $r ['document_date'];
	$row ['category_id'] = $r ['category_id'];
	$row ['active_date'] = $r ['active_date'];
	$row ['to_vatid'] = $r ['to_vatid'];
	$row ['register_date'] = $r ['register_date'];
	$data [] = $row;
	//$wartosc += $row ['value'];
	$sumvat += $row ['vatsumapozycja'];
}

foreach ($tmp3 as $key => $value) {
	if ($value ['sumavat'] == 0) {
		$tmp3 [$key] ['sumavat'] = NULL;
	}
}
// Create new PHPExcel object
echo date('H:i:s'), " Create new PHPExcel object", EOL;
$objPHPExcel = new PHPExcel();

// Set document properties
echo date('H:i:s'), " Set document properties", EOL;
$objPHPExcel->getProperties()->setCreator( "SaasSystems" )
							  ->setLastModifiedBy ( "SaasSystems" )
							  ->setTitle ( "SaasSystems - Rejestr sprzedaży VAT" )
							  ->setSubject ( "SaasSystem - raport" )
							  ->setDescription ( "" )
							  ->setKeywords ( "" )
							  ->setCategory ( "Reports" );

/* * ************************************************** */
/* * ***************** EXCELL Styles ****************** */
/* * ************************************************** */
// Set default widths and heights
$objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(15);
$objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(20);

//tego nie ruszaj ani troche na razie
$headerStyle = array(
	'alignment' => array(
		'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
		'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
	),
	'font' => array(
		'bold' => true,
		'color' => array('rgb' => 'FFFFFF'),
		'name' => 'Verdana',
	),
	'fill' => array(
		'type' => PHPExcel_Style_Fill::FILL_SOLID,
		'startcolor' => array(
			'rgb' => '272822',
		),
	),
);

$categoryStyle = array(
	'alignment' => array(
		'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,
		'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
	),
	'font' => array(
		'bold' => true,
		'color' => array('rgb' => 'FFFFFF'),
		'name' => 'Verdana',
	),
	'fill' => array(
		'type' => PHPExcel_Style_Fill::FILL_SOLID,
		'startcolor' => array(
			'rgb' => '4E5044',
		),
	),
);

$subCategoryStyle = array(
	'alignment' => array(
		'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,
		'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
	),
	'font' => array(
		'bold' => true,
		'color' => array('rgb' => 'FFFFFF'),
		'name' => 'Verdana',
	),
	'fill' => array(
		'type' => PHPExcel_Style_Fill::FILL_SOLID,
		'startcolor' => array(
			'rgb' => '8F937D',
		),
	),
);

$columnAlignRight = array(
	'alignment' => array(
		'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,
		'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
	),
);

$columnAlignLeft = array(
	'alignment' => array(
		'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
		'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
	),
);
// tu masz szerokosci kolumn oraz wyrownania do ktorej strony
$objPHPExcel->setActiveSheetIndex(0)->getRowDimension('1')->setRowHeight(40);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(25);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(80);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(15);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(15);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('H')->setWidth(15);

$objPHPExcel->setActiveSheetIndex(0)->getStyle("A2:A4000")->applyFromArray($columnAlignLeft);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("B2:B4000")->applyFromArray($columnAlignLeft);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("C2:C4000")->applyFromArray($columnAlignLeft);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("D2:D4000")->applyFromArray($columnAlignLeft);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("E2:E4000")->applyFromArray($columnAlignLeft);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("F2:F4000")->applyFromArray($columnAlignRight);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("G2:G4000")->applyFromArray($columnAlignRight);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("H2:H4000")->applyFromArray($columnAlignRight);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("I2:I4000")->applyFromArray($columnAlignRight);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("J2:J4000")->applyFromArray($columnAlignRight);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("K2:K4000")->applyFromArray($columnAlignRight);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("L2:L4000")->applyFromArray($columnAlignRight);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("M2:M4000")->applyFromArray($columnAlignRight);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("N2:N4000")->applyFromArray($columnAlignRight);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("O2:O4000")->applyFromArray($columnAlignRight);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("P2:P4000")->applyFromArray($columnAlignRight);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("Q2:Q4000")->applyFromArray($columnAlignRight);
$objPHPExcel->setActiveSheetIndex(0)->getStyle("R2:R4000")->applyFromArray($columnAlignRight);

$objPHPExcel->setActiveSheetIndex(0)->getStyle("A1:G1")->applyFromArray($headerStyle);

/* * ************************************************** */
/* * ******************* EXCELL Data ****************** */
/* * ************************************************** */
// Add header
//tu masz naglowki kolumn
$licznikLiter = ord('G');
$objPHPExcel->setActiveSheetIndex(0)
		->setCellValue('A1', $mod_strings['LBL_DOC_NUMBER'])
		->setCellValue('B1', $mod_strings['LBL_REGISTER_DATE'])
		->setCellValue('C1', $mod_strings['LBL_CREATE_LAB'])
		->setCellValue('D1', $mod_strings['LBL_SALES_NIP'])
		->setCellValue('E1', $mod_strings['LBL_LIST_SUBJECT'])
		->setCellValue('F1', $mod_strings['LBL_BUYER_VALUE_BRUTTO'])
		->setCellValue('G1', $mod_strings['LBL_SUM_VAT']);



foreach ($tmp3 as $vatvalue => $vatnetto) {
	$licznikLiter ++;
	$objPHPExcel->setActiveSheetIndex(0)->getStyle(chr($licznikLiter) . "2:" . chr($licznikLiter) . "4000")->applyFromArray($columnAlignRight);
	$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($licznikLiter))->setWidth(15);
	$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue(chr($licznikLiter) . '1', 'netto' . $vatvalue);
	$objPHPExcel->setActiveSheetIndex(0)->getStyle(chr($licznikLiter) . '1')->applyFromArray($headerStyle);
	if ($vatnetto['sumavat'] != null) {
		$licznikLiter ++;
		$objPHPExcel->setActiveSheetIndex(0)->getStyle(chr($licznikLiter) . "2:" . chr($licznikLiter) . "4000")->applyFromArray($columnAlignRight);
		$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($licznikLiter))->setWidth(15);
		$objPHPExcel->setActiveSheetIndex(0)
				->setCellValue(chr($licznikLiter) . '1', 'vat' . $vatvalue);
		$objPHPExcel->setActiveSheetIndex(0)->getStyle(chr($licznikLiter) . '1')->applyFromArray($headerStyle);
	}
}



/* * ************************************************** */
/* * ******************* EXCELL Data ****************** */
/* * ************************************************** */
// Add all data
$lastRowNumber = 2;
$rowNumber = 2;

// tu masz uzupelnianie danymi tabelki w pliku

foreach ($data as $key => $item) {
	$licznikLiter = ord('G');
	$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue('A' . ($rowNumber), $item['document_number'])
			->setCellValue('B' . ($rowNumber), date("d.m.Y", strtotime($item['register_date'])))
			->setCellValue('C' . ($rowNumber), date("d.m.Y", strtotime($item['active_date'])))
			->setCellValue('D' . ($rowNumber), $item['to_vatid'])
			->setCellValue('E' . ($rowNumber), html_entity_decode($item['name']))
			->setCellValue('F' . ($rowNumber), number_format($item['value'], 2, ".", ""))
			->setCellValue('G' . ($rowNumber), number_format($item['vatsumapozycja'], 2, ".", ""));
	$objPHPExcel->setActiveSheetIndex(0)->getStyle('F' . ($rowNumber))->getNumberFormat()->setFormatCode("#,#0.#0 zł");
	$objPHPExcel->setActiveSheetIndex(0)->getStyle('G' . ($rowNumber))->getNumberFormat()->setFormatCode("#,#0.#0 zł");
	
	
	foreach ($tmp3 as $vatname => $vaty) {
		$licznikLiter++;
		$wypiszVat = null;
		$prawdafalsz = false;
		foreach ($item['vaty'] as $vatvalue => $vatnetto) {
			if ($vatname == $vatnetto['vat_value']) {
				$wypiszVat = $vatnetto;
				unset($item['vaty'][$vatvalue]);
				break;
			}
		}
		
		if ($wypiszVat != null) {
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue((chr($licznikLiter) ) . ($rowNumber),  $wypiszVat['netto']);
			$objPHPExcel->setActiveSheetIndex(0)->getStyle(chr($licznikLiter) . ($rowNumber))->getNumberFormat()->setFormatCode("#,#0.#0 zł");
			if ($vaty ['sumavat'] != null) {
				$licznikLiter++;
				$objPHPExcel->setActiveSheetIndex(0)->setCellValue((chr($licznikLiter) ) . ($rowNumber), $wypiszVat['vat']);
				$objPHPExcel->setActiveSheetIndex(0)->getStyle(chr($licznikLiter) . ($rowNumber))->getNumberFormat()->setFormatCode("#,#0.#0 zł");
			}
		} else {
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue((chr($licznikLiter) ) . ($rowNumber),  0);
			$objPHPExcel->setActiveSheetIndex(0)->getStyle(chr($licznikLiter) . ($rowNumber))->getNumberFormat()->setFormatCode("#,#0.#0 zł");
			if ($vaty ['sumavat'] != null) {
				$licznikLiter++;
				$objPHPExcel->setActiveSheetIndex(0)->setCellValue((chr($licznikLiter) ) . ($rowNumber),  0);
				$objPHPExcel->setActiveSheetIndex(0)->getStyle(chr($licznikLiter) . ($rowNumber))->getNumberFormat()->setFormatCode("#,#0.#0 zł");
			}
		}
	}


	$rowNumber++;
	$lastRowNumber++;
}




// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle($mod_strings['LBL_REPORT_RECEIVE_REGISTER']);

// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);

// Save Excel 2007 file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(__DIR__ . "/ExcelFiles/RaportZakupu.xls");
?>
