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


class Atk_Pengambilan_Controller extends CI_Controller {

     public function __construct() {
        parent::__construct();
        $this->load->model('Atk_Pengambilan_model', 'pengambilan');
        $this->load->model('ATK_Product_model');
        $this->load->model('Divisi_Categories_model');
        $this->load->model('Atk_Categories_model');
        $this->load->model('Brand_Categories_model');
        $this->load->model('UOM_Categories_model');
        $this->load->model('Inventory_Location_model');
        $this->load->model('ATK_model');
        $this->load->model('Divisi_model');
        $this->load->database();
        $this->load->model('Inventory_Location_Model'); 

        
        

        $this->load->helper(array('form', 'url'));
        $this->load->library(array('session', 'cart', 'form_validation'));
        
    }




    public function index() {
    // Ambil filter dari GET
    $filter_produk = $this->input->get('filter_produk');
    $filter_divisi = $this->input->get('filter_divisi');
    $filter_lokasi = $this->input->get('filter_lokasi');

    // Data untuk dikirim ke view
    $data = [
        "pengambilan"   => $this->Atk_Pengambilan_model->get_filtered_pengambilan(
            $filter_produk, 
            $filter_divisi, 
            $filter_lokasi
        ),
        "product"       => $this->ATK_Product_model->getAll(),
        "divisi"        => $this->Divisi_Categories_model->getAll(),
        "kategori"      => $this->Atk_Categories_model->getAll(),
        "divisi_list"   => $this->Atk_Pengambilan_model->getDivisi(),
        "kategori_list" => $this->Atk_Pengambilan_model->getKategori(),
        "produk"        => $this->Atk_Pengambilan_model->get_all_produk(),
        "lokasi"        => $this->Inventory_Location_Model->getAll(),

        // simpan filter biar bisa ditampilkan kembali di form
        "filter_produk" => $filter_produk,
        "filter_divisi" => $filter_divisi,
        "filter_lokasi" => $filter_lokasi,
    ];

    // Load view
    $this->load->view('Admin/head');
    $this->load->view('admin/atk_pengambilan/view', $data);  
    $this->load->view('Admin/Atk_Pengambilan/add', $data);  
    $this->load->view('Admin/footer');
}



     public function input(){
        $this->load->view('Admin/head');
        $this->load->view('Admin/Atk_Pengambilan/add'); 
        $this->load->view('Admin/footer');
    }

    public function button()
{
    // load semua model yang dibutuhkan
    $this->load->model('Atk_Pengambilan_model');
    $this->load->model('ATK_Product_model');
    $this->load->model('Divisi_Categories_model');
    $this->load->model('Atk_Categories_model');
    $this->load->model('Inventory_Location_Model');

    // kumpulkan data
    $data = [
        "pengambilan" => $this->Atk_Pengambilan_model->getAll(),
        "products"    => $this->ATK_Product_model->getAll(),        // ✅ konsisten pakai plural
        "divisi"      => $this->Divisi_Categories_model->getAll(),
        "kategori"    => $this->Atk_Categories_model->getAll(),
        "lokasi"      => $this->Inventory_Location_Model->getAll(), // ✅ tambahkan lokasi
    ];

    // load view
    $this->load->view('Admin/head_user');
    $this->load->view('Admin/Atk_Pengambilan/button', $data);
    $this->load->view('Admin/Atk_Pengambilan/add_user', $data);
    $this->load->view('Admin/footer_user');
}


    public function tambah()
{
    $produk_id = $this->input->post('atk_pengambilan_product');
    $jumlah    = (int)$this->input->post('atk_pengambilan_jumlah');

    $data = [
        'atk_pengambilan_peminjam' => $this->input->post('atk_pengambilan_peminjam'),
        'atk_pengambilan_divisi'   => $this->input->post('atk_pengambilan_divisi'),
        'atk_pengambilan_product'  => $produk_id,
        'atk_pengambilan_jumlah'   => $jumlah,
        'atk_pengambilan_status'   => 1,
        'created_at'               => date('Y-m-d H:i:s')
    ];

    // Simpan ke tabel atk_pengambilan
    $this->db->insert('atk_pengambilan', $data);

    // --- Update stok produk (kurangi sesuai jumlah yang diambil) ---
    $this->db->set('atk_product_stok', 'atk_product_stok - ' . $jumlah, FALSE);
    $this->db->where('atk_product_id', $produk_id);
    $this->db->update('atk_product');

    // kasih notif sukses
    $this->session->set_flashdata('success', 'Barang berhasil ditambahkan ke pengambilan dan stok diperbarui.');

    redirect('Admin/ATK/Atk_Pengambilan_Controller');
}




   public function tambah_user()
{
    $peminjam = $this->input->post('nama_peminjam');
    $divisi   = $this->input->post('atk_pengambilan_divisi');
    $lokasi   = $this->input->post('atk_pengambilan_lokasi'); // ✅ lokasi ikut disimpan
    $produk_ids = $this->input->post('produk_id');
    $jumlahs    = $this->input->post('atk_pengambilan_jumlah');

    if (!empty($produk_ids) && is_array($produk_ids)) {
        $this->db->trans_start(); // ✅ mulai transaksi

        foreach ($produk_ids as $i => $produk_id) {
            $jumlah = isset($jumlahs[$i]) ? (int)$jumlahs[$i] : 0;
            if ($jumlah <= 0) {
                continue;
            }

            // ✅ Cek stok dulu
            $stok = $this->db->select('atk_product_stok')
                             ->from('atk_product')
                             ->where('atk_product_id', $produk_id)
                             ->get()
                             ->row();

            if (!$stok || $stok->atk_product_stok < $jumlah) {
                $this->session->set_flashdata('pesan_error', 'Stok produk tidak mencukupi untuk salah satu item.');
                redirect('Admin/ATK/Atk_Pengambilan_Controller/button');
                return;
            }

            // ✅ Data insert
            $data = [
                'atk_pengambilan_peminjam' => $peminjam,
                'atk_pengambilan_divisi'   => $divisi,
                'atk_pengambilan_lokasi'   => $lokasi,
                'atk_pengambilan_product'  => $produk_id,
                'atk_pengambilan_jumlah'   => $jumlah,
                'atk_pengambilan_status'   => 1,
                'tanggal_pengambilan'      => date('Y-m-d H:i:s'),
                'created_at'               => date('Y-m-d H:i:s'),
            ];

            $this->db->insert('atk_pengambilan', $data);

            // ✅ Update stok
            $this->db->set('atk_product_stok', 'atk_product_stok - ' . $jumlah, FALSE)
                     ->where('atk_product_id', $produk_id)
                     ->update('atk_product');
        }

        $this->db->trans_complete(); // ✅ selesai transaksi

        if ($this->db->trans_status() === FALSE) {
            $this->session->set_flashdata('pesan_error', 'Terjadi kesalahan saat menyimpan data.');
            redirect('Admin/ATK/Atk_Pengambilan_Controller/button');
        } else {
            $this->session->set_flashdata('pesan_success', 'Barang berhasil diambil dan stok diperbarui.');
            redirect('Admin/ATK/Atk_Pengambilan_Controller/sukses_user');
        }
    } else {
        $this->session->set_flashdata('pesan_error', 'Tidak ada data barang yang dipilih.');
        redirect('Admin/ATK/Atk_Pengambilan_Controller/button');
    }
}






    public function getProductsByCategory()
{
    $category_id = $this->input->post('category_id');
    $location_id = $this->input->post('location_id'); // ✅ ambil lokasi dari Ajax

    $this->load->model("ATK_Product_model");

    $this->db->from('atk_product');
    $this->db->where('atk_product_categories', $category_id);

    if (!empty($location_id)) {
        $this->db->where('atk_product_location', $location_id); 
        // ⚠️ pastikan nama kolom di tabel benar 
        // misal: atk_product_location / inventory_location_id
    }

    $products = $this->db->get()->result();

    echo json_encode($products);
}


    function sukses_user(){
        $this->session->set_flashdata('pesan_success', 'Data Pengambilan ATK berhasil dibuat');
        redirect('Admin/ATK/Atk_Pengambilan_Controller/button');
    }

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

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

    public function view_ubah($id) {
        $pengambilan = $this->Atk_Pengambilan_model->getById($id);

        if (!$pengambilan) {
            show_404();
            return;
        }

        $product_id = $pengambilan->atk_pengambilan_product;
        $product = $this->ATK_Product_model->getById($product_id);

        $data['pengambilan'] = $pengambilan;
        $data['product'] = $product;

        $data["kategori"] = $this->Atk_Categories_model->getAll();
        $data["brand"] = $this->Brand_Categories_model->getAll();
        $data["uom"] = $this->UOM_Categories_model->getAll();
        $data["locations"] = $this->Inventory_Location_model->getAll();
        $data["divisi"] = $this->Divisi_Categories_model->getAll();

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

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

    $id = $this->input->post('id');
    $atk_pengambilan_peminjam = $this->input->post('atk_pengambilan_peminjam');
    $atk_pengambilan_divisi = $this->input->post('atk_pengambilan_divisi');
    $atk_pengambilan_product = $this->input->post('atk_pengambilan_product');
    $jumlah = $this->input->post('atk_pengambilan_jumlah');  
    $status = $this->input->post('atk_pengambilan_status'); 

    $data = array(
        'atk_pengambilan_peminjam'  => $atk_pengambilan_peminjam,
        'atk_pengambilan_divisi'    => $atk_pengambilan_divisi,
        'atk_pengambilan_product'   => $atk_pengambilan_product,
        'atk_pengambilan_jumlah' => $jumlah,
        'atk_pengambilan_status'    => $status,
        'tanggal_pengambilan'       => $tanggal
    );

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

    $this->Atk_Pengambilan_model->update($where, $data, 'atk_pengambilan');
    $this->session->set_flashdata('pesan_success', 'Data Pengambilan ATK berhasil diubah');
    redirect('Admin/ATK/Atk_Pengambilan_Controller');
}


    public function hapus($id){
    $where = array('id' => $id);
    $this->Atk_Pengambilan_model->delete($where, 'atk_pengambilan');
    $this->session->set_flashdata('pesan_success', 'Data Pengambilan ATK berhasil dihapus');
    redirect('Admin/ATK/Atk_Pengambilan_Controller');
}

    ///public function tambah_keranjang() {
    /// $cart = $this->session->userdata('keranjang_atk') ?? [];

    ///$item = [
    /// 'peminjam' => $this->input->post('peminjam'),
    /// 'divisi'   => $this->input->post('divisi'),
    ///'product'  => $this->input->post('product'),
    /// 'jumlah'   => $this->input->post('jumlah'),
    /// 'status'   => 1
    ///];

    ///  $cart[] = $item;
    ///  $this->session->set_userdata('keranjang_atk', $cart);

    ///   redirect('Admin/ATK/Atk_Pengambilan_Controller/lihat_keranjang');
    ///}
    ///  public function checkout() {
    ///   $cart = $this->session->userdata('keranjang_atk');

    ///   if (!$cart || count($cart) == 0) {
    ///     redirect('Admin/ATK/Atk_Pengambilan_Controller/lihat_keranjang');
    ///    }

    ///   foreach ($cart as $item) {
    ///     $data = [
    ///          'atk_pengambilan_peminjam' => $item['peminjam'],
    ///          'atk_pengambilan_divisi'   => $item['divisi'],
    ///          'atk_pengambilan_product'  => $item['product'],
    ///          'atk_pengambilan_jumlah'   => $item['jumlah'],
    ///          'atk_pengambilan_status'   => 1
    ///      ];
    ///      $this->db->insert('atk_pengambilan', $data);
    ///   }

    ///   $this->session->unset_userdata('keranjang_atk');

    ///   redirect('Admin/ATK/Atk_Pengambilan_Controller');
    ///    }

    public function add_user_by_id($id) {
        $data['barang'] = $this->Atk_Model->get_barang_by_id($id);
        $this->load->view('Admin/Atk_Pengambilan/add_user', $data);
        return $this->db->get_where('atk_barang', ['id_barang' => $id])->row();
    }

    public function get_produk_by_kategori() {
        $id_kategori = $this->input->post('id_kategori');
        $produk = $this->ATK_model->getProdukByKategori($id_kategori);
        echo json_encode($produk);
    }

    public function add_user() {
        $data['product'] = $this->ATK_model->getAllProduk();
        $data['kategori'] = $this->ATK_model->get_all_kategori();
        $data['divisi'] = $this->ATK_model->get_all_divisi();

        $this->load->view('Admin/Atk_Pengambilan/add_user', $data);
    }

    public function form_pengambilan()
    {
        $data['produk'] = $this->ATK_model->getAllProduk();
        $this->load->view('Admin/Atk_Pengambilan/add_user', $data);
    }

    public function detail($id)
    {
        $this->load->model('Atk_Pengambilan_model');
        $data['pengambilan'] = $this->Atk_Pengambilan_model->getById($id);
        $this->load->view('Admin/Atk_Pengambilan/detail', $data);
    }

    public function masukkan_keranjang()
    {
        $item = [
            'name'     => $this->input->post('name'),
            'qty'      => $this->input->post('qty'),
            'kategori' => $this->input->post('kategori'),
            'divisi'   => $this->input->post('divisi'),
            'peminjam' => $this->input->post('peminjam')
        ];

        $cart = $this->session->userdata('cart') ?? [];
        $cart[] = $item;
        $this->session->set_userdata('cart', $cart);

        $this->session->set_flashdata('success', 'Barang berhasil dimasukkan ke keranjang.');
        redirect('atk_pengambilan');
    }

    public function add_to_cart()
    {
        $item = [
            'kode_barang' => $this->input->post('kode_barang'),
            'nama_barang' => $this->input->post('nama_barang'),
            'jumlah'              => $this->input->post('jumlah'),
            'tanggal_pengambilan' => $this->input->post('tanggal_pengambilan')
        ];

        $cart = $this->session->userdata('cart') ?? [];
        $cart[] = $item;
        $this->session->set_userdata('cart', $cart);

        redirect('Admin/Atk_Pengambilan_Controller/cart_view');

    }

  ///  public function cart_view()
  ///  {
  ///      $data['cart'] = $this->session->userdata('cart') ?? [];
  ///      $this->load->view('admin/atk/cart_view', $data);
  ///  }

    public function view_data_pengambilan()
    {
        $this->load->model('Atk_Pengambilan_model');
        $data['pengambilan'] = $this->Atk_Pengambilan_model->get_pengambilan_with_product();
        $this->load->view('Admin/Atk_Pengambilan/view_pengambilan', $data);
    }

    public function save()
{
    $peminjam = $this->session->userdata('username');
    if (empty($peminjam)) {
        show_error("Session 'username' tidak ditemukan. Pastikan user login dulu.");
        return;
    }

    $products = $this->input->post('atk_pengambilan_product');  // array
    $jumlahs  = $this->input->post('atk_pengambilan_jumlah');   // array
    $divisi   = $this->input->post('atk_pengambilan_divisi');

    foreach ($products as $i => $product_id) {
        $jumlah = (int) $jumlahs[$i];

        // cek stok
        $stok = $this->ATK_Product_model->getStock($product_id);
        if ($jumlah > $stok) {
            $this->session->set_flashdata('error', "Stok produk ID $product_id tidak mencukupi");
            redirect('Admin/Atk_Pengambilan_Controller/add');

            return;
        }

        // simpan data per item
        $data = [
            'atk_pengambilan_peminjam' => $peminjam,
            'atk_pengambilan_divisi'   => $divisi,
            'atk_pengambilan_product'  => $product_id,
            'atk_pengambilan_jumlah'   => $jumlah,
            'atk_pengambilan_status'   => 1,
            'tanggal_pengambilan'      => date('Y-m-d H:i:s')
        ];
        $this->Atk_Pengambilan_model->save($data);

        // kurangi stok
        $this->ATK_Product_model->reduceStock($product_id, $jumlah);
    }

    $this->session->set_flashdata('success', 'Pengambilan berhasil disimpan');
    redirect('admin/ATK/Atk_Pengambilan_Controller');
}

    public function create(){
    $this->load->view('Admin/ATK/form_pengambilan');
}

public function add(){
        // ambil produk dari ATK_Product_model
        $data['produk'] = $this->ATK_Product_model->getAll();
        $data['divisi']   = $this->Divisi_Categories_model->getAll();
        $data['kategori'] = $this->Atk_Categories_model->getAll();

        $this->load->view('Admin/head');
        $this->load->view('Admin/Atk_Pengambilan/add', $data); // <-- gunakan add.php
        $this->load->view('Admin/footer');
    }
    public function insert() {
        $data = [
            'atk_pengambilan_peminjam' => $this->input->post('peminjam'),
            'atk_pengambilan_divisi'   => $this->input->post('divisi'),
            'atk_pengambilan_product'  => $this->input->post('product'),
            'atk_pengambilan_jumlah'   => $this->input->post('jumlah'),
            'atk_pengambilan_status'   => 1,
            'tanggal_pengambilan'      => date('Y-m-d')
        ];

        $this->Atk_Pengambilan_model->insert($data);
        $this->session->set_flashdata('pesan_success', 'Data berhasil ditambahkan!');
        redirect('Admin/ATK/Atk_Pengambilan_Controller');
    }
    
public function cetak_pdf()
{
    $this->load->library('pdf');
    $this->load->model('Atk_Pengambilan_model');

    // ✅ Ambil filter dari GET (sama kayak di index)
    $filter_produk = $this->input->get('filter_produk');
    $filter_divisi = $this->input->get('filter_divisi');
    $filter_lokasi = $this->input->get('filter_lokasi');

    // ✅ Ambil data sesuai filter
    $data = $this->Atk_Pengambilan_model->get_filtered_pengambilan($filter_produk, $filter_divisi, $filter_lokasi);

    // ✅ Generate PDF
    $pdf = new Pdf();
    $pdf->AddPage('L');
    $pdf->SetFont('Arial','B',12);

    // Header tabel
    $pdf->Cell(10,10,'No',1,0,'C');
    $pdf->Cell(70,10,'Nama Peminjam',1,0,'C');
    $pdf->Cell(70,10,'Nama Barang',1,0,'C');
    $pdf->Cell(30,10,'Qty',1,0,'C');
    $pdf->Cell(50,10,'Tanggal',1,0,'C');
    $pdf->Cell(40,10,'Jam',1,1,'C');

    // Isi data
    $pdf->SetFont('Arial','',11);
    $no = 1;
    foreach ($data as $row) {
        $pdf->Cell(10,10,$no++,1,0,'C');

        $x = $pdf->GetX();
        $y = $pdf->GetY();
        $pdf->MultiCell(70,10,$row->atk_pengambilan_peminjam,1,'L');
        $pdf->SetXY($x+70,$y);

        $pdf->Cell(70,10,$row->atk_product_nama,1,0,'L');
        $pdf->Cell(30,10,$row->atk_pengambilan_jumlah,1,0,'C');

        $tanggal = date('d-m-Y', strtotime($row->tanggal_pengambilan));
        $jam     = date('H:i', strtotime($row->tanggal_pengambilan));

        $pdf->Cell(50,10,$tanggal,1,0,'C');
        $pdf->Cell(40,10,$jam,1,1,'C');
    }

    $pdf->Output('I','laporan_pengambilan.pdf');
}








function Header() {
    // Tentukan path logo
    $logoPath = FCPATH . 'assets/img/asiaserv-logo.png';

    if (file_exists($logoPath)) {
        // Jika file logo ada → tampilkan logo di kiri
        $this->Image($logoPath, 10, 6, 30); // x=10, y=6, width=30
    } else {
        // Jika logo tidak ada → tampilkan teks fallback
        $this->SetFont('Arial','B',12);
        $this->Cell(0,10,'ASIASERV Asset Management',0,1,'C');
    }

    // Pindah ke bawah agar ada jarak
    $this->Ln(20);
}


    function Footer() {
        $this->SetY(-15); // 15mm dari bawah
        $this->SetFont('Arial', 'I', 8);
        $this->Cell(0, 10, 'Halaman ' . $this->PageNo(), 0, 0, 'C');
    }

public function get_all_products() {
    return $this->db->get('atk_product')->result();
}

public function export_excel()
{
    // Ambil filter dari GET/POST (dua-duanya didukung)
    $filter_produk = $this->input->get_post('filter_produk', true);
    $filter_divisi = $this->input->get_post('filter_divisi', true);

    // Fallback: kalau kosong, ambil dari session (diset saat user klik Filter di view)
    if ($filter_produk === null || $filter_produk === '') {
        $filter_produk = $this->session->userdata('filter_produk');
    }
    if ($filter_divisi === null || $filter_divisi === '') {
        $filter_divisi = $this->session->userdata('filter_divisi');
    }

    // Ambil data sesuai filter
    $this->load->model('Atk_Pengambilan_model', 'pengambilan');
    $pengambilan = $this->pengambilan->get_filtered_pengambilan($filter_produk, $filter_divisi);

    // Bangun Spreadsheet TANPA kirim header/output di sini
    $spreadsheet = $this->generate_excel($pengambilan);

    // Output ke browser (header cukup di sini saja)
    $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);

    // Pastikan buffer bersih
    if (ob_get_length()) { ob_end_clean(); }

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

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


private function generate_excel($pengambilan)
{
    require 'vendor/autoload.php';

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

    // ===== Logo =====
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('Asiaserv Logo');
$drawing->setDescription('Asiaserv Logo');
$drawing->setPath('assets/img/asiaserv-logo.png');
$drawing->setHeight(60); // kecilin dikit biar hemat tempat
$drawing->setCoordinates('A1');
$drawing->setWorksheet($sheet);

// ===== Judul =====
$sheet->setCellValue('A2','Laporan Pengambilan ATK');
$sheet->mergeCells('A2:F2');
$sheet->getStyle('A2')->getFont()->setBold(true)->setSize(14);
$sheet->getStyle('A2')->getAlignment()
      ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)
      ->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);

// ===== Header Tabel =====
$headerRow = 4;
$sheet->fromArray(['No','Nama Peminjam','Divisi','Produk ATK','Jumlah','Tanggal Pengambilan'], null, 'A'.$headerRow);
$sheet->getStyle('A'.$headerRow.':F'.$headerRow)->getFont()->setBold(true);
$sheet->getStyle('A'.$headerRow.':F'.$headerRow)->getAlignment()
      ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
$sheet->getStyle('A'.$headerRow.':F'.$headerRow)->getFill()
      ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
      ->getStartColor()->setRGB('D9EAD3');


    // ===== Isi Data =====
    $row = $headerRow + 1;
    $no  = 1;
    foreach ($pengambilan as $p) {
        $sheet->setCellValue('A'.$row, $no++);
        $sheet->setCellValue('B'.$row, $p->atk_pengambilan_peminjam);
        $sheet->setCellValue('C'.$row, $p->divisi_categories_nama);
        $sheet->setCellValue('D'.$row, $p->atk_product_nama);
        $sheet->setCellValue('E'.$row, $p->atk_pengambilan_jumlah);
        $sheet->setCellValue('F'.$row, \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel(strtotime($p->tanggal_pengambilan)));
        $sheet->getStyle('F'.$row)->getNumberFormat()
            ->setFormatCode('dd-mm-yy');
        $row++;
    }

    // ===== Alignment setelah loop =====
    $start = $headerRow + 1;
    $end   = $row - 1; // baris terakhir isi

    if ($end >= $start) {
        // A, C–F center
        $sheet->getStyle("A{$start}:A{$end}")
              ->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle("C{$start}:F{$end}")
              ->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

        // B (Peminjam) kiri
        $sheet->getStyle("B{$start}:B{$end}")
              ->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);

        // Optional: vertical center biar rapi
        $sheet->getStyle("A{$start}:F{$end}")
              ->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
    }

    // ===== Border + Autosize =====
    $sheet->getStyle('A'.$headerRow.':F'.max($end, $headerRow))
          ->getBorders()->getAllBorders()
          ->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);

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

    // JANGAN kirim header/save di sini. Cukup return spreadsheet.
    return $spreadsheet;
}



public function filter()
{
    // Terima kedua kemungkinan nama field dari form
    $filter_produk = $this->input->post('filter_produk', true);
    $filter_divisi = $this->input->post('filter_divisi', true);

    // Backward-compat: kalau pakai nama lama
    if ($filter_produk === null) {
        $filter_produk = $this->input->post('produk_id', true);
    }
    if ($filter_divisi === null) {
        $filter_divisi = $this->input->post('divisi_id', true);
    }

    // Simpan ke session supaya export_excel bisa pakai
    $this->session->set_userdata('filter_produk', $filter_produk);
    $this->session->set_userdata('filter_divisi', $filter_divisi);

    // Ambil data view pakai filter yang sama
    $this->load->model('Atk_Pengambilan_model');
    $data['pengambilan'] = $this->Atk_Pengambilan_model->get_filtered_pengambilan($filter_produk, $filter_divisi);

    // Dropdown helper (opsional, sesuaikan view kamu)
    $data['produk'] = $this->Atk_Pengambilan_model->get_all_produk();
    $data['divisi'] = $this->Atk_Pengambilan_model->get_all_divisi();

    // Kirim juga nilai filter ke view agar form tetap menampilkan pilihan terakhir
    $data['filter_produk'] = $filter_produk;
    $data['filter_divisi'] = $filter_divisi;

    $this->load->view('admin/atk_pengambilan/view', $data);
}

public function diagram_perbulan() {
    $data['perbulan'] = $this->pengambilan->get_pengambilan_perbulan();
    $this->load->view('admin/atk/diagram_perbulan_view', $data);
}

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

    $data['jumlah_karyawan'] = $this->pengambilan->totalKaryawanATK();

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


}

    

