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

class Peminjaman_inventaris_model extends CI_Model {

    // ─── AMBIL SEMUA PEMINJAMAN ───────────────────────────────
    public function get_all($status = null) {
        $this->db->select('pi.*, i.nama_barang, i.kode_barang, i.satuan, i.foto as foto_barang,
                           w.nama_lengkap as nama_warga, w.nik');
        $this->db->from('peminjaman_inventaris pi');
        $this->db->join('inventaris i', 'i.id = pi.inventaris_id', 'left');
        $this->db->join('warga w', 'w.id = pi.warga_id', 'left');
        if ($status) $this->db->where('pi.status', $status);
        $this->db->order_by('pi.created_at', 'DESC');
        return $this->db->get()->result();
    }

    // ─── DETAIL SATU PEMINJAMAN ───────────────────────────────
    public function get_by_id($id) {
        $this->db->select('pi.*, i.nama_barang, i.kode_barang, i.satuan, i.jumlah as stok_total,
                           i.foto as foto_barang, i.lokasi,
                           w.nama_lengkap as nama_warga, w.nik');
        $this->db->from('peminjaman_inventaris pi');
        $this->db->join('inventaris i', 'i.id = pi.inventaris_id', 'left');
        $this->db->join('warga w', 'w.id = pi.warga_id', 'left');
        $this->db->where('pi.id', $id);
        return $this->db->get()->row();
    }

    // ─── RIWAYAT PEMINJAMAN PER BARANG ───────────────────────
    public function get_by_inventaris($inventaris_id) {
        $this->db->select('pi.*, w.nama_lengkap as nama_warga');
        $this->db->from('peminjaman_inventaris pi');
        $this->db->join('warga w', 'w.id = pi.warga_id', 'left');
        $this->db->where('pi.inventaris_id', $inventaris_id);
        $this->db->order_by('pi.created_at', 'DESC');
        return $this->db->get()->result();
    }

    // ─── PEMINJAMAN AKTIF PER BARANG ─────────────────────────
    public function get_active_by_inventaris($inventaris_id) {
        $this->db->where('inventaris_id', $inventaris_id);
        $this->db->where_in('status', ['dipinjam', 'terlambat']);
        return $this->db->get('peminjaman_inventaris')->result();
    }

    // ─── JUMLAH SEDANG DIPINJAM ───────────────────────────────
    // FIX: include status 'terlambat' karena sync_status_terlambat()
    // bisa mengubah status dari 'dipinjam' → 'terlambat',
    // sehingga barang yang belum dikembalikan tetap terhitung.
    public function get_jumlah_dipinjam($inventaris_id) {
        $this->db->select_sum('jumlah_pinjam', 'total');
        $this->db->where('inventaris_id', $inventaris_id);
        $this->db->where_in('status', ['dipinjam', 'terlambat']);
        $row = $this->db->get('peminjaman_inventaris')->row();
        return $row->total ?? 0;
    }

    // ─── INSERT ───────────────────────────────────────────────
    public function insert($data) {
        $data['kode_pinjam'] = $this->_generate_kode();
        $this->db->insert('peminjaman_inventaris', $data);
        return $this->db->insert_id();
    }

    // ─── UPDATE (proses kembali / edit) ──────────────────────
    public function update($id, $data) {
        $this->db->where('id', $id);
        return $this->db->update('peminjaman_inventaris', $data);
    }

    // ─── PROSES KEMBALI ──────────────────────────────────────
    public function proses_kembali($id, $data_kembali) {
        $data = [
            'tanggal_kembali'  => $data_kembali['tanggal_kembali'],
            'kondisi_kembali'  => $data_kembali['kondisi_kembali'],
            'catatan_kembali'  => $data_kembali['catatan_kembali'],
            'status'           => 'dikembalikan',
        ];
        $this->db->where('id', $id);
        return $this->db->update('peminjaman_inventaris', $data);
    }

    // ─── HAPUS ───────────────────────────────────────────────
    public function delete($id) {
        $this->db->where('id', $id);
        return $this->db->delete('peminjaman_inventaris');
    }

    // ─── STATISTIK ───────────────────────────────────────────
    public function get_stats() {
        $stats = [];
        $stats['total']        = $this->db->count_all('peminjaman_inventaris');

        $this->db->where_in('status', ['dipinjam', 'terlambat']);
        $stats['dipinjam']     = $this->db->count_all_results('peminjaman_inventaris');

        $this->db->where('status', 'dikembalikan');
        $stats['dikembalikan'] = $this->db->count_all_results('peminjaman_inventaris');

        // terlambat: status dipinjam/terlambat dan tanggal_rencana_kembali < hari ini
        $this->db->where_in('status', ['dipinjam', 'terlambat']);
        $this->db->where('tanggal_rencana_kembali <', date('Y-m-d'));
        $stats['terlambat']    = $this->db->count_all_results('peminjaman_inventaris');

        return $stats;
    }

    // ─── AUTO-UPDATE STATUS TERLAMBAT ────────────────────────
    public function sync_status_terlambat() {
        $this->db->set('status', 'terlambat');
        $this->db->where('status', 'dipinjam');
        $this->db->where('tanggal_rencana_kembali <', date('Y-m-d'));
        return $this->db->update('peminjaman_inventaris');
    }

    // ─── GENERATE KODE UNIK ──────────────────────────────────
    private function _generate_kode() {
        $prefix = 'PJM-' . date('Y');
        $this->db->like('kode_pinjam', $prefix, 'after');
        $this->db->order_by('id', 'DESC');
        $this->db->limit(1);
        $last = $this->db->get('peminjaman_inventaris')->row();
        $seq  = $last ? (intval(substr($last->kode_pinjam, -4)) + 1) : 1;
        return $prefix . str_pad($seq, 4, '0', STR_PAD_LEFT);
    }
}