<?php
require_once('includes/load.php');
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Alignment;

page_require_level(4);

if (!isset($_POST['salaries_data_export']) || empty($_POST['salaries_data_export'])) {
    redirect('laporan_gaji.php', false);
}

$gaji_karyawan = json_decode($_POST['salaries_data_export'], true);
$month = isset($_POST['month']) ? $_POST['month'] : date('m');
$year = isset($_POST['year']) ? $_POST['year'] : date('Y');

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

$sheet->mergeCells('A1:J1');
$sheet->setCellValue('A1', 'Laporan Gaji Karyawan Bulan ' . date('F Y', strtotime("{$year}-{$month}-01")));
$sheet->getStyle('A1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);

$headers = ['No', 'Nama Karyawan', 'Gaji Pokok', 'Hadir', 'Alpha', 'Izin', 'Sakit', 'Cuti', 'Total Potongan', 'Gaji Bersih'];
$sheet->fromArray($headers, null, 'A3');

$headerStyle = $sheet->getStyle('A3:J3');
$headerStyle->getFont()->setBold(true);
$headerStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$headerStyle->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);

$row = 4;
foreach ($gaji_karyawan as $index => $gaji) {
    $sheet->setCellValue('A' . $row, $index + 1);
    $sheet->setCellValue('B' . $row, $gaji['name']);
    $sheet->setCellValue('C' . $row, $gaji['basic_salary']);
    $sheet->setCellValue('D' . $row, $gaji['hadir_count']);
    $sheet->setCellValue('E' . $row, $gaji['alpha_count']);
    $sheet->setCellValue('F' . $row, $gaji['izin_count']);
    $sheet->setCellValue('G' . $row, $gaji['sakit_count']);
    $sheet->setCellValue('H' . $row, $gaji['cuti_count']);
    $sheet->setCellValue('I' . $row, $gaji['total_deductions']);
    $sheet->setCellValue('J' . $row, $gaji['net_salary']);

    $sheet->getStyle('C' . $row)->getNumberFormat()->setFormatCode('"Rp "#,##0.00');
    $sheet->getStyle('I' . $row)->getNumberFormat()->setFormatCode('"Rp "#,##0.00');
    $sheet->getStyle('J' . $row)->getNumberFormat()->setFormatCode('"Rp "#,##0.00');

    $sheet->getStyle('A' . $row . ':J' . $row)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
    $row++;
}

foreach (range('A', 'J') as $columnID) {
    $sheet->getColumnDimension($columnID)->setAutoSize(true);
}

$fileName = 'Laporan_Gaji_Karyawan_' . date('F_Y', strtotime("{$year}-{$month}-01")) . '.xlsx';

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $fileName . '"');
header('Cache-Control: max-age=0');

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