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

class Inventaris extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
        if(!$this->session->userdata('logged_in')) redirect('auth');
        $this->load->model('Inventaris_model');
        $this->load->library('form_validation');
    }

    public function index() {
        $data['title'] = 'Inventaris RT';
        $data['inventaris'] = $this->Inventaris_model->get_all();
        $data['stats'] = $this->Inventaris_model->get_stats();
        $data['is_admin'] = in_array($this->session->userdata('role'), ['admin', 'rt']);
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('inventaris/index', $data);
        $this->load->view('templates/footer');
    }

    // ✅ Hanya SATU fungsi detail() — sudah include riwayat peminjaman
    public function detail($id) {
        $this->load->model('Peminjaman_inventaris_model');

        $data['title']    = 'Detail Inventaris';
        $data['item']     = $this->Inventaris_model->get_by_id($id);
        $data['gallery']  = $this->Inventaris_model->get_gallery($id);
        $data['is_admin'] = in_array($this->session->userdata('role'), ['admin', 'rt']);

        $data['riwayat_pinjam']  = $this->Peminjaman_inventaris_model->get_by_inventaris($id);
        $data['jumlah_dipinjam'] = $this->Peminjaman_inventaris_model->get_jumlah_dipinjam($id);

        if(!$data['item']) show_404();

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('inventaris/detail', $data);
        $this->load->view('templates/footer');
    }

    public function tambah() {
        $this->_check_admin();
        $data['title'] = 'Tambah Inventaris';
        $data['kategori'] = $this->Inventaris_model->get_kategori_options();

        $this->form_validation->set_rules('nama_barang', 'Nama Barang', 'required');

        if($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('inventaris/tambah', $data);
            $this->load->view('templates/footer');
        } else {
            $config['upload_path'] = './uploads/inventaris/';
            $config['allowed_types'] = 'jpg|jpeg|png';
            $config['max_size'] = 2048;
            
            if(!is_dir($config['upload_path'])) mkdir($config['upload_path'], 0777, true);
            
            $foto = '';
            if(!empty($_FILES['foto']['name'])) {
                $this->load->library('upload', $config);
                if($this->upload->do_upload('foto')) {
                    $foto = $this->upload->data('file_name');
                }
            }

            $data_insert = [
                'kode_barang'       => $this->input->post('kode_barang'),
                'nama_barang'       => $this->input->post('nama_barang'),
                'kategori'          => $this->input->post('kategori'),
                'jumlah'            => $this->input->post('jumlah'),
                'satuan'            => $this->input->post('satuan'),
                'kondisi'           => $this->input->post('kondisi'),
                'lokasi'            => $this->input->post('lokasi'),
                'tanggal_pembelian' => $this->input->post('tanggal_pembelian'),
                'harga_pembelian'   => str_replace('.', '', $this->input->post('harga_pembelian')),
                'sumber_dana'       => $this->input->post('sumber_dana'),
                'keterangan'        => $this->input->post('keterangan'),
                'foto'              => $foto
            ];

            $id = $this->Inventaris_model->insert($data_insert);
            
            if(!empty($_FILES['gallery']['name'][0])) {
                $this->_upload_gallery($id);
            }
            
            $this->session->set_flashdata('success', 'Inventaris berhasil ditambahkan');
            redirect('inventaris');
        }
    }

    public function edit($id) {
        $this->_check_admin();
        
        $data['title']    = 'Edit Inventaris';
        $data['item']     = $this->Inventaris_model->get_by_id($id);
        $data['gallery']  = $this->Inventaris_model->get_gallery($id);
        $data['kategori'] = $this->Inventaris_model->get_kategori_options();
        
        if(!$data['item']) show_404();
        
        $this->form_validation->set_rules('nama_barang', 'Nama Barang', 'required');
        $this->form_validation->set_rules('kode_barang', 'Kode Barang', 'required');
        
        if($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('inventaris/edit', $data);
            $this->load->view('templates/footer');
        } else {
            $foto = $data['item']->foto;
            
            if($this->input->post('hapus_foto')) {
                if($foto && file_exists('./uploads/inventaris/'.$foto)) {
                    unlink('./uploads/inventaris/'.$foto);
                }
                $foto = '';
            }
            
            if(!empty($_FILES['foto']['name'])) {
                $config['upload_path'] = './uploads/inventaris/';
                $config['allowed_types'] = 'jpg|jpeg|png';
                $config['max_size'] = 2048;
                
                $this->load->library('upload', $config);
                if($this->upload->do_upload('foto')) {
                    if($data['item']->foto && file_exists('./uploads/inventaris/'.$data['item']->foto)) {
                        unlink('./uploads/inventaris/'.$data['item']->foto);
                    }
                    $foto = $this->upload->data('file_name');
                }
            }
            
            $update_data = [
                'kode_barang'       => $this->input->post('kode_barang'),
                'nama_barang'       => $this->input->post('nama_barang'),
                'kategori'          => $this->input->post('kategori'),
                'jumlah'            => $this->input->post('jumlah'),
                'satuan'            => $this->input->post('satuan'),
                'kondisi'           => $this->input->post('kondisi'),
                'lokasi'            => $this->input->post('lokasi'),
                'tanggal_pembelian' => $this->input->post('tanggal_pembelian'),
                'harga_pembelian'   => str_replace('.', '', $this->input->post('harga_pembelian')),
                'sumber_dana'       => $this->input->post('sumber_dana'),
                'keterangan'        => $this->input->post('keterangan'),
                'foto'              => $foto
            ];
            
            $this->Inventaris_model->update($id, $update_data);
            
            $hapus_gallery = $this->input->post('hapus_gallery');
            if($hapus_gallery) {
                foreach($hapus_gallery as $gallery_id) {
                    $this->Inventaris_model->delete_gallery($gallery_id);
                }
            }
            
            if(!empty($_FILES['gallery']['name'][0])) {
                $this->_upload_gallery($id);
            }
            
            $this->session->set_flashdata('success', 'Inventaris berhasil diperbarui');
            redirect('inventaris');
        }
    }

    public function hapus($id) {
        $this->_check_admin();
        
        $item = $this->Inventaris_model->get_by_id($id);
        if(!$item) show_404();
        
        if($item->foto && file_exists('./uploads/inventaris/'.$item->foto)) {
            unlink('./uploads/inventaris/'.$item->foto);
        }
        
        $gallery = $this->Inventaris_model->get_gallery($id);
        foreach($gallery as $g) {
            if(file_exists('./uploads/inventaris/gallery/'.$g->foto)) {
                unlink('./uploads/inventaris/gallery/'.$g->foto);
            }
        }
        
        $this->Inventaris_model->delete($id);
        $this->session->set_flashdata('success', 'Inventaris berhasil dihapus');
        redirect('inventaris');
    }

    // ─── PRIVATE HELPERS ──────────────────────────────────────

    private function _upload_gallery($inventaris_id) {
        $config['upload_path'] = './uploads/inventaris/gallery/';
        $config['allowed_types'] = 'jpg|jpeg|png';
        $config['max_size'] = 2048;
        
        if(!is_dir($config['upload_path'])) mkdir($config['upload_path'], 0777, true);
        
        $this->load->library('upload');
        
        $files = $_FILES['gallery'];
        $file_count = count($files['name']);
        
        for($i = 0; $i < $file_count; $i++) {
            if($files['name'][$i]) {
                $_FILES['file']['name']     = $files['name'][$i];
                $_FILES['file']['type']     = $files['type'][$i];
                $_FILES['file']['tmp_name'] = $files['tmp_name'][$i];
                $_FILES['file']['error']    = $files['error'][$i];
                $_FILES['file']['size']     = $files['size'][$i];
                
                $this->upload->initialize($config);
                
                if($this->upload->do_upload('file')) {
                    $this->Inventaris_model->insert_gallery([
                        'inventaris_id' => $inventaris_id,
                        'foto'          => $this->upload->data('file_name')
                    ]);
                }
            }
        }
    }

    private function _check_admin() {
        $role = $this->session->userdata('role');
        if(!in_array($role, ['admin', 'rt'])) {
            $this->session->set_flashdata('error', 'Akses ditolak');
            redirect('inventaris');
        }
    }
}