<?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: gunakan key 'logged_in' yang kita set saat login
            if (!$this->session->userdata('logged_in')) {
                redirect('Auth/Login'); // pastikan route / controller ini ada
            }

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


    public function export_excel() {
    $bulan = $this->input->get('bulan') ?? date('m');
    $tahun = $this->input->get('tahun') ?? date('Y');

    // Ambil data
    $rekap = $this->pengambilan->rekapKaryawan($bulan, $tahun);
    $rekap_divisi = $this->pengambilan->rekapDivisi($bulan, $tahun);

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

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

    // ================= JUDUL =================
    $sheet->mergeCells('A2:E2');
    $sheet->setCellValue('A2', 'Rekap Pengambilan ATK Bulan '.$bulan.' Tahun '.$tahun);
    $sheet->getStyle('A2')->getFont()->setBold(true)->setSize(14);
    $sheet->getStyle('A2')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\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' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                   'startColor' => ['rgb' => '4CAF50']],
        'alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER]
    ];
    $sheet->getStyle('A'.$row.':E'.$row)->applyFromArray($headerStyle);

    // ================= DATA REKAP PER KARYAWAN =================
    $row++;
    $no = 1;
    $total_transaksi = 0;
    $total_item = 0;
    foreach ($rekap as $r) {
        $sheet->setCellValue('A'.$row, $no++);
        $sheet->setCellValue('B'.$row, $r->atk_pengambilan_peminjam);
        $sheet->setCellValue('C'.$row, $r->atk_pengambilan_divisi);
        $sheet->setCellValue('D'.$row, $r->total_transaksi);
        $sheet->setCellValue('E'.$row, $r->total_item);

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

        $total_transaksi += $r->total_transaksi;
        $total_item += $r->total_item;
        $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(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

    // ================= REKAP PER DIVISI =================
    $row += 3; // beri jarak
    $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;

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

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

        $total_karyawan_div += $d->total_karyawan;
        $total_transaksi_div += $d->total_transaksi;
        $total_item_div += $d->total_item;

        $row++;
    }

    // Total Keseluruhan 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(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

    // ================= BORDER =================
    $sheet->getStyle("A4:E$row")->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);

    // ================= AUTO SIZE =================
    foreach (range('A','E') as $col) {
        $sheet->getColumnDimension($col)->setAutoSize(true);
    }

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

    // ================= EXPORT =================
    $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
    $filename = 'Rekap_Pengambilan_'.$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;
}





    public function export_pdf() {
        $bulan = $this->input->get('bulan');
        $tahun = $this->input->get('tahun');

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

        $this->load->library('Pdf');
        $pdf = new Pdf('L','mm','A4');
        $pdf->AddPage();

        // Judul
        $pdf->SetFont('Arial','B',14);
        $pdf->Cell(0,10,"Rekap Pengambilan ATK Bulan $bulan Tahun $tahun",0,1,'C');
        $pdf->Ln(5);

        // Rekap Karyawan
        $pdf->SetFont('Arial','B',12);
        $pdf->Cell(0,10,'Rekap Per Karyawan',0,1);
        $pdf->SetFont('Arial','B',10);
        $pdf->Cell(10,8,'No',1,0,'C');
        $pdf->Cell(60,8,'Nama',1,0,'C');
        $pdf->Cell(50,8,'Divisi',1,0,'C');
        $pdf->Cell(40,8,'Total Transaksi',1,0,'C');
        $pdf->Cell(40,8,'Total Item',1,1,'C');

        $pdf->SetFont('Arial','',10);
        $no=1; $total_trans=0; $total_item=0;
        foreach($rekap as $r){
            $pdf->Cell(10,8,$no++,1,0,'C');
            $pdf->Cell(60,8,$r->atk_pengambilan_peminjam,1,0,'L');
            $pdf->Cell(50,8,$r->atk_pengambilan_divisi,1,0,'C');
            $pdf->Cell(40,8,$r->total_transaksi,1,0,'C');
            $pdf->Cell(40,8,$r->total_item,1,1,'C');
            $total_trans += $r->total_transaksi;
            $total_item  += $r->total_item;
        }
        $pdf->SetFont('Arial','B',10);
        $pdf->Cell(120,8,'Total',1,0,'C');
        $pdf->Cell(40,8,$total_trans,1,0,'C');
        $pdf->Cell(40,8,$total_item,1,1,'C');

        // Rekap Divisi
        $pdf->SetFont('Arial','B',12);
        $pdf->Cell(0,10,'Rekap Per Divisi',0,1);
        $pdf->SetFont('Arial','B',10);
        $pdf->Cell(10,8,'No',1,0,'C');
        $pdf->Cell(60,8,'Divisi',1,0,'C');
        $pdf->Cell(40,8,'Total Karyawan',1,0,'C');
        $pdf->Cell(40,8,'Total Transaksi',1,0,'C');
        $pdf->Cell(40,8,'Total Item',1,1,'C');

        $pdf->SetFont('Arial','',10);
        $no=1; $tk=0; $tt=0; $ti=0;
        foreach($rekap_divisi as $d){
            $pdf->Cell(10,8,$no++,1,0,'C');
            $pdf->Cell(60,8,$d->atk_pengambilan_divisi,1,0,'C');
            $pdf->Cell(40,8,$d->total_karyawan,1,0,'C');
            $pdf->Cell(40,8,$d->total_transaksi,1,0,'C');
            $pdf->Cell(40,8,$d->total_item,1,1,'C');
            $tk += $d->total_karyawan;
            $tt += $d->total_transaksi;
            $ti += $d->total_item;
        }
        $pdf->SetFont('Arial','B',10);
        $pdf->Cell(70,8,'Total',1,0,'C');
        $pdf->Cell(40,8,$tk,1,0,'C');
        $pdf->Cell(40,8,$tt,1,0,'C');
        $pdf->Cell(40,8,$ti,1,1,'C');

        $pdf->Output('D', "Rekap_ATK_$bulan-$tahun.pdf");
    }




public function index()
{
   
    // Ambil filter bulan & tahun dari input GET
        $bulan_filter = $this->input->get('bulan') ?? 'all';
        $tahun_filter = $this->input->get('tahun') ?? date('Y');

        // Panggil model untuk rekap per bulan
        $rekap_bulan = $this->Atk_Pengambilan_model->getRekapPerBulan($bulan_filter, $tahun_filter);

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

        foreach($rekap_bulan as $r){
            $labels[] = "Bulan ".$r->bulan;
            $jumlah[] = $r->total_pengambilan;
             $atk_list[] = $r->atk_list ? $r->atk_list : "-"; // tooltip ATK
        }

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

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

    // Ambil filter
    $bulan_filter = $this->input->get('bulan') ? $this->input->get('bulan') : 'all';
    $tahun_filter = $this->input->get('tahun') ? (int)$this->input->get('tahun') : (int)date('Y');

    // ===== Data Per Bulan =====
    $query_bulan = "SELECT MONTHNAME(tanggal_pengambilan) AS bulan, COUNT(*) AS total
                    FROM atk_pengambilan
                    WHERE YEAR(tanggal_pengambilan) = $tahun_filter";
    if ($bulan_filter != 'all') {
        $query_bulan .= " AND MONTH(tanggal_pengambilan) = $bulan_filter";
    }
    $query_bulan .= " GROUP BY MONTH(tanggal_pengambilan) ORDER BY MONTH(tanggal_pengambilan)";
    $result_bulan = $this->db->query($query_bulan)->result_array();

    $data['bulan']  = !empty($result_bulan) ? array_column($result_bulan, 'bulan') : [];
    $data['jumlah'] = !empty($result_bulan) ? array_column($result_bulan, 'total') : [];

    // ===== Data Per Minggu =====
    if ($bulan_filter != 'all') {
        $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, 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");
        $this->db->order_by("minggu", "ASC");
        $result_minggu = $this->db->get()->result_array();
    } else {
        $this->db->select("WEEK(tanggal_pengambilan, 1) AS minggu, COUNT(*) AS total");
        $this->db->from("atk_pengambilan");
        $this->db->where("YEAR(tanggal_pengambilan)", $tahun_filter);
        $this->db->group_by("minggu");
        $this->db->order_by("minggu", "ASC");
        $result_minggu = $this->db->get()->result_array();
    }

    // Format hasil minggu
    $data['minggu'] = [];
    $data['jumlah_minggu'] = [];
    foreach ($result_minggu as $idx => $row) {
        $data['minggu'][] = "Minggu ke-" . ($idx + 1);
        $data['jumlah_minggu'][] = $row['total'];
    }

    // Kirim filter ke view
    $data['bulan_filter'] = $bulan_filter;
    $data['tahun_filter'] = $tahun_filter;


    

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


public function inventory_dashboard()
{
    $this->load->model("Inventory_model");

    // ambil semua produk dengan jumlah stok
    $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');

    $bulan = $this->input->get('bulan') ?? 'all';
    $tahun = $this->input->get('tahun') ?? date('Y');

    $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 dalam detik

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



    }


