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

class Peminjaman_inventaris extends CI_Controller {

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

    // ─── INDEX ────────────────────────────────────────────────
    public function index() {
        // Sync otomatis status terlambat
        $this->Peminjaman_inventaris_model->sync_status_terlambat();

        $status = $this->input->get('status') ?: null;

        $data['title']       = 'Peminjaman Barang';
        $data['peminjaman']  = $this->Peminjaman_inventaris_model->get_all($status);
        $data['stats']       = $this->Peminjaman_inventaris_model->get_stats();
        $data['status_aktif']= $status;
        $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('peminjaman_inventaris/index', $data);
        $this->load->view('templates/footer');
    }

    // ─── DETAIL ───────────────────────────────────────────────
    public function detail($id) {
        $data['title']    = 'Detail Peminjaman';
        $data['pinjam']   = $this->Peminjaman_inventaris_model->get_by_id($id);
        $data['is_admin'] = in_array($this->session->userdata('role'), ['admin', 'rt']);
        if (!$data['pinjam']) show_404();

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

    // ─── TAMBAH PEMINJAMAN ────────────────────────────────────
    public function tambah() {
        $this->_check_admin();

        // Pre-fill inventaris dari query string (dari halaman detail barang)
        $inventaris_id = $this->input->get('inventaris_id');

        $data['title']      = 'Catat Peminjaman';
        $data['inventaris'] = $this->Inventaris_model->get_all();
        $data['warga']      = $this->Warga_model->get_all();
        $data['selected_inv'] = $inventaris_id
            ? $this->Inventaris_model->get_by_id($inventaris_id)
            : null;

        $this->form_validation->set_rules('inventaris_id',  'Barang',          'required|integer');
        $this->form_validation->set_rules('nama_peminjam',  'Nama Peminjam',   'required|max_length[100]');
        $this->form_validation->set_rules('jumlah_pinjam',  'Jumlah Pinjam',   'required|integer|greater_than[0]');
        $this->form_validation->set_rules('tanggal_pinjam', 'Tanggal Pinjam',  'required');
        $this->form_validation->set_rules('tanggal_rencana_kembali', 'Tgl Rencana Kembali', 'required');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('peminjaman_inventaris/tambah', $data);
            $this->load->view('templates/footer');
        } else {
            $inv_id      = $this->input->post('inventaris_id');
            $inv         = $this->Inventaris_model->get_by_id($inv_id);
            $jml_pinjam  = (int) $this->input->post('jumlah_pinjam');
            $jml_dipinjam= (int) $this->Peminjaman_inventaris_model->get_jumlah_dipinjam($inv_id);
            $stok_tersedia = ($inv->jumlah ?? 0) - $jml_dipinjam;

            if ($jml_pinjam > $stok_tersedia) {
                $this->session->set_flashdata('error', "Stok tersedia hanya $stok_tersedia {$inv->satuan}.");
                redirect('peminjaman-inventaris/tambah?inventaris_id=' . $inv_id);
                return;
            }

            $insert = [
                'inventaris_id'             => $inv_id,
                'warga_id'                  => $this->input->post('warga_id') ?: null,
                'nama_peminjam'             => $this->input->post('nama_peminjam'),
                'no_hp_peminjam'            => $this->input->post('no_hp_peminjam'),
                'jumlah_pinjam'             => $jml_pinjam,
                'tanggal_pinjam'            => $this->input->post('tanggal_pinjam'),
                'tanggal_rencana_kembali'   => $this->input->post('tanggal_rencana_kembali'),
                'kondisi_awal'              => $this->input->post('kondisi_awal'),
                'keperluan'                 => $this->input->post('keperluan'),
                'status'                    => 'dipinjam',
                'approved_by'               => $this->session->userdata('user_id'),
            ];

            $id = $this->Peminjaman_inventaris_model->insert($insert);
            $this->session->set_flashdata('success', 'Peminjaman berhasil dicatat.');
            redirect('peminjaman-inventaris/detail/' . $id);
        }
    }

    // ─── PROSES KEMBALI ───────────────────────────────────────
    public function kembali($id) {
        $this->_check_admin();

        $pinjam = $this->Peminjaman_inventaris_model->get_by_id($id);
        if (!$pinjam || $pinjam->status == 'dikembalikan') {
            $this->session->set_flashdata('error', 'Data tidak valid atau sudah dikembalikan.');
            redirect('peminjaman-inventaris');
            return;
        }

        $data['title']  = 'Proses Pengembalian';
        $data['pinjam'] = $pinjam;

        $this->form_validation->set_rules('tanggal_kembali',  'Tanggal Kembali', 'required');
        $this->form_validation->set_rules('kondisi_kembali',  'Kondisi Kembali', 'required');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('peminjaman_inventaris/kembali', $data);
            $this->load->view('templates/footer');
        } else {
            $kembali_data = [
                'tanggal_kembali' => $this->input->post('tanggal_kembali'),
                'kondisi_kembali' => $this->input->post('kondisi_kembali'),
                'catatan_kembali' => $this->input->post('catatan_kembali'),
            ];
            $this->Peminjaman_inventaris_model->proses_kembali($id, $kembali_data);
            $this->session->set_flashdata('success', 'Barang berhasil dicatat sebagai sudah dikembalikan.');
            redirect('peminjaman-inventaris/detail/' . $id);
        }
    }

    // ─── HAPUS ────────────────────────────────────────────────
    public function hapus($id) {
        $this->_check_admin();
        $this->Peminjaman_inventaris_model->delete($id);
        $this->session->set_flashdata('success', 'Data peminjaman berhasil dihapus.');
        redirect('peminjaman-inventaris');
    }

    // ─── AJAX: cari warga ────────────────────────────────────
    public function search_warga() {
        $keyword = $this->input->get('q');
        $this->db->select('id, nama_lengkap, nik, no_hp');
        $this->db->from('warga');
        $this->db->group_start();
            $this->db->like('nama_lengkap', $keyword);
            $this->db->or_like('nik', $keyword);
        $this->db->group_end();
        $this->db->limit(10);
        $result = $this->db->get()->result();
        echo json_encode($result);
    }

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