<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\ModelResepObat;
use App\Models\ModelResepObatDetail;
use App\Models\ModelRekammedis;
use App\Models\ModelObat;

class ResepObat extends BaseController
{
    protected $ModelResepObat;
    protected $ModelResepObatDetail;
    protected $ModelRekammedis;
    protected $ModelObat;

    public function __construct()
    {
        $this->ModelResepObat       = new ModelResepObat();
        $this->ModelResepObatDetail = new ModelResepObatDetail();
        $this->ModelRekammedis      = new ModelRekammedis();
        $this->ModelObat            = new ModelObat();
    }

    public function index()
    {
        $data = [
            'Breadcumb' => 'Resep Obat',
            'resep' => $this->ModelResepObat->getAll(),
            'rekam_medis' => $this->ModelRekammedis->getAllData(), // pastikan method getAll() ada
            'obat' => $this->ModelObat->findAll(), // jika ingin langsung load juga daftar obat untuk modal
        ];
        return view('resep_obat/index', $data);
    }

    public function tambah()
    {
        $data = [
            'rekam_medis' => $this->ModelRekammedis->findAll(),
            'obat'        => $this->ModelObat->findAll()
        ];
        return view('resep_obat/tambah', $data);
    }

    public function detail_ajax()
    {
        if ($this->request->isAJAX()) {
            $id = $this->request->getVar('id_resep');

            $data = $this->ModelResepObatDetail
                ->select('resep_obat_detail.*, obat.nama_obat')
                ->join('obat', 'obat.id_obat = resep_obat_detail.id_obat')
                ->where('id_resep', $id)
                ->findAll();

            return $this->response->setJSON([
                'status' => 'success',
                'data' => $data
            ]);
        }

        return $this->response->setJSON([
            'status' => 'error',
            'message' => 'Akses tidak valid'
        ]);
    }

    public function tambahData()
    {
        if ($this->request->isAJAX()) {
            $id_rekam_medis = $this->request->getPost('id_rekam_medis');
            $tanggal_resep = $this->request->getPost('tanggal_resep');
            $catatan = $this->request->getPost('catatan');

            $id_obat = $this->request->getPost('id_obat');
            $dosis = $this->request->getPost('dosis');
            $jumlah = $this->request->getPost('jumlah');
            $aturan_pakai = $this->request->getPost('aturan_pakai');

            if (!$id_rekam_medis || !$tanggal_resep || empty($id_obat)) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Data tidak lengkap.'
                ]);
            }

            // Simpan ke resep_obat
            $idResep = $this->ModelResepObat->insert([
                'id_rekam_medis' => $id_rekam_medis,
                'tanggal_resep' => $tanggal_resep,
                'catatan' => $catatan,
            ], true); // return ID

            $detail = [];
            for ($i = 0; $i < count($id_obat); $i++) {
                if ($id_obat[$i] != '') {
                    $detail[] = [
                        'id_resep' => $idResep,
                        'id_obat' => $id_obat[$i],
                        'dosis' => $dosis[$i],
                        'jumlah' => $jumlah[$i],
                        'aturan_pakai' => $aturan_pakai[$i],
                    ];
                }
            }

            if (!empty($detail)) {
                $this->ModelResepObatDetail->insertBatch($detail);
            }

            return $this->response->setJSON([
                'status' => 'success',
                'message' => 'Resep obat berhasil disimpan.'
            ]);
        }
    }

    public function getDetailResep($id)
    {
        $resep = $this->ModelResepObat->find($id);
        $detail = $this->ModelResepObatDetail->where('id_resep', $id)->findAll();

        if (!$resep) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Resep tidak ditemukan.'
            ]);
        }

        return $this->response->setJSON([
            'status' => 'success',
            'resep' => $resep,
            'detail' => $detail
        ]);
    }

    public function updateData()
    {
        if ($this->request->isAJAX()) {
            $id_resep = $this->request->getPost('id_resep');
            $id_rekam_medis = $this->request->getPost('id_rekam_medis');
            $tanggal_resep = $this->request->getPost('tanggal_resep');
            $catatan = $this->request->getPost('catatan');

            $id_obat = $this->request->getPost('id_obat');
            $dosis = $this->request->getPost('dosis');
            $jumlah = $this->request->getPost('jumlah');
            $aturan_pakai = $this->request->getPost('aturan_pakai');

            // Update resep utama
            $this->ModelResepObat->update($id_resep, [
                'id_rekam_medis' => $id_rekam_medis,
                'tanggal_resep' => $tanggal_resep,
                'catatan' => $catatan,
            ]);

            // Hapus detail lama
            $this->ModelResepObatDetail->where('id_resep', $id_resep)->delete();

            // Insert detail baru
            $detail = [];
            for ($i = 0; $i < count($id_obat); $i++) {
                $detail[] = [
                    'id_resep' => $id_resep,
                    'id_obat' => $id_obat[$i],
                    'dosis' => $dosis[$i],
                    'jumlah' => $jumlah[$i],
                    'aturan_pakai' => $aturan_pakai[$i],
                ];
            }

            if (!empty($detail)) {
                $this->ModelResepObatDetail->insertBatch($detail);
            }

            return $this->response->setJSON([
                'status' => 'success',
                'message' => 'Resep berhasil diupdate.'
            ]);
        }
    }


    public function simpan()
    {
        if ($this->request->isAJAX()) {
            $resepData = [
                'id_rekam_medis' => $this->request->getVar('id_rekam_medis'),
                'tanggal_resep'  => $this->request->getVar('tanggal_resep'),
                'catatan'        => $this->request->getVar('catatan')
            ];

            $idResep = $this->ModelResepObat->insert($resepData, true); // true = return ID

            $obatList = $this->request->getVar('obat');
            $dosisList = $this->request->getVar('dosis');
            $jumlahList = $this->request->getVar('jumlah');
            $aturanList = $this->request->getVar('aturan_pakai');

            foreach ($obatList as $i => $id_obat) {
                $this->ModelResepObatDetail->insert([
                    'id_resep'     => $idResep,
                    'id_obat'      => $id_obat,
                    'dosis'        => $dosisList[$i],
                    'jumlah'       => $jumlahList[$i],
                    'aturan_pakai' => $aturanList[$i],
                ]);
            }

            return $this->response->setJSON(['status' => 'success', 'message' => 'Resep berhasil disimpan']);
        }
    }

    public function detail($id_resep)
    {
        $resep = $this->ModelResepObat->getById($id_resep);
        $detail = $this->ModelResepObatDetail->getByResep($id_resep);

        if (!$resep) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException("Resep tidak ditemukan");
        }

        $data = [
            'resep' => $resep,
            'detail' => $detail
        ];

        return view('resep_obat/detail', $data);
    }

    public function delete($id_resep)
    {
        $this->ModelResepObatDetail->deleteByResep($id_resep);
        $this->ModelResepObat->deleteData($id_resep);

        return redirect()->to('/resepobat')->with('success', 'Resep berhasil dihapus');
    }
}
