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

class ManageMedicine extends CI_Controller {

	public function __construct() {
		parent::__construct();
		if(!$this->session->userdata('logged_in')) {
			redirect(base_url());
		
		}
		$this->load->model('Medicine_model');
		
 	}
	
	public function index() {

		if(isset($_POST) && !empty($_POST)){

			$medicine_data = $_POST;
			$medicine_add = $this->Medicine_model->addMedicine($medicine_data);
			if($medicine_add == true){
				$this->session->set_flashdata('message', array('message' => 'Successfully Added', 'title' => 'Success !', 'class' => 'success'));
			}
			else{
				$this->session->set_flashdata('message', array('message' => 'Error Occured! Medicine Already Exist', 'title' => 'Error !', 'class' => 'error'));
			}
		}
		$all_medicines = $this->Medicine_model->get_all_medicine();	

		$template['page'] = "ManageMedicine/addMedicine";
		$template['page_title'] = "Manage Medicine Page";
		$template['data'] = $all_medicines;
		$this->load->view('template', $template);
	}
	function medicine_delete($id){
		$delete_data = $this->Medicine_model->delete_medicine($id);
		if($delete_data){
			$this->session->set_flashdata('message', array('message' => 'Successfully Deleted', 'title' => 'Success !', 'class' => 'success'));
			redirect(base_url().'ManageMedicine');
		}
	}
	function medicine_edit(){
        $id = $this->uri->segment(3);
        if($id == ''){
        	redirect(base_url().'ManageMedicine/index');
        } 
        else{

			$medicine_data = $this->Medicine_model->get_single_medicine($id);
			if($medicine_data != ''){
				$template['page'] = "ManageMedicine/editMedicine";
				$template['page_title'] = "Manage Medicine Page";
				$template['data'] = $medicine_data;
				if(isset($_POST) && !empty($_POST)){
					$data=$_POST;
					//date_default_timezone_set("Asia/Kolkata");			
					$data['modified_date']=date("Y-m-d h:i:sa");
					$success_update = $this->Medicine_model->update_medicine($data, $id);
					if($success_update == true){
						$this->session->set_flashdata('message', array('message' => 'Successfully Updated', 'title' => 'Success !', 'class' => 'success'));
					redirect(base_url().'ManageMedicine');
					}else{
						$this->session->set_flashdata('message', array('message' => 'Sorry Updation Failed. Medicine Already Exist', 'title' => 'Error', 'class' => 'error'));
					redirect(base_url().'ManageMedicine');
					}
				}
	   		}else{
	   			redirect(base_url().'ManageMedicine/index');
	   		}
		}
		$this->load->view('template', $template);
	}
}