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

class Inventaris_model extends CI_Model {

    public function get_all($kategori = null, $kondisi = null) {
        $this->db->select('inventaris.*');
        if($kategori) $this->db->where('kategori', $kategori);
        if($kondisi) $this->db->where('kondisi', $kondisi);
        $this->db->order_by('created_at', 'DESC');
        return $this->db->get('inventaris')->result();
    }

    public function get_by_id($id) {
        return $this->db->get_where('inventaris', ['id' => $id])->row();
    }

    public function get_gallery($inventaris_id) {
        return $this->db->get_where('inventaris_gallery', ['inventaris_id' => $inventaris_id])->result();
    }

    public function insert($data) {
        $this->db->insert('inventaris', $data);
        return $this->db->insert_id();
    }

    public function insert_gallery($data) {
        return $this->db->insert('inventaris_gallery', $data);
    }

    public function update($id, $data) {
        $this->db->where('id', $id);
        return $this->db->update('inventaris', $data);
    }

    public function delete($id) {
        $this->db->where('id', $id);
        return $this->db->delete('inventaris');
    }

    public function get_stats() {
        $stats = [];
        $stats['total'] = $this->db->count_all('inventaris');
        $stats['baik'] = $this->db->where('kondisi', 'baik')->count_all_results('inventaris');
        $stats['rusak'] = $this->db->where_in('kondisi', ['rusak_ringan', 'rusak_berat'])->count_all_results('inventaris');
        $stats['total_nilai'] = $this->db->select_sum('harga_pembelian')->get('inventaris')->row()->harga_pembelian;
        return $stats;
    }

    public function get_kategori_options() {
        return [
            'elektronik' => 'Elektronik',
            'furniture' => 'Furniture',
            'kendaraan' => 'Kendaraan',
            'perlengkapan' => 'Perlengkapan',
            'lainnya' => 'Lainnya'
        ];
    }
    public function delete_gallery($id) {
    $item = $this->db->get_where('inventaris_gallery', ['id' => $id])->row();
    if($item && file_exists('./uploads/inventaris/gallery/'.$item->foto)) {
        unlink('./uploads/inventaris/gallery/'.$item->foto);
    }
    return $this->db->delete('inventaris_gallery', ['id' => $id]);
}
}