<?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()
{
    date_default_timezone_set('Asia/Jakarta'); // Pastikan zona waktu sudah di set

    $produk_id = $this->input->post('atk_pengambilan_product');
    $jumlah    = (int)$this->input->post('atk_pengambilan_jumlah');
    // =========================================================================
    // ✅ PERBAIKAN 1: Ambil input 'notes'
    $notes = $this->input->post('notes');
    // =========================================================================
    
    $data = [
        'atk_pengambilan_peminjam' => $this->input->post('atk_pengambilan_peminjam'),
        'atk_pengambilan_divisi'   => $this->input->post('atk_pengambilan_divisi'),
        // ✅ PASTIKAN ANDA JUGA MENGAMBIL LOKASI (dari form sebelumnya)
        'atk_pengambilan_lokasi'   => $this->input->post('atk_pengambilan_lokasi'), 
        'atk_pengambilan_product'  => $produk_id,
        'atk_pengambilan_jumlah'   => $jumlah,
        'atk_pengambilan_status'   => 1,
        // ✅ PERBAIKAN 2: Masukkan 'notes' ke dalam array data
        'notes'                    => $notes, 
        'created_at'               => date('Y-m-d H:i:s')
    ];

    // Simpan ke tabel atk_pengambilan
    // Menggunakan $this->db->insert() sudah benar, tidak perlu lewat model jika hanya insert
    $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');
    $notes = $this->input->post('notes');
    $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,
                'notes' => $notes,
                '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;
    }

    // Ambil data produk yang sedang diedit (tidak wajib dikirim ke view jika sudah ada di $pengambilan)
    $product_id = $pengambilan->atk_pengambilan_product;
    $product = $this->ATK_Product_model->getById($product_id);

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

  
    
    // 1. Ambil daftar LOKASI (Sudah benar, tapi kita konsistenkan namanya)
    $data["lokasi"] = $this->Inventory_Location_model->getAll();
    
    // 2. Ambil daftar PRODUK/ATK Name (Ini yang hilang!)
    // Asumsi: Model ATK_Product_model memiliki fungsi getAll()
    $data["produk"] = $this->ATK_Product_model->getAll(); 
    
    // 3. Ambil daftar DIVISI (Sudah benar)
    $data["divisi"] = $this->Divisi_Categories_model->getAll();

    // Data lain
    $data["kategori"] = $this->Atk_Categories_model->getAll();
    $data["brand"] = $this->Brand_Categories_model->getAll();
    $data["uom"] = $this->UOM_Categories_model->getAll();

    // --- PERBAIKAN SAMPAI SINI ---

    $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");
    

    $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_lokasi = $this->input->post('atk_pengambilan_lokasi'); 
    $atk_pengambilan_product = $this->input->post('atk_pengambilan_product');
    $jumlah = $this->input->post('atk_pengambilan_jumlah');  
    $status = $this->input->post('atk_pengambilan_status'); 
    $notes = $this->input->post('notes'); 

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

    $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()
{
    date_default_timezone_set('Asia/Jakarta');
    $this->load->library('pdf');
    $this->load->model('Atk_Pengambilan_model');

    // 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');

    // 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'); // L for Landscape
    
    // --- Lebar Kolom Didefinisikan di sini ---
    // Lebar Kolom (Total = 277)
    $w = [10, 45, 55, 30, 30, 40, 30, 37]; 
    $safe_y_limit = 180; 
    $tinggi_baris = 7; 

    // ==========================================================
    // JUDUL UTAMA LAPORAN
    // ==========================================================
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(277, 10, 'LAPORAN PENGAMBILAN STASIONARI (ATK)', 0, 1, 'C');
    
    $pdf->SetFont('Arial','I',10);
    $pdf->Cell(277, 5, 'Data per tanggal: ' . date('d-m-Y H:i:s'), 0, 1, 'C');
    $pdf->Ln(5); 

    // ==========================================================
    // HEADER TABEL
    // ==========================================================
    $this->drawTableHeader($pdf, $w); // Menggunakan $w yang baru

    // ==========================================================
    // ISI DATA
    // ==========================================================
    $pdf->SetFont('Arial','',9);
    $no = 1;

    foreach ($data as $row) {
        
        // Cek Batas Halaman
        if ($pdf->GetY() > $safe_y_limit) { 
            $pdf->AddPage('L');
            $this->drawTableHeader($pdf, $w); // Gambar ulang header
            $pdf->SetFont('Arial','',9); 
        }
        
        // --- DATA ROW ---
        // Penyelarasan kolom sesuai permintaan sebelumnya (C=Tengah, L=Kiri)
        
        // 1. No (C)
        $pdf->Cell($w[0], $tinggi_baris, $no++, 1, 0, 'C'); 

        // 2. Peminjam (L)
        $pdf->Cell($w[1], $tinggi_baris, $row->atk_pengambilan_peminjam, 1, 0, 'L');
        
        // 3. Nama Barang (L)
        $pdf->Cell($w[2], $tinggi_baris, $row->atk_product_nama, 1, 0, 'L'); 

        // 4. Divisi (C)
        $pdf->Cell($w[3], $tinggi_baris, $row->divisi_categories_nama, 1, 0, 'C'); 

        // 5. Lokasi (C)
        $pdf->Cell($w[4], $tinggi_baris, $row->inventory_location_nama, 1, 0, 'C'); // <--- Kolom Location

        // 6. Tanggal Ambil (C)
        $pdf->Cell($w[5], $tinggi_baris, date('d-m-Y H:i', strtotime($row->tanggal_pengambilan)), 1, 0, 'C'); 

        // 7. Jumlah (C)
        $pdf->Cell($w[6], $tinggi_baris, $row->atk_pengambilan_jumlah, 1, 0, 'C'); 

        // 8. Catatan (L)
        $pdf->Cell($w[7], $tinggi_baris, $row->notes, 1, 1, 'L'); // <--- Kolom Notes (Catatan)
    }

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

// ==========================================================
// FUNGSI BANTUAN UNTUK MENGGAMBAR ULANG HEADER
// ==========================================================
private function drawTableHeader($pdf, $w)
{
    $pdf->SetFont('Arial','B',10);
    $pdf->SetFillColor(200, 220, 255); // Warna latar belakang header
    
    // Header selalu rata tengah
    $pdf->Cell($w[0], 7, 'No', 1, 0, 'C', 1);
    $pdf->Cell($w[1], 7, 'Peminjam', 1, 0, 'C', 1);
    $pdf->Cell($w[2], 7, 'Nama Barang', 1, 0, 'C', 1);
    $pdf->Cell($w[3], 7, 'Divisi', 1, 0, 'C', 1);
    $pdf->Cell($w[4], 7, 'Lokasi', 1, 0, 'C', 1); // <--- Kolom Location
    $pdf->Cell($w[5], 7, 'Tanggal Ambil', 1, 0, 'C', 1);
    $pdf->Cell($w[6], 7, 'Jumlah', 1, 0, 'C', 1);
    $pdf->Cell($w[7], 7, 'Catatan', 1, 1, 'C', 1); // <--- Kolom Notes (Catatan)
}



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()
{
    // ... kode yang sudah ada ...
    $filter_produk = $this->input->get_post('filter_produk', true);
    $filter_divisi = $this->input->get_post('filter_divisi', true);
    // ✅ Tambahkan filter lokasi
    $filter_lokasi = $this->input->get_post('filter_lokasi', true); 

    // Fallback: kalau kosong, ambil dari session 
    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');
    }
    // ✅ Fallback Lokasi
    if ($filter_lokasi === null || $filter_lokasi === '') {
        $filter_lokasi = $this->session->userdata('filter_lokasi');
    }

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

 

    // 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();
    $last_col = 'H'; // Kolom terakhir
    $headerRow = 4; // Baris Header

    // =========================================================
    // 1. STYLE GLOBAL UNTUK PENYELARASAN VERTIKAL
    // =========================================================
    $sheet->getDefaultRowDimension()->setRowHeight(20); // Tambah sedikit tinggi baris default
    $sheet->getStyle('A1:'.$last_col.'100')->getAlignment()
          ->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);


    // =========================================================
    // 2. 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);
    $drawing->setCoordinates('A1');
    $drawing->setWorksheet($sheet);

    // =========================================================
    // 3. JUDUL LAPORAN DAN TANGGAL (BARIS 2 & 3)
    // =========================================================
    $sheet->setCellValue('A2','LAPORAN PENGAMBILAN ATK');
    $sheet->mergeCells('A2:'.$last_col.'2');
    $sheet->getStyle('A2')->getFont()->setBold(true)->setSize(16)->setColor(new \PhpOffice\PhpSpreadsheet\Style\Color(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_DARKGREEN));
    $sheet->getStyle('A2')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

    $sheet->setCellValue('A3','Per Tanggal: '.date('d F Y H:i:s'));
    $sheet->mergeCells('A3:'.$last_col.'3');
    $sheet->getStyle('A3')->getFont()->setItalic(true)->setSize(10);
    $sheet->getStyle('A3')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

    // =========================================================
    // 4. HEADER TABEL
    // =========================================================
    $sheet->fromArray([
        'No',
        'Nama Peminjam', // Disesuaikan
        'Divisi',
        'Lokasi',
        'Nama Produk ATK', // Disesuaikan
        'Jumlah',
        'Tanggal Ambil', // Disesuaikan
        'Catatan' // Disesuaikan
    ], null, 'A'.$headerRow);

    // Gaya Header
    $sheet->getStyle('A'.$headerRow.':'.$last_col.$headerRow)->getFont()->setBold(true)->setSize(10)->setColor(new \PhpOffice\PhpSpreadsheet\Style\Color(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE));
    $sheet->getStyle('A'.$headerRow.':'.$last_col.$headerRow)->getAlignment()
          ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
    $sheet->getStyle('A'.$headerRow.':'.$last_col.$headerRow)->getFill()
          ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
          ->getStartColor()->setRGB('2E8B57'); // Warna Hijau Gelap

    // Mengunci Header agar tidak ikut discroll (Frozen Pane)
    $sheet->freezePane('A'.($headerRow + 1));


    // =========================================================
    // 5. 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->inventory_location_nama);
        $sheet->setCellValue('E'.$row, $p->atk_product_nama);
        $sheet->setCellValue('F'.$row, $p->atk_pengambilan_jumlah);
        $sheet->setCellValue('G'.$row, \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel(strtotime($p->tanggal_pengambilan)));
        $sheet->setCellValue('H'.$row, $p->notes);

        // Format Khusus
        $sheet->getStyle('G'.$row)->getNumberFormat()->setFormatCode('dd-mm-yyyy hh:mm'); // Detail waktu
        $row++;
    }

    // =========================================================
    // 6. GARIS TEPI, AUTOSIZE & PENYELARASAN ISI
    // =========================================================

    // Border
    $sheet->getStyle('A'.$headerRow.':'.$last_col.($row-1))
          ->getBorders()->getAllBorders()
          ->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN)
          ->setColor(new \PhpOffice\PhpSpreadsheet\Style\Color(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_BLACK));

    // Penyelarasan Isi (Menggantikan style global)
    $data_range = 'A'.($headerRow + 1).':'.$last_col.($row-1);
    
    // Rata Tengah (No, Jumlah, Tanggal)
    $sheet->getStyle('A'.$headerRow.':A'.($row-1))->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); // No
    $sheet->getStyle('F'.$headerRow.':G'.($row-1))->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); // Jumlah dan Tanggal

    // Rata Kiri (Nama, Divisi, Lokasi, Produk, Catatan)
    $sheet->getStyle('B'.$headerRow.':E'.($row-1))->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
    $sheet->getStyle('H'.$headerRow.':H'.($row-1))->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);


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

    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);
}


}

    

