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

class Farmasi extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Farmasi_model');
        $this->load->library(['session', 'form_validation']);
        $this->load->helper(['url', 'general_helper']);

        if (!$this->session->userdata('logged_in')) {
            redirect('welcome');
        }
    }

    public function index()
    {
        redirect('farmasi/resep');
    }

    public function resep()
    {
        $filters = [
            'tanggal' => $this->input->get('tanggal') ?: date('Y-m-d'),
            'status' => $this->input->get('status') ?: 'all',
            'keyword' => trim((string) $this->input->get('keyword')),
        ];

        $data = [
            'title' => 'Farmasi',
            'filters' => $filters,
            'list' => $this->Farmasi_model->list_resep($filters),
        ];

        $this->render('farmasi/resep', $data);
    }

    public function detail($resep_id)
    {
        $resep = $this->Farmasi_model->get_resep($resep_id);
        if (!$resep) {
            show_404();
        }

        $data = [
            'title' => 'Detail Resep Farmasi',
            'resep' => $resep,
        ];

        $this->render('farmasi/detail', $data);
    }

    public function serahkan($resep_id)
    {
        if ($this->input->method() !== 'post') {
            redirect('farmasi/detail/' . $resep_id);
        }

        $detailIds = $this->input->post('resep_detail_id') ?: [];
        $jumlahSerah = $this->input->post('jumlah_serah') ?: [];
        $rows = [];

        $max = max(count($detailIds), count($jumlahSerah));
        for ($i = 0; $i < $max; $i++) {
            $id = trim($detailIds[$i] ?? '');
            if ($id === '') {
                continue;
            }

            $rows[] = [
                'resep_detail_id' => $id,
                'jumlah_serah' => (float) ($jumlahSerah[$i] ?? 0),
            ];
        }

        [$ok, $message] = $this->Farmasi_model->dispense_resep(
            $resep_id,
            $rows,
            $this->session->userdata('id_petugas') ?: null
        );

        $this->session->set_flashdata($ok ? 'success' : 'error', $message);
        redirect('farmasi/detail/' . $resep_id);
    }

    public function master_obat()
    {
        $keyword = trim((string) $this->input->get('keyword'));

        $data = [
            'title' => 'Master Obat',
            'keyword' => $keyword,
            'obat' => $this->Farmasi_model->list_master_obat($keyword),
            'bentuk_sediaan' => $this->Farmasi_model->list_bentuk_sediaan(),
        ];

        $this->render('farmasi/master_obat', $data);
    }

    public function simpan_obat()
    {
        $payload = [
            'kode_obat' => trim((string) $this->input->post('kode_obat', true)),
            'nama_obat' => trim((string) $this->input->post('nama_obat', true)),
            'bentuk_sediaan_id' => trim((string) $this->input->post('bentuk_sediaan_id', true)),
            'satuan_kecil' => trim((string) $this->input->post('satuan_kecil', true)),
            'kategori' => trim((string) $this->input->post('kategori', true)),
            'harga_beli' => (float) ($this->input->post('harga_beli', true) ?: 0),
            'harga_jual' => (float) ($this->input->post('harga_jual', true) ?: 0),
            'stok_minimum' => (float) ($this->input->post('stok_minimum', true) ?: 0),
        ];

        [$ok, $message] = $this->Farmasi_model->save_master_obat($payload);
        $this->session->set_flashdata($ok ? 'success' : 'error', $message);
        redirect('farmasi/master_obat');
    }

    public function simpan_bentuk_sediaan()
    {
        $payload = [
            'nama_bentuk' => trim((string) $this->input->post('nama_bentuk', true)),
            'deskripsi' => trim((string) $this->input->post('deskripsi', true)),
        ];

        [$ok, $message] = $this->Farmasi_model->save_bentuk_sediaan($payload);
        $this->session->set_flashdata($ok ? 'success' : 'error', $message);
        redirect('farmasi/master_obat');
    }

    public function stok()
    {
        $data = [
            'title' => 'Stok Obat',
            'stok' => $this->Farmasi_model->stok_ringkas(),
            'obat_options' => $this->Farmasi_model->get_active_obat_options(),
            'lokasi' => $this->Farmasi_model->list_lokasi(),
        ];

        $this->render('farmasi/stok', $data);
    }

    public function tambah_stok()
    {
        $payload = [
            'obat_id' => $this->input->post('obat_id', true),
            'lokasi_id' => $this->input->post('lokasi_id', true),
            'qty' => (float) ($this->input->post('qty', true) ?: 0),
            'keterangan' => trim((string) $this->input->post('keterangan', true)),
            'created_by' => $this->session->userdata('id_petugas') ?: null,
        ];

        [$ok, $message] = $this->Farmasi_model->tambah_stok($payload);
        $this->session->set_flashdata($ok ? 'success' : 'error', $message);
        redirect('farmasi/stok');
    }

    public function sesuaikan_stok()
    {
        $payload = [
            'obat_id' => $this->input->post('obat_id', true),
            'lokasi_id' => $this->input->post('lokasi_id', true),
            'qty_baru' => (float) ($this->input->post('qty_baru', true) ?: 0),
            'keterangan' => trim((string) $this->input->post('keterangan', true)),
            'created_by' => $this->session->userdata('id_petugas') ?: null,
        ];

        [$ok, $message] = $this->Farmasi_model->penyesuaian_stok($payload);
        $this->session->set_flashdata($ok ? 'success' : 'error', $message);
        redirect('farmasi/stok');
    }

    public function mutasi()
    {
        $filters = [
            'tanggal' => $this->input->get('tanggal') ?: date('Y-m-d'),
            'lokasi_id' => $this->input->get('lokasi_id') ?: 'all',
            'jenis_mutasi' => $this->input->get('jenis_mutasi') ?: 'all',
        ];

        $data = [
            'title' => 'Mutasi Stok',
            'filters' => $filters,
            'lokasi' => $this->Farmasi_model->list_lokasi(),
            'list' => $this->Farmasi_model->list_mutasi($filters),
        ];

        $this->render('farmasi/mutasi', $data);
    }
}
