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

require_once APPPATH . '../vendor/autoload.php'; // <-- pastikan ini ada

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use Dompdf\Dompdf;

class Admin_Dashboard_Controller extends CI_Controller {
    public function __construct(){
        parent::__construct();
        $this->load->model("akun_model");
        $this->load->model("Inventory_model");
        $this->load->model("Atk_Pengambilan_model", "pengambilan");
        $this->load->library('session');

        // Cek login
        if (!$this->session->userdata('logged_in')) {
            redirect('Auth/Login');
        }

        // Cek timeout manual
        $this->check_timeout();
    }

    // ---------------- EXPORT EXCEL ----------------
    public function export_excel() {
        // baca parameter GET
        $raw_bulan = $this->input->get('bulan');
        $bulan = ($raw_bulan === null || $raw_bulan === '') ? 'all' : $raw_bulan;
        $raw_tahun = $this->input->get('tahun');
        $tahun = ($raw_tahun === null || $raw_tahun === '') ? date('Y') : (int)$raw_tahun;

        // Ambil data via model (model harus bisa menangani 'all' atau bulan tertentu)
        $rekap = $this->pengambilan->rekapKaryawan($bulan, $tahun);
        $rekap_divisi = $this->pengambilan->rekapDivisi($bulan, $tahun);

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

        // Logo
        $logoPath = FCPATH . 'assets/img/asiaserv-logo.png';
        if (file_exists($logoPath)) {
            $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
            $drawing->setName('Logo');
            $drawing->setDescription('Logo Perusahaan');
            $drawing->setPath($logoPath);
            $drawing->setHeight(50);
            $drawing->setCoordinates('A1');
            $drawing->setWorksheet($sheet);
        }

        // Judul (tampilkan nama bulan kalau bukan 'all')
        $judul_bulan = ($bulan === 'all') ? 'Semua Bulan' : $this->bulan_nama((int)$bulan);
        $sheet->mergeCells('A2:E2');
        $sheet->setCellValue('A2', "Rekap Pengambilan ATK - $judul_bulan Tahun $tahun");
        $sheet->getStyle('A2')->getFont()->setBold(true)->setSize(14);
        $sheet->getStyle('A2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

        // Header rekap per karyawan
        $row = 4;
        $sheet->setCellValue('A'.$row, 'No');
        $sheet->setCellValue('B'.$row, 'Nama Peminjam');
        $sheet->setCellValue('C'.$row, 'Divisi');
        $sheet->setCellValue('D'.$row, 'Total Transaksi');
        $sheet->setCellValue('E'.$row, 'Total Item');

        $headerStyle = [
            'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
            'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '4CAF50']],
            'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER]
        ];
        $sheet->getStyle('A'.$row.':E'.$row)->applyFromArray($headerStyle);

        // Data rekap per karyawan
        $row++;
        $no = 1;
        $total_transaksi = 0;
        $total_item = 0;
        if (!empty($rekap)) {
            foreach ($rekap as $r) {
                $sheet->setCellValue('A'.$row, $no++);
                $sheet->setCellValue('B'.$row, isset($r->atk_pengambilan_peminjam) ? $r->atk_pengambilan_peminjam : '-');
                $sheet->setCellValue('C'.$row, isset($r->atk_pengambilan_divisi) ? $r->atk_pengambilan_divisi : '-');
                $sheet->setCellValue('D'.$row, isset($r->total_transaksi) ? $r->total_transaksi : 0);
                $sheet->setCellValue('E'.$row, isset($r->total_item) ? $r->total_item : 0);

                $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
                $sheet->getStyle('B'.$row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
                $sheet->getStyle('C'.$row.':E'.$row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

                $total_transaksi += isset($r->total_transaksi) ? $r->total_transaksi : 0;
                $total_item += isset($r->total_item) ? $r->total_item : 0;
                $row++;
            }
        }

        // Total keseluruhan
        $sheet->setCellValue('A'.$row, 'Total Keseluruhan');
        $sheet->mergeCells('A'.$row.':C'.$row);
        $sheet->setCellValue('D'.$row, $total_transaksi);
        $sheet->setCellValue('E'.$row, $total_item);
        $sheet->getStyle('A'.$row.':E'.$row)->getFont()->setBold(true);
        $sheet->getStyle('A'.$row.':E'.$row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

        // Rekap per divisi (jarak)
        $row += 3;
        $sheet->setCellValue('A'.$row, 'No');
        $sheet->setCellValue('B'.$row, 'Divisi');
        $sheet->setCellValue('C'.$row, 'Total Karyawan');
        $sheet->setCellValue('D'.$row, 'Total Transaksi');
        $sheet->setCellValue('E'.$row, 'Total Item');
        $sheet->getStyle('A'.$row.':E'.$row)->applyFromArray($headerStyle);

        $row++;
        $no = 1;
        $total_karyawan_div = 0;
        $total_transaksi_div = 0;
        $total_item_div = 0;

        if (!empty($rekap_divisi)) {
            foreach($rekap_divisi as $d) {
                $sheet->setCellValue('A'.$row, $no++);
                $sheet->setCellValue('B'.$row, isset($d->atk_pengambilan_divisi) ? $d->atk_pengambilan_divisi : '-');
                $sheet->setCellValue('C'.$row, isset($d->total_karyawan) ? $d->total_karyawan : 0);
                $sheet->setCellValue('D'.$row, isset($d->total_transaksi) ? $d->total_transaksi : 0);
                $sheet->setCellValue('E'.$row, isset($d->total_item) ? $d->total_item : 0);

                $sheet->getStyle('A'.$row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
                $sheet->getStyle('B'.$row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
                $sheet->getStyle('C'.$row.':E'.$row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

                $total_karyawan_div += isset($d->total_karyawan) ? $d->total_karyawan : 0;
                $total_transaksi_div += isset($d->total_transaksi) ? $d->total_transaksi : 0;
                $total_item_div += isset($d->total_item) ? $d->total_item : 0;

                $row++;
            }
        }

        // Total per divisi
        $sheet->setCellValue('A'.$row, 'Total Keseluruhan');
        $sheet->mergeCells('A'.$row.':B'.$row);
        $sheet->setCellValue('C'.$row, $total_karyawan_div);
        $sheet->setCellValue('D'.$row, $total_transaksi_div);
        $sheet->setCellValue('E'.$row, $total_item_div);
        $sheet->getStyle('A'.$row.':E'.$row)->getFont()->setBold(true);
        $sheet->getStyle('A'.$row.':E'.$row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

        // Borders & autosize
        $sheet->getStyle("A4:E$row")->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
        foreach (range('A','E') as $col) {
            $sheet->getColumnDimension($col)->setAutoSize(true);
        }

        // Landscape
        $sheet->getPageSetup()->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE);

        // Export
        $writer = new Xlsx($spreadsheet);
        $filename = 'Rekap_Pengambilan_'.($bulan === 'all' ? 'SemuaBulan' : $this->bulan_nama((int)$bulan)).'_'.$tahun.'.xlsx';

        if (ob_get_contents()) ob_end_clean();

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

        $writer->save("php://output");
        exit;
    }

    // ---------------- EXPORT PDF ----------------
    public function export_pdf() {
    // 1. Pengambilan dan Validasi Parameter
    // Pastikan parameter 'bulan' dan 'tahun' selalu valid
    $raw_bulan = $this->input->get('bulan');
    $bulan = ($raw_bulan === null || $raw_bulan === '' || !is_numeric($raw_bulan)) ? 'all' : (int)$raw_bulan;
    $raw_tahun = $this->input->get('tahun');
    $tahun = ($raw_tahun === null || $raw_tahun === '' || !is_numeric($raw_tahun)) ? (int)date('Y') : (int)$raw_tahun;

    // 2. Pengambilan Data
    $rekap = $this->pengambilan->rekapKaryawan($bulan, $tahun);
    $rekap_divisi = $this->pengambilan->rekapDivisi($bulan, $tahun);
    
    // Konversi bulan ke nama (asumsi Anda memiliki method bulan_nama)
    $judul_bulan = ($bulan === 'all') ? 'Semua Periode' : $this->bulan_nama($bulan);
    $judul_periode = "$judul_bulan Tahun $tahun";

    // 3. Inisialisasi PDF
    $this->load->library('Pdf');
    // Menggunakan A4 Landscape ('L', 'mm', 'A4')
    $pdf = new Pdf('L','mm','A4');
    $pdf->AddPage();
    
    // Lebar halaman A4 Landscape: 297mm. Margin standar 10mm. Area yang tersedia: 277mm.
    $margin = 10;
    $lebar_area = 297 - (2 * $margin);

    // =========================================================================
    // 4. HEADER DOKUMEN
    // =========================================================================
    
    // Informasi Judul Utama
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(0,8,"REKAPITULASI PENGAMBILAN ATK",0,1,'C');
    
    // Informasi Periode
    $pdf->SetFont('Arial','',12);
    $pdf->Cell(0,6,"Periode: $judul_periode",0,1,'C');

    // Informasi Tanggal Cetak (Ditaruh di pojok kanan atas)
    $pdf->SetY($pdf->GetY() - 15); // Naikkan posisi sedikit
    $pdf->SetFont('Arial','I',8);
    $pdf->Cell(0,5,"Dicetak: ".date('d M Y H:i:s'),0,1,'R');
    $pdf->Ln(5); // Jarak antar header dan tabel

    // =========================================================================
    // 5. REKAP PER KARYAWAN
    // =========================================================================
    $pdf->SetFont('Arial','B',12);
    $pdf->Cell(0,8,'A. Rekap Per Karyawan',0,1,'L');

    // Header Tabel Karyawan
    $pdf->SetFillColor(220, 220, 220); // Warna abu-abu muda untuk header
    $pdf->SetFont('Arial','B',9);
    $tinggi_baris = 7;
    
    $w_karyawan = [10, 80, 50, 40, 40]; // Total: 220. Kita punya 277. Sisanya 57mm.
    
    // Penyesuaian lebar: Total 277mm. Kita gunakan 250mm agar ada spasi di kanan.
    $sisa_lebar = $lebar_area - array_sum($w_karyawan); // 277 - 220 = 57
    $w_karyawan = [10, 95, 60, 45, 45]; // Total: 255mm. Sisa 22mm.
    
    $pdf->Cell($w_karyawan[0],$tinggi_baris,'No',1,0,'C',true);
    $pdf->Cell($w_karyawan[1],$tinggi_baris,'Nama Karyawan',1,0,'C',true); // Diperluas
    $pdf->Cell($w_karyawan[2],$tinggi_baris,'Divisi',1,0,'C',true); // Diperluas
    $pdf->Cell($w_karyawan[3],$tinggi_baris,'Total Transaksi',1,0,'C',true);
    $pdf->Cell($w_karyawan[4],$tinggi_baris,'Total Item',1,1,'C',true);

    // Data Tabel Karyawan
    $pdf->SetFont('Arial','',9);
    $no=1; $total_trans_kar=0; $total_item_kar=0;
    if (!empty($rekap)) {
        foreach($rekap as $r){
            // Gunakan is_string() untuk memastikan format data
            $nama = isset($r->atk_pengambilan_peminjam) ? $r->atk_pengambilan_peminjam : '-';
            $divisi = isset($r->atk_pengambilan_divisi) ? $r->atk_pengambilan_divisi : '-';
            $transaksi = isset($r->total_transaksi) ? (int)$r->total_transaksi : 0;
            $item = isset($r->total_item) ? (int)$r->total_item : 0;
            
            // Output data
            $pdf->Cell($w_karyawan[0],$tinggi_baris,$no++,1,0,'C');
            $pdf->Cell($w_karyawan[1],$tinggi_baris,$nama,1,0,'L'); // Rata Kiri untuk Nama
            $pdf->Cell($w_karyawan[2],$tinggi_baris,$divisi,1,0,'L'); // Rata Kiri untuk Divisi
            $pdf->Cell($w_karyawan[3],$tinggi_baris,$transaksi,1,0,'R'); // Rata Kanan untuk Angka
            $pdf->Cell($w_karyawan[4],$tinggi_baris,$item,1,1,'R'); // Rata Kanan untuk Angka
            
            // Hitung Total
            $total_trans_kar += $transaksi;
            $total_item_kar += $item;
        }
    } else {
        $pdf->Cell(array_sum($w_karyawan),$tinggi_baris,'Data tidak ditemukan.',1,1,'C');
    }

    // Baris Total Karyawan
    $pdf->SetFont('Arial','B',9);
    $pdf->Cell($w_karyawan[0] + $w_karyawan[1] + $w_karyawan[2], $tinggi_baris, 'TOTAL PENGAMBILAN PER KARYAWAN',1,0,'C',true);
    $pdf->Cell($w_karyawan[3],$tinggi_baris,$total_trans_kar,1,0,'R',true);
    $pdf->Cell($w_karyawan[4],$tinggi_baris,$total_item_kar,1,1,'R',true);
    $pdf->Ln(10); // Spasi antara tabel

    // =========================================================================
    // 6. REKAP PER DIVISI
    // =========================================================================
    $pdf->SetFont('Arial','B',12);
    $pdf->Cell(0,8,'B. Rekap Per Divisi',0,1,'L');

    // Header Tabel Divisi
    $pdf->SetFillColor(220, 220, 220);
    $pdf->SetFont('Arial','B',9);
    
    // Penyesuaian lebar untuk tabel kedua
    $w_divisi = [10, 80, 40, 40, 40]; // Total: 210mm. Sisa 67mm.
    $w_divisi = [10, 80, 50, 60, 60]; // Total: 260mm. Sisa 17mm.
    
    $pdf->Cell($w_divisi[0],$tinggi_baris,'No',1,0,'C',true);
    $pdf->Cell($w_divisi[1],$tinggi_baris,'Divisi',1,0,'C',true);
    $pdf->Cell($w_divisi[2],$tinggi_baris,'Karyawan Aktif',1,0,'C',true); // Diubah Total Karyawan -> Karyawan Aktif
    $pdf->Cell($w_divisi[3],$tinggi_baris,'Total Transaksi',1,0,'C',true);
    $pdf->Cell($w_divisi[4],$tinggi_baris,'Total Item',1,1,'C',true);

    // Data Tabel Divisi
    $pdf->SetFont('Arial','',9);
    $no=1; $tk_div=0; $tt_div=0; $ti_div=0;
    if (!empty($rekap_divisi)) {
        foreach($rekap_divisi as $d){
            $divisi = isset($d->atk_pengambilan_divisi) ? $d->atk_pengambilan_divisi : '-';
            $karyawan = isset($d->total_karyawan) ? (int)$d->total_karyawan : 0;
            $transaksi = isset($d->total_transaksi) ? (int)$d->total_transaksi : 0;
            $item = isset($d->total_item) ? (int)$d->total_item : 0;

            // Output data
            $pdf->Cell($w_divisi[0],$tinggi_baris,$no++,1,0,'C');
            $pdf->Cell($w_divisi[1],$tinggi_baris,$divisi,1,0,'L'); // Rata Kiri untuk Divisi
            $pdf->Cell($w_divisi[2],$tinggi_baris,$karyawan,1,0,'R'); // Rata Kanan untuk Angka
            $pdf->Cell($w_divisi[3],$tinggi_baris,$transaksi,1,0,'R'); // Rata Kanan untuk Angka
            $pdf->Cell($w_divisi[4],$tinggi_baris,$item,1,1,'R'); // Rata Kanan untuk Angka

            // Hitung Total
            $tk_div += $karyawan;
            $tt_div += $transaksi;
            $ti_div += $item;
        }
    } else {
        $pdf->Cell(array_sum($w_divisi),$tinggi_baris,'Data tidak ditemukan.',1,1,'C');
    }

    // Baris Total Divisi
    $pdf->SetFont('Arial','B',9);
    $pdf->Cell($w_divisi[0] + $w_divisi[1], $tinggi_baris, 'TOTAL PENGAMBILAN PER DIVISI',1,0,'C',true);
    $pdf->Cell($w_divisi[2],$tinggi_baris,$tk_div,1,0,'R',true);
    $pdf->Cell($w_divisi[3],$tinggi_baris,$tt_div,1,0,'R',true);
    $pdf->Cell($w_divisi[4],$tinggi_baris,$ti_div,1,1,'R',true);

    // 7. Output PDF
    $pdf->Output('D', "Rekap_ATK_".($bulan === 'all' ? 'SemuaPeriode' : $this->bulan_nama($bulan))."_$tahun.pdf");
}

    // ---------------- DASHBOARD INDEX ----------------
    public function index()
    {
        // Baca parameter GET secara aman
        $raw_bulan = $this->input->get('bulan');
        $raw_tahun = $this->input->get('tahun');

        // jika GET kosong atau tidak ada -> 'all' (tapi kita tetap kirim ke view '' agar view tahu harus sembunyikan chart mingguan)
        $bulan_filter = ($raw_bulan === null || $raw_bulan === '') ? 'all' : $raw_bulan;
        $tahun_filter = ($raw_tahun === null || $raw_tahun === '') ? (int)date('Y') : (int)$raw_tahun;

        // Panggil model untuk rekap (model harus bisa menerima 'all' atau nomor bulan)
        $rekap_bulan = $this->pengambilan->getRekapPerBulan($bulan_filter, $tahun_filter);

        // Siapkan data chart
        $labels = [];
        $jumlah = [];
        $atk_list = [];

        // Jika 'all' -> asumsi model mengembalikan field 'bulan' (angka 1..12 atau nama)
        // Jika spesifik bulan -> model mengembalikan field 'hari'
        foreach ($rekap_bulan as $r) {
            if ($bulan_filter === 'all') {
                // preferensi: jika model memberikan bulan angka gunakan nama bulan
                if (isset($r->bulan)) {
                    $bulan_num = (int)$r->bulan;
                    $labels[] = $this->bulan_nama($bulan_num);
                } else if (isset($r->bulan_nama)) {
                    $labels[] = $r->bulan_nama;
                } else {
                    $labels[] = 'Bulan N/A';
                }
            } else {
                // spesifik bulan -> tampilkan hari
                if (isset($r->hari)) {
                    $labels[] = "Hari ke-".$r->hari;
                } else if (isset($r->tanggal)) {
                    // jika model mengembalikan tanggal lengkap
                    $labels[] = date('j', strtotime($r->tanggal));
                } else {
                    $labels[] = 'Hari N/A';
                }
            }

            $jumlah[] = isset($r->total_pengambilan) ? (int)$r->total_pengambilan : 0;
            $atk_list[] = isset($r->atk_list) ? $r->atk_list : "-";
        }

        // Kirim ke view: agar view menyembunyikan chart mingguan saat 'all', kita kirim bulan_filter = '' untuk kasus 'all'
        $view_bulan_filter = ($bulan_filter === 'all') ? '' : $bulan_filter;

        $data['bulan'] = $labels;
        $data['jumlah'] = $jumlah;
        $data['atk_list'] = $atk_list;

        $data['total_inventory'] = $this->Inventory_model->jumlah_inventory();

        // Data per minggu: hanya jika ada bulan spesifik dipilih
        $data['minggu'] = [];
        $data['jumlah_minggu'] = [];
        if ($bulan_filter !== 'all') {
            // hitung minggu di dalam satu bulan
            $start_date = date("Y-m-01", strtotime("$tahun_filter-$bulan_filter-01"));
            $end_date   = date("Y-m-t", strtotime($start_date));

            $this->db->select("WEEK(tanggal_pengambilan, 1) AS minggu_index, COUNT(*) AS total");
            $this->db->from("atk_pengambilan");
            $this->db->where("tanggal_pengambilan >=", $start_date);
            $this->db->where("tanggal_pengambilan <=", $end_date);
            $this->db->group_by("minggu_index");
            $this->db->order_by("minggu_index", "ASC");
            $result_minggu = $this->db->get()->result_array();

            // Format minggu: tampilkan "Minggu ke-1", "Minggu ke-2" berdasarkan index urutan (bukan nomor minggu tahunan)
            foreach ($result_minggu as $idx => $row) {
                $data['minggu'][] = "Minggu ke-" . ($idx + 1);
                $data['jumlah_minggu'][] = isset($row['total']) ? (int)$row['total'] : 0;
            }
        }

        $data['bulan_filter'] = $view_bulan_filter; // untuk view (kosongkan jika all)
        $data['tahun_filter'] = $tahun_filter;

        // Load views
        $this->load->view('Admin/head');
        $this->load->view('Admin/admin_dashboard', $data);
        $this->load->view('Admin/footer');
    }

    // ---------------- INVENTORY ----------------
    public function inventory_dashboard()
    {
        $this->load->model("Inventory_model");
        $data['produk_list'] = $this->Inventory_model->get_inventory_by_produk();

        $this->load->view('Admin/head');
        $this->load->view('Admin/inventory_dashboard', $data);
        $this->load->view('Admin/footer');
    }

    public function produk_detail($id_produk)
    {
        $this->load->model("Inventory_model");
        $data['produk'] = $this->Inventory_model->get_produk_detail($id_produk);

        $this->load->view('Admin/head');
        $this->load->view('Admin/produk_detail', $data);
        $this->load->view('Admin/footer');
    }

    public function rekap_pengambilan() {
        $this->load->model('Atk_Pengambilan_model', 'pengambilan');

        $raw_bulan = $this->input->get('bulan');
        $bulan = ($raw_bulan === null || $raw_bulan === '') ? 'all' : $raw_bulan;
        $raw_tahun = $this->input->get('tahun');
        $tahun = ($raw_tahun === null || $raw_tahun === '') ? date('Y') : (int)$raw_tahun;

        $data['bulan'] = $bulan;
        $data['tahun'] = $tahun;
        $data['rekap'] = $this->pengambilan->rekapKaryawan($bulan, $tahun);
        $data['rekap_divisi'] = $this->pengambilan->rekapDivisi($bulan, $tahun);

        $this->load->view('Admin/head');
        $this->load->view('Admin/rekap_pengambilan', $data);
        $this->load->view('Admin/footer');
    }

    private function check_timeout() {
        $inactive = 1800; // 30 menit

        if ($this->session->userdata('last_activity')) {
            $session_life = time() - $this->session->userdata('last_activity');
            if ($session_life > $inactive) {
                $this->session->sess_destroy();
                redirect('Auth');
            }
        }
        $this->session->set_userdata('last_activity', time());
    }

    // ---------------- HELPER: nama bulan ----------------
    private function bulan_nama($n) {
        $arr = [
            1=>"Januari",2=>"Februari",3=>"Maret",4=>"April",5=>"Mei",6=>"Juni",
            7=>"Juli",8=>"Agustus",9=>"September",10=>"Oktober",11=>"November",12=>"Desember"
        ];
        return isset($arr[$n]) ? $arr[$n] : "Bulan-$n";
    }
}
