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

class Rencana_pembelian extends CI_Controller {

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

    private function _is_admin() {
        return in_array($this->session->userdata('role'), ['admin', 'rt']);
    }

    private function _check_admin() {
        if (!$this->_is_admin()) {
            $this->session->set_flashdata('error', 'Akses ditolak');
            redirect('rencana-pembelian');
        }
    }

    // ─────────────────────────────────────────────
    // INDEX
    // ─────────────────────────────────────────────

    public function index() {
        $status = $this->input->get('status') ?: null;

        $data['title']     = 'Rencana Pembelian';
        $data['rencana']   = $this->Rencana_pembelian_model->get_all($status);
        $data['stats']     = $this->Rencana_pembelian_model->get_stats();
        $data['is_admin']  = $this->_is_admin();
        $data['filter_status'] = $status;

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

    // ─────────────────────────────────────────────
    // TAMBAH
    // ─────────────────────────────────────────────

    public function tambah() {
        $this->_check_admin();

        $data['title']    = 'Tambah Rencana Pembelian';
        $data['kas_list'] = $this->Master_kas_model->get_aktif();

        $this->form_validation->set_rules('nama_barang', 'Nama Barang', 'required');
        $this->form_validation->set_rules('jumlah',      'Jumlah',      'required|integer');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('rencana_pembelian/tambah', $data);
            $this->load->view('templates/footer');
        } else {
            $insert = [
                'nama_barang'     => $this->input->post('nama_barang'),
                'kategori'        => $this->input->post('kategori'),
                'jumlah'          => $this->input->post('jumlah'),
                'satuan'          => $this->input->post('satuan') ?: 'unit',
                'estimasi_harga'  => (int) str_replace('.', '', $this->input->post('estimasi_harga')),
                'sumber_dana'     => $this->input->post('sumber_dana'),
                'prioritas'       => $this->input->post('prioritas'),
                'status'          => 'direncanakan',
                'keterangan'      => $this->input->post('keterangan'),
                'tanggal_rencana' => $this->input->post('tanggal_rencana') ?: date('Y-m-d'),
                'diajukan_oleh'   => $this->session->userdata('user_id'),
            ];
            $this->Rencana_pembelian_model->insert($insert);
            $this->session->set_flashdata('success', 'Rencana pembelian berhasil ditambahkan');
            redirect('rencana-pembelian');
        }
    }

    // ─────────────────────────────────────────────
    // EDIT
    // ─────────────────────────────────────────────

    public function edit($id) {
        $this->_check_admin();

        $data['item']    = $this->Rencana_pembelian_model->get_by_id($id);
        if (!$data['item']) show_404();

        // Hanya bisa edit jika belum terealisasi
        if (in_array($data['item']->status, ['terbeli', 'hibah'])) {
            $this->session->set_flashdata('error', 'Rencana yang sudah terealisasi tidak dapat diedit');
            redirect('rencana-pembelian');
        }

        $data['title']    = 'Edit Rencana Pembelian';
        $data['kas_list'] = $this->Master_kas_model->get_aktif();

        $this->form_validation->set_rules('nama_barang', 'Nama Barang', 'required');
        $this->form_validation->set_rules('jumlah',      'Jumlah',      'required|integer');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('rencana_pembelian/edit', $data);
            $this->load->view('templates/footer');
        } else {
            $update = [
                'nama_barang'     => $this->input->post('nama_barang'),
                'kategori'        => $this->input->post('kategori'),
                'jumlah'          => $this->input->post('jumlah'),
                'satuan'          => $this->input->post('satuan') ?: 'unit',
                'estimasi_harga'  => (int) str_replace('.', '', $this->input->post('estimasi_harga')),
                'sumber_dana'     => $this->input->post('sumber_dana'),
                'prioritas'       => $this->input->post('prioritas'),
                'status'          => $this->input->post('status'),
                'keterangan'      => $this->input->post('keterangan'),
                'tanggal_rencana' => $this->input->post('tanggal_rencana'),
            ];
            $this->Rencana_pembelian_model->update($id, $update);
            $this->session->set_flashdata('success', 'Rencana pembelian berhasil diperbarui');
            redirect('rencana-pembelian');
        }
    }

    // ─────────────────────────────────────────────
    // HAPUS
    // ─────────────────────────────────────────────

    public function hapus($id) {
        $this->_check_admin();
        $item = $this->Rencana_pembelian_model->get_by_id($id);
        if (!$item) show_404();

        if (in_array($item->status, ['terbeli', 'hibah'])) {
            $this->session->set_flashdata('error', 'Rencana yang sudah terealisasi tidak dapat dihapus');
            redirect('rencana-pembelian');
        }

        $this->Rencana_pembelian_model->delete($id);
        $this->session->set_flashdata('success', 'Rencana pembelian berhasil dihapus');
        redirect('rencana-pembelian');
    }

    // ─────────────────────────────────────────────
    // REALISASI — form pilih: terbeli atau hibah
    // ─────────────────────────────────────────────

    public function realisasi($id) {
        $this->_check_admin();

        $data['item'] = $this->Rencana_pembelian_model->get_by_id($id);
        if (!$data['item']) show_404();

        if (in_array($data['item']->status, ['terbeli', 'hibah', 'dibatalkan'])) {
            $this->session->set_flashdata('error', 'Rencana ini sudah terealisasi atau dibatalkan');
            redirect('rencana-pembelian');
        }

        $data['title']    = 'Realisasi Rencana Pembelian';
        $data['kas_list'] = $this->Master_kas_model->get_aktif();

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

    // ─────────────────────────────────────────────
    // PROSES REALISASI (POST)
    // ─────────────────────────────────────────────

    public function proses_realisasi($id) {
        $this->_check_admin();

        $item = $this->Rencana_pembelian_model->get_by_id($id);
        if (!$item) show_404();

        $jenis_realisasi = $this->input->post('jenis_realisasi');
        $user_id         = $this->session->userdata('user_id');

        if ($jenis_realisasi === 'terbeli') {
            // Validasi
            if (empty($this->input->post('harga_realisasi')) || empty($this->input->post('master_kas_id'))) {
                $this->session->set_flashdata('error', 'Harga beli dan kas sumber wajib diisi');
                redirect('rencana-pembelian/realisasi/' . $id);
            }

            $result = $this->Rencana_pembelian_model->realisasi_terbeli($id, $this->input->post(), $user_id);

        } elseif ($jenis_realisasi === 'hibah') {
            if (empty($this->input->post('pemberi_hibah'))) {
                $this->session->set_flashdata('error', 'Nama pemberi hibah wajib diisi');
                redirect('rencana-pembelian/realisasi/' . $id);
            }
            $result = $this->Rencana_pembelian_model->realisasi_hibah($id, $this->input->post(), $user_id);

        } else {
            $this->session->set_flashdata('error', 'Jenis realisasi tidak valid');
            redirect('rencana-pembelian/realisasi/' . $id);
        }

        if (isset($result['error'])) {
            $this->session->set_flashdata('error', $result['error']);
            redirect('rencana-pembelian/realisasi/' . $id);
        }

        $this->session->set_flashdata('success', 'Realisasi berhasil! Barang otomatis masuk ke inventaris.');
        redirect('inventaris/detail/' . $result['inventaris_id']);
    }

    // ─────────────────────────────────────────────
    // BATALKAN
    // ─────────────────────────────────────────────

    public function batalkan($id) {
        $this->_check_admin();
        $item = $this->Rencana_pembelian_model->get_by_id($id);
        if (!$item) show_404();

        if (in_array($item->status, ['terbeli', 'hibah'])) {
            $this->session->set_flashdata('error', 'Rencana yang sudah terealisasi tidak dapat dibatalkan');
            redirect('rencana-pembelian');
        }

        $this->Rencana_pembelian_model->update($id, ['status' => 'dibatalkan']);
        $this->session->set_flashdata('success', 'Rencana pembelian dibatalkan');
        redirect('rencana-pembelian');
    }

    // ─────────────────────────────────────────────
    // SETUJUI
    // ─────────────────────────────────────────────

    public function setujui($id) {
        $this->_check_admin();
        $this->Rencana_pembelian_model->update($id, [
            'status'         => 'disetujui',
            'disetujui_oleh' => $this->session->userdata('user_id'),
        ]);
        $this->session->set_flashdata('success', 'Rencana pembelian disetujui');
        redirect('rencana-pembelian');
    }
}