<?php  
	
	include 'aksi/koneksi.php';
	require 'vendor/export-import/autoload.php';

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


	if(isset($_POST['export_btn']))
	{
		$sessionCabang = $_POST['satuan_cabang'];
		$fileName 	= "data-satuan-barang-export-tanggal-".date("Y-m-d");

		$query 		= "SELECT * FROM satuan WHERE satuan_cabang = $sessionCabang ORDER BY satuan_id DESC ";
		$query_run 	= mysqli_query($conn, $query);

		if( mysqli_num_rows($query_run) > 0 ) {

			$spreadsheet = new Spreadsheet();
			$sheet 		 = $spreadsheet->getActiveSheet();
			$sheet->setCellValue('A1', 'ID');
			$sheet->setCellValue('B1', 'Nama satuan Barang');
			$sheet->setCellValue('C1', 'Status');
			$sheet->setCellValue('D1', 'Cabang');

			$rowCount = 2;
			foreach ( $query_run as $data ) {
				$sheet->setCellValue('A' . $rowCount, $data['satuan_id']);
				$sheet->setCellValue('B' . $rowCount, $data['satuan_nama']);

				// Mencari Data Status
				$cabang = $data['satuan_status'];
				if ( $cabang < 1 ) {
					$nameStatus = 'Tidak Aktif';
				} else {
					$nameStatus = 'Aktif';
				}
				$sheet->setCellValue('C' . $rowCount, $nameStatus);

				// Mencari Data Cabang
				$cabang = $data['satuan_cabang'];
				if ( $cabang < 1 ) {
					$nameCabang = 'Pusat';
				} else {
					$nameCabang = 'Cabang ke '.$cabang;
				}
				$sheet->setCellValue('D' . $rowCount, $nameCabang);
				$rowCount++;
			}

			// if ( $ext == 'xlsx' ) {
			// 	$writer 		= new Xlsx($spreadsheet);
			// 	$final_fileName = $fileName.'.xlsx';
			// } elseif ( $ext == 'xls' ) {
			// 	$writer 		= new Xls($spreadsheet);
			// 	$final_fileName = $fileName.'.xls';
			// } elseif ( $ext == 'csv' ) {
			// 	$writer 		= new Csv($spreadsheet);
			// 	$final_fileName = $fileName.'.csv';
			// }
			
			$writer 		= new Xlsx($spreadsheet);
			$final_fileName = $fileName.'.xlsx';

			// $writer->save($final_fileName);
			header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
			header('Content-Disposition: attachment; filename="'.urlencode($final_fileName).'" ');
			$writer->save('php://output');


		} else {
			echo "
				<script>
					alert('Data Gagal Export');
					document.location.href = 'barang';
				</script>
			";
		}
	}