<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Laporan extends Auth_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Payroll_model');
        $this->load->model('Pegawai_model');
        $this->load->model('Absensi_model');
        $this->load->helper('app_helper');
    }

    /**
     * Halaman index laporan - pilih jenis laporan
     */
    public function index()
    {
        $this->render('output/laporan/index', [
            'title' => 'Pusat Laporan',
        ]);
    }

    /**
     * Laporan payroll bulanan
     */
    public function payroll()
    {
        $bulan        = $this->input->get('bulan')        ?: date('m');
        $tahun        = $this->input->get('tahun')        ?: date('Y');
        $tipe_periode = $this->input->get('tipe_periode') ?: 'REGULER';
        $format       = $this->input->get('format')       ?: 'html';

        $periode_list = $this->Payroll_model->get_periode_list(['APPROVED', 'LOCKED']);

        $periode = $this->Payroll_model->get_periode_target($bulan, $tahun, $tipe_periode, ['APPROVED', 'LOCKED']);
        $id_periode = $periode ? (int) $periode->id_periode : null;

        $rows = [];
        if ($id_periode) {
            $rows = $this->Payroll_model->get_payroll_detail($id_periode);
        }

        if ($format === 'excel' && $id_periode) {
            $this->_export_excel_payroll($periode, $rows);
            return;
        }

        $this->render('output/laporan/payroll', [
            'title'        => 'Laporan Payroll Bulanan',
            'periode_list' => $periode_list,
            'periode'      => $periode,
            'rows'         => $rows,
            'bulan'        => $bulan,
            'tahun'        => $tahun,
            'tipe_periode' => $tipe_periode,
        ]);
    }

    /**
     * Laporan bank (daftar transfer gaji ke bank)
     */
    public function bank()
    {
        $bulan        = $this->input->get('bulan')        ?: date('m');
        $tahun        = $this->input->get('tahun')        ?: date('Y');
        $tipe_periode = $this->input->get('tipe_periode') ?: 'REGULER';
        $format       = $this->input->get('format')       ?: 'html';

        $periode_list = $this->Payroll_model->get_periode_list(['APPROVED', 'LOCKED']);

        $periode = $this->Payroll_model->get_periode_target($bulan, $tahun, $tipe_periode, ['APPROVED', 'LOCKED']);
        $id_periode = $periode ? (int) $periode->id_periode : null;

        $rows = [];
        if ($id_periode) {
            $rows = $this->_get_bank_data($id_periode);
        }

        if ($format === 'excel' && $id_periode) {
            $this->_export_excel_bank($periode, $rows);
            return;
        }

        $this->render('output/laporan/bank', [
            'title'        => 'Laporan Bank Payroll',
            'periode_list' => $periode_list,
            'periode'      => $periode,
            'rows'         => $rows,
            'bulan'        => $bulan,
            'tahun'        => $tahun,
            'tipe_periode' => $tipe_periode,
        ]);
    }

    /**
     * Laporan absensi bulanan
     */
    public function absensi()
    {
        $bulan  = (int) ($this->input->get('bulan')  ?: date('m'));
        $tahun  = (int) ($this->input->get('tahun')  ?: date('Y'));

        $resolved = resolve_payroll_period($bulan, $tahun, 'REGULER');
        if (!$resolved) {
            $this->session->set_flashdata('error', 'Periode laporan absensi tidak valid.');
            redirect('output/laporan');
            return;
        }

        $summary = $this->Absensi_model->get_summary_periode($resolved['tanggal_mulai'], $resolved['tanggal_selesai'], null);

        $this->render('output/laporan/absensi', [
            'title'   => 'Laporan Absensi Bulanan',
            'summary' => $summary,
            'bulan'   => $bulan,
            'tahun'   => $tahun,
            'periode_label' => $resolved['label_rentang'],
        ]);
    }

    // ------------------------------------------------------------------
    // Private helpers
    // ------------------------------------------------------------------

    private function _get_bank_data($id_periode)
    {
        return $this->db
            ->select('p.id_payroll, pg.nip, pg.nama_lengkap, pg.nama_bank, pg.no_rekening, p.gaji_neto, d.nama_divisi', false)
            ->from('tb_payroll p')
            ->join('tb_pegawai pg', 'pg.id_pegawai = p.id_pegawai', 'left')
            ->join('tb_divisi d', 'd.id_divisi = pg.id_divisi', 'left')
            ->where('p.id_periode', (int) $id_periode)
            ->order_by('d.nama_divisi', 'ASC')
            ->order_by('pg.nama_lengkap', 'ASC')
            ->get()->result();
    }

    private function _export_excel_payroll($periode, $rows)
    {
        require_once APPPATH . '../vendor/autoload.php';

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet       = $spreadsheet->getActiveSheet();
        $sheet->setTitle('Payroll');

        $bulan_text = bulan_indonesia($periode->bulan) . ' ' . $periode->tahun;
        $rentang_text = tgl_indonesia($periode->tanggal_mulai) . ' s/d ' . tgl_indonesia($periode->tanggal_selesai);

        // Header
        $sheet->mergeCells('A1:L1');
        $sheet->setCellValue('A1', 'LAPORAN PAYROLL BULANAN - ' . strtoupper($bulan_text));
        $sheet->mergeCells('A2:L2');
        $sheet->setCellValue('A2', 'Periode: ' . $rentang_text . ' | Tipe: ' . ($periode->tipe_periode ?? 'REGULER'));
        $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(13);

        $headers = ['No', 'NIP', 'Nama Pegawai', 'Divisi', 'Hari Hadir', 'Hari Absen', 'Lembur (jam)',
                    'Gaji Bruto', 'Total Potongan', 'Gaji Neto', 'BPJS TK', 'PPh 21'];
        $col = 'A';
        foreach ($headers as $h) {
            $sheet->setCellValue($col . '4', $h);
            $sheet->getStyle($col . '4')->getFont()->setBold(true);
            $sheet->getStyle($col . '4')->getFill()
                  ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
                  ->getStartColor()->setARGB('FFE53935');
            $sheet->getStyle($col . '4')->getFont()->getColor()->setARGB('FFFFFFFF');
            $col++;
        }

        $row = 5;
        $no  = 1;
        foreach ($rows as $r) {
            $sheet->setCellValue('A' . $row, $no++);
            $sheet->setCellValue('B' . $row, $r->nip);
            $sheet->setCellValue('C' . $row, $r->nama_lengkap);
            $sheet->setCellValue('D' . $row, $r->nama_divisi);
            $sheet->setCellValue('E' . $row, $r->hari_hadir ?? 0);
            $sheet->setCellValue('F' . $row, $r->hari_absen ?? 0);
            $sheet->setCellValue('G' . $row, $r->total_jam_lembur ?? 0);
            $sheet->setCellValue('H' . $row, $r->gaji_bruto ?? 0);
            $sheet->setCellValue('I' . $row, $r->total_potongan ?? 0);
            $sheet->setCellValue('J' . $row, $r->gaji_neto ?? 0);
            $sheet->setCellValue('K' . $row, $r->potongan_bpjs_tk ?? 0);
            $sheet->setCellValue('L' . $row, $r->potongan_pph21 ?? 0);

            foreach (['H', 'I', 'J', 'K', 'L'] as $c) {
                $sheet->getStyle($c . $row)
                      ->getNumberFormat()
                      ->setFormatCode('#,##0');
            }
            $row++;
        }

        // Auto width
        foreach (range('A', 'L') as $c) {
            $sheet->getColumnDimension($c)->setAutoSize(true);
        }

        $filename = 'laporan_payroll_' . $periode->bulan . '_' . $periode->tahun . '.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

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

    private function _export_excel_bank($periode, $rows)
    {
        require_once APPPATH . '../vendor/autoload.php';

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet       = $spreadsheet->getActiveSheet();
        $sheet->setTitle('Transfer Bank');

        $bulan_text = bulan_indonesia($periode->bulan) . ' ' . $periode->tahun;
        $rentang_text = tgl_indonesia($periode->tanggal_mulai) . ' s/d ' . tgl_indonesia($periode->tanggal_selesai);

        $sheet->mergeCells('A1:G1');
        $sheet->setCellValue('A1', 'DAFTAR TRANSFER GAJI - ' . strtoupper($bulan_text));
        $sheet->mergeCells('A2:G2');
        $sheet->setCellValue('A2', 'Periode: ' . $rentang_text . ' | Tipe: ' . ($periode->tipe_periode ?? 'REGULER'));
        $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(13);

        $headers = ['No', 'NIP', 'Nama Pegawai', 'Divisi', 'Nama Bank', 'No. Rekening', 'Nominal Transfer'];
        $col = 'A';
        foreach ($headers as $h) {
            $sheet->setCellValue($col . '4', $h);
            $sheet->getStyle($col . '4')->getFont()->setBold(true);
            $sheet->getStyle($col . '4')->getFill()
                  ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
                  ->getStartColor()->setARGB('FFE53935');
            $sheet->getStyle($col . '4')->getFont()->getColor()->setARGB('FFFFFFFF');
            $col++;
        }

        $row = 5;
        $no  = 1;
        $total = 0;
        foreach ($rows as $r) {
            $sheet->setCellValue('A' . $row, $no++);
            $sheet->setCellValue('B' . $row, $r->nip);
            $sheet->setCellValue('C' . $row, $r->nama_lengkap);
            $sheet->setCellValue('D' . $row, $r->nama_divisi);
            $sheet->setCellValue('E' . $row, $r->nama_bank ?: '-');
            $sheet->setCellValue('F' . $row, $r->no_rekening ?: '-');
            $sheet->setCellValue('G' . $row, $r->gaji_neto ?? 0);
            $sheet->getStyle('G' . $row)->getNumberFormat()->setFormatCode('#,##0');
            $total += (float) $r->gaji_neto;
            $row++;
        }

        $sheet->setCellValue('F' . $row, 'TOTAL');
        $sheet->setCellValue('G' . $row, $total);
        $sheet->getStyle('F' . $row . ':G' . $row)->getFont()->setBold(true);
        $sheet->getStyle('G' . $row)->getNumberFormat()->setFormatCode('#,##0');

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

        $filename = 'laporan_bank_' . $periode->bulan . '_' . $periode->tahun . '.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

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