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

class UnitController extends CI_Controller{


	public function __construct() {

		parent::__construct();

		if($this->session->userdata('admin_logged_in')!==TRUE){
			redirect('/');
		}

		$this->load->model('dataHandling/crud','crud');
		$this->load->model('pages/UnitModel','model');
		$this->load->model('TableModel/unit/FetchUnitData','TableModel');

	}
	public function index(){
		$this->layouts->add_includes('assets/backend/js/pages/unit.js');
		$data['title']="Unit of Measure";
		$data['content']='pages/main/unit';
		$this->load->view('layout/backend-access',$data);
	}

	public function getUnitData(){
		if ($this->input->is_ajax_request()){
			$list = $this->TableModel->get_datatables();
			$data = array();
			$no = $_POST['start'];

			foreach ($list as $data_n) {


				$no++;
				$row = array();
				$row[] = $no;
				$row[] = $data_n->uom;
				$row[] = $data_n->status;
				$row[] = sha1($data_n->uom_id);


				$data[] = $row;
			}

			$output = array(
				"draw" => $_POST['draw'],
				"recordsTotal" => $this->TableModel->count_all(),
				"recordsFiltered" => $this->TableModel->count_filtered(),
				"data" => $data,
			);
			//output to json format
			echo json_encode($output);
		}
	}

	public function newUnitEntryProcess(){
		if ($this->input->is_ajax_request())
		{
			$this->form_validation->set_rules('unit_name','Unit Name','required|trim');

			if($this->form_validation->run()){

				$unit_name=$this->input->post('unit_name',TRUE);
				$dataSet=array(
					'uom'=>$unit_name,
				);

				$table="uom";

				if($this->crud->insertReturnData($dataSet,$table)){
					$data['response']='Unit save successfully';
				}
				else{
					$data['response']='Error Occured';
				}
				echo json_encode($data);
			}
			else{
				$data['response']='Validation Error';
				echo json_encode($data);
			}
		}
	}

	public function UnitEditProcess(){
		if ($this->input->is_ajax_request())
		{
			$this->form_validation->set_rules('unit_name','Unit Name','required|trim');
			$this->form_validation->set_rules('status','Status','required|trim');

			if($this->form_validation->run()){

				$unit_id_sha1=$this->input->post('unit_id',TRUE);
				$result=$this->crud->getIDProcessing($unit_id_sha1,'uom_id','uom');
				$unit_id= $result->uom_id;

				$unit_name=$this->input->post('unit_name',TRUE);
				$status=$this->input->post('status',TRUE);
				$dataSet=array(
					'uom'=>$unit_name,
					'status'=>$status,
				);
				$table="uom";

				if($this->crud->updateData($unit_id,$dataSet,'uom_id',$table)){
					$data['response']='Unit update successfully';
				}
				else{
					$data['response']='Error Occured';
				}
				echo json_encode($data);
			}
			else{
				$data['response']='Validation Error';
				echo json_encode($data);
			}
		}
	}

	public function getUnitJsonData(){
		if ($this->input->is_ajax_request()){
			$this->model->getUnitJsonData();
		}
	}

}
