<?php

class Satusehat_data_medication extends CI_Controller {

	public function __construct()
	{
		parent::__construct();

		$this->load->model('api_satusehat_model');
		$this->load->model('data_obat_model');
		$this->load->model('pengaturan_model');

		$this->load->model('asset_menu_class_model');
		$this->load->model('paging_model');				
		$this->load->model('select_model');		

		$this->url_controller = $this->uri->segment(1);
		$this->navigation = $this->session->userdata('nav_'.$this->session->userdata('prefix'));
	}

	public function index()
	{	
		$data = [
			'menu' => [
				'data' => $this->asset_menu_class_model->tabel_data($this->session->userdata('level_id_'.$this->session->userdata('prefix'))),
				'select_level' => $this->select_model->select_asset('asset_level_user', 'id')
			]			
		];

		$this->load->view($this->navigation.'/body', $data);
	}

	public function page()
	{		
		$this->load->view($this->url_controller.'/page');
	}			

	public function tabel()
	{
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0; 
		$url_page = $this->url_controller.'/tabel';	
		$limit = 10;

		$context  = array(
			'service_name' => 'medication',
			'keyword' => $this->input->post('keyword'),
			'limit' => $limit,
			'start' => $page
		);

		$get_data = $this->data_obat_model->tabel_data($context);
		$get_jml = $this->data_obat_model->jml_data($context);

		$data = [
			'data' => $get_data,
			'jml_data' => $get_jml,
			'page' => $page,
			'pagination' => $this->paging_model->get($get_jml, $limit, $url_page, 'tabel_1'),
			'page_curr' => $url_page.'/'.$page
		];

		$this->load->view($this->url_controller.'/tabel', $data);
	}

	public function kirim()
	{
		$data = $this->input->post();

		$response = $this->execute($data);

		echo json_encode($response);
	}
	
	public function edit()
	{
		$context  = array('id' => $this->input->post('id'));

		$data = [
			'url_form' => $this->url_controller.'/update',
			'data' => $this->data_obat_model->lihat_data($context),
			'select_jenis' => $this->select_model->select_asset('asset_jenis_obat', 'value')
		];	

		$this->load->view($this->url_controller.'/form', $data);
	}

	public function update()
	{		
		$context = $this->input->post();

		$query = $this->data_obat_model->update_kfa($context);

		echo json_encode($query);
	}

	public function execute($context_data)
	{
		$data_obat = $this->data_obat_model->lihat_data($context_data);

		$context = (array) $data_obat;

		$context['service_name'] = 'medication';

		$response = $this->api_satusehat_model->post($context); 

		if(!empty($response))
		{
			$response['data'] = (array) $obat;

			$response = $this->data_obat_model->update_kfa($response);			
		} 
		else $response = array('eror' => 'warning', 'pesan' => 'Tidak ada respon dari SATUSEHAT. Kesalahan data yang dikirim');

		return $response;
	}
}

?>