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

class Atk_Product_Controller extends CI_Controller {

    public function __construct(){
		parent::__construct();
		$this->load->model("ATK_Product_model");
        $this->load->model("ATK_Categories_model");
        $this->load->model("Location_model");
        $this->load->model("Inventory_Types_model");
        $this->load->model("Brand_Categories_model");
        $this->load->model("Uom_Categories_model");
		$this->load->library('session');
        $this->load->library('pdf');
	}

	

    public function index()
    {
        // Ambil filter kategori dari GET, jika ada
        $filter_kategori = $this->input->get('filter_kategori');


        $filter_lokasi = $this->input->get('filter_lokasi');


        // Ambil semua data ATK Product dengan filter kategori (jika diterapkan)
        $data["product"] = $this->ATK_Product_model->getAll($filter_kategori, $filter_lokasi);
        $data["kategori"] = $this->ATK_Categories_model->getAll();
        $data["location"] = $this->Location_model->getAll();
        $data["type"] = $this->Inventory_Types_model->getAll();
        $data["brand"] = $this->Brand_Categories_model->getAll();
        $data["uom"] = $this->Uom_Categories_model->getAll();

        // Sertakan filter untuk menjaga state dropdown kategori
        $data['filter_kategori'] = $filter_kategori;
        $data['filter_lokasi'] = $filter_lokasi;


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

    public function export_excel()
{
    $filter_kategori = $this->input->get('filter_kategori');
    $filter_lokasi   = $this->input->get('filter_lokasi');

    $data['product'] = $this->ATK_Product_model->getFiltered($filter_kategori, $filter_lokasi);

    $this->generate_excel($data);
}

private function generate_excel($data)
{
    // --- KONFIGURASI AWAL ---
    
    require_once FCPATH . 'vendor/autoload.php';

    // Konstanta untuk baris/kolom
    $HEADER_START_ROW = 7;
    $DATA_START_ROW = $HEADER_START_ROW + 1;
    $TITLE_START_ROW = 3;
    $LAST_COLUMN = 'H';
    $REPORT_NAME = 'LAPORAN DATA PRODUK ATK';
    $COMPANY_NAME = 'PT ASIASERV INDONESIA';
    $FILENAME = 'Data_ATK_' . date('Ymd_His') . '.xlsx';

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

    // --- PROPERTI DOKUMEN ---
    $spreadsheet->getProperties()
        ->setCreator('System Report Generator')
        ->setTitle($REPORT_NAME);
    
    // --- LOGO (KIRI ATAS - A1) ---
    $logoPath = FCPATH . 'assets/img/asiaserv-logo.png'; 
    if (file_exists($logoPath)) {
        $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
        $drawing->setName('Asiaserv Logo');
        $drawing->setPath($logoPath);
        $drawing->setHeight(80); 
        $drawing->setCoordinates('A1'); 
        $drawing->setWorksheet($sheet);
    }

    // --- JUDUL LAPORAN (Rata Tengah) ---
    
    $sheet->setCellValue('A' . $TITLE_START_ROW, $REPORT_NAME);
    $sheet->setCellValue('A' . ($TITLE_START_ROW + 1), $COMPANY_NAME);
    
    $sheet->mergeCells('A' . $TITLE_START_ROW . ':' . $LAST_COLUMN . $TITLE_START_ROW);
    $sheet->mergeCells('A' . ($TITLE_START_ROW + 1) . ':' . $LAST_COLUMN . ($TITLE_START_ROW + 1));
    
    $styleTitle = [
        'alignment' => [
            'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, 
            'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
        ],
        'font' => [
            'bold' => true,
            'size' => 15,
        ],
    ];
    $sheet->getStyle('A' . $TITLE_START_ROW . ':' . $LAST_COLUMN . ($TITLE_START_ROW + 1))->applyFromArray($styleTitle);

    // --- HEADER TABEL (Rata Tengah) ---
    
    $header = ['No', 'Nama ATK', 'Brand', 'Kategori', 'Stok', 'Satuan', 'Lokasi', 'Notes'];
    $sheet->fromArray($header, null, 'A' . $HEADER_START_ROW);
    
    $styleTableHeader = [
        'font' => ['bold' => true, 'size' => 10],
        'alignment' => [
            'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, 
            'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
        ],
        'fill' => [
            'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
            'startColor' => ['rgb' => 'D9EAD3'],
        ],
        'borders' => [
            'allBorders' => [
                'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
            ],
        ],
    ];
    
    $headerRange = 'A' . $HEADER_START_ROW . ':' . $LAST_COLUMN . $HEADER_START_ROW;
    $sheet->getStyle($headerRange)->applyFromArray($styleTableHeader);

    // --- DATA TABEL (Rata Tengah) ---
    
    $row = $DATA_START_ROW;
    $no = 1;
    
    foreach ($data['product'] as $p) {
        $sheet->setCellValue("A{$row}", $no++);
        $sheet->setCellValue("B{$row}", $p->atk_product_nama);
        $sheet->setCellValue("C{$row}", $p->brand_categories_nama);
        $sheet->setCellValue("D{$row}", $p->atk_categories_nama);
        $sheet->setCellValueExplicit("E{$row}", $p->atk_product_stok, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC); 
        $sheet->setCellValue("F{$row}", $p->uom_categories_nama);
        $sheet->setCellValue("G{$row}", $p->inventory_location_nama);
        $sheet->setCellValue("H{$row}", $p->atk_product_notes);
        $row++;
    }
    
    // --- STYLING DATA ---
    
    $dataRange = 'A' . $DATA_START_ROW . ':' . $LAST_COLUMN . ($row - 1);
    
    $styleTableData = [
        'alignment' => [
            'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, 
            'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
            'wrapText' => true, 
        ],
        'borders' => [
            'allBorders' => [
                'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
            ],
        ],
    ];
    $sheet->getStyle($dataRange)->applyFromArray($styleTableData);
    
    
    // --- PENGATURAN LEBAR KOLOM MANUAL ---
    // Ganti nilai di bawah (misalnya 10, 25, 12, dll.) sesuai kebutuhan Anda.
    // Lebar dihitung dalam 'character width' default font.
    
    $sheet->getColumnDimension('A')->setWidth(5);   // No
    $sheet->getColumnDimension('B')->setWidth(26);  // Nama ATK
    $sheet->getColumnDimension('C')->setWidth(10);  // Brand
    $sheet->getColumnDimension('D')->setWidth(15);  // Kategori
    $sheet->getColumnDimension('E')->setWidth(7);  // Stok
    $sheet->getColumnDimension('F')->setWidth(12);  // Satuan
    $sheet->getColumnDimension('G')->setWidth(20);  // Lokasi
    $sheet->getColumnDimension('H')->setWidth(25);  // Notes (Paling lebar)
    
    // Freeze Pane (membekukan header tabel)
    $sheet->freezePane('A' . $DATA_START_ROW);

$sheet->getPageSetup()->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE);
    // --- OUTPUT FILE ---
    
    ob_clean(); 
    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;
}

    public function input()
	{
		// $x['idKategori']=$this->kategori_model->autoId();
		$this->load->view('Admin/head');
		$this->load->view('Admin/Atk_Product/add');
		$this->load->view('Admin/footer');
	}

	
    public function tambah(){
    $inventory = $this->ATK_Product_model;
    // otomatis update_date diisi di model
    $result = $inventory->save();
    if($result > 0) $this->sukses();
    else $this->gagal();	
}


	function sukses(){
        $this->session->set_flashdata('pesan_success', 'Data Product ATK berhasil dibuat');
        redirect('Admin/ATK/Atk_Product_Controller');
	}

	function gagal(){
        $this->session->set_flashdata('pesan_error', 'Data Location berhasil dibuat');
        redirect('Admin/ATK/Atk_Product_Controller');
	}


    // public function view_ubah($atk_product_id) {
    //     $where = array('atk_product_id' => $atk_product_id);
    //     $data['inventory'] = $this->ATK_Product_model->view_update($where, 'inventory')->row(); // Use row() for a single object
    //     $this->load->view('Admin/head');
    //     $this->load->view('Admin/Inventory/update', $data);
    //     $this->load->view('Admin/footer');
    // }

    public function view_ubah($atk_product_id) {
        $where = array('atk_product_id' => $atk_product_id);
        $data['product'] = $this->ATK_Product_model->view_update($where, 'atk_product')->row();
        $data['locations'] = $this->Location_model->getAll(); // untuk lokasi
        $data['types'] = $this->Inventory_Types_model->getAll(); // untuk tipe
        $data['brand']=$this->Brand_Categories_model->getAll();
        $data['uom']=$this->Uom_Categories_model->getAll();
        $data["kategori"]=$this->ATK_Categories_model->getAll();
        $this->load->view('Admin/head');
        $this->load->view('Admin/Atk_Product/update', $data);
        $this->load->view('Admin/footer');
    }
    
    

    // Simpan Ubah ke Database
    public function update(){

        date_default_timezone_set("Asia/Jakarta");
        $tanggal = date("Y-m-d H:i:s");

		$post = $this->input->post();	
		$atk_product_id 		= $this->input->post('atk_product_id');
        $atk_product_nama = $this->input->post('atk_product_nama');
        $atk_product_stok = $this->input->post('atk_product_stok');
        $atk_product_uom = $this->input->post('atk_product_uom');
        $atk_product_inventory_types = $this->input->post('atk_product_inventory_types');
        $atk_product_categories = $this->input->post('atk_product_categories');
        $atk_product_brand = $this->input->post('atk_product_brand');
        $atk_product_location = $this->input->post('atk_product_location');
        $atk_product_notes = $this->input->post('atk_product_notes');
        // $atk_product_status = $this->input->post('atk_product_status');
        // $updated_at = $tanggal;

   

        $data = array(
			'atk_product_id'         => $atk_product_id,
			'atk_product_nama'       => $atk_product_nama,
            'atk_product_stok'       => $atk_product_stok,
            'atk_product_uom'       => $atk_product_uom,
            'atk_product_inventory_types'       => 9,
            'atk_product_categories'       => $atk_product_categories,
            'atk_product_brand'       => $atk_product_brand,
            'atk_product_location'       => $atk_product_location,
            'atk_product_notes'       => $atk_product_notes,
            'atk_product_status'       => 1,
            'update_date' => date("Y-m-d H:i:s")
           
        );

        $where = array(
            'atk_product_id'       => $atk_product_id
        );

        $this->ATK_Product_model->update($where,$data,'atk_product');
        $this->session->set_flashdata('pesan_success', 'Data Product ATK berhasil diubah');
        redirect('Admin/ATK/Atk_Product_Controller');
    }

	public function hapus($atk_product_id){
		$data = array(
            'atk_product_id'       => $atk_product_id,
            'atk_product_status'        => 0
        );

        $where = array(
            'atk_product_id'       => $atk_product_id
        );
        $this->ATK_Product_model->update($where,$data,'atk_product');
        $this->session->set_flashdata('pesan_success', 'Data Product ATK berhasil dihapus');
        redirect('Admin/ATK/Atk_Product_Controller');
    }
    
public function export_pdf()
{
    $filter_kategori = $this->input->get('filter_kategori');
    $filter_lokasi   = $this->input->get('filter_lokasi');

    $product = $this->ATK_Product_model->get_data_filtered(
        $filter_kategori,
        $filter_lokasi
    );

    // Mulai PDF
    $pdf = new Pdf('L', 'mm', 'A4');
    $pdf->AddPage();

    // Judul
    $pdf->SetFont('Arial','B',14);
    $pdf->Cell(0,7,'LAPORAN DATA PRODUCT (ATK)',0,1,'C');
    $pdf->SetFont('Arial','',12);
    $pdf->Cell(0,7,'PT ASIASERV INDONESIA',0,1,'C');
    $pdf->Ln(5);

    // Header Tabel
    $pdf->SetFont('Arial','B',10);
    $pdf->SetFillColor(240,240,240);

   $header = [
    ['label'=>'No.', 'width'=>10],
    ['label'=>'Nama Produk', 'width'=>50],
    ['label'=>'Brand', 'width'=>30],
    ['label'=>'Kategori', 'width'=>30],
    ['label'=>'Stok', 'width'=>15],
    ['label'=>'Unit', 'width'=>15],
    ['label'=>'Lokasi', 'width'=>33],
    ['label'=>'Notes', 'width'=>40],
    ['label'=>'Last Update', 'width'=>35],   // ⬅ kolom baru
            
];


    foreach ($header as $col) {
        $pdf->Cell($col['width'], 8, $col['label'], 1, 0, 'C', true);
    }
    $pdf->Ln();

    // Isi Tabel
    $pdf->SetFont('Arial','',9);

    if (!empty($product)) {
    $no = 1;
    foreach ($product as $p) {

        // Kolom nomor
        $pdf->Cell(10, 7, $no++, 1, 0, 'C');

        // Nama produk
        $pdf->Cell(50, 7, $p->atk_product_nama, 1, 0, 'L');

        // Brand
        $pdf->Cell(30, 7, $p->brand_categories_nama, 1, 0, 'C');

        // Kategori
        $pdf->Cell(30, 7, $p->atk_categories_nama, 1, 0, 'C');

        // Stok
        $pdf->Cell(15, 7, $p->atk_product_stok, 1, 0, 'C');

        // UOM
        $pdf->Cell(15, 7, $p->uom_categories_nama, 1, 0, 'C');

        // Lokasi
        $pdf->Cell(33, 7, $p->inventory_location_nama, 1, 0, 'C');

        // Notes (fallback untuk null/kosong)
        $notes = !empty($p->atk_product_notes) ? $p->atk_product_notes : '-';
        $pdf->Cell(40, 7, $notes, 1, 0, 'L');

        // Last Update (ambil dari field yg benar: update_date)
        $last_update = !empty($p->update_date) ? $p->update_date : '-';
        $pdf->Cell(35, 7, $last_update, 1, 1, 'C');
    }

    } else {
        $pdf->Cell(290, 10, 'Tidak ada data ATK ditemukan berdasarkan filter.', 1, 1, 'C');
    }

    // Output PDF
    $pdf->Output('D', 'Laporan_ATK.pdf');
}


    
}
?>