<?php 
/**
 * Leave_granter Page Controller
 * @category  Controller
 */
class Leave_granterController extends SecureController{
	function __construct(){
		parent::__construct();
		$this->tablename = "leave_granter";
	}
	/**
     * List page records
     * @param $fieldname (filter record by a field) 
     * @param $fieldvalue (filter field value)
     * @return BaseView
     */
	function index($fieldname = null , $fieldvalue = null){
		$request = $this->request;
		$db = $this->GetModel();
		$tablename = $this->tablename;
		$fields = array("leave_granter.id", 
			"portfolio.name AS portfolio_name", 
			"leave_granter.leave_type", 
			"leave_granter.nodays");
		$pagination = $this->get_pagination(MAX_RECORD_COUNT); // get current pagination e.g array(page_number, page_limit)
		//search table record
		if(!empty($request->search)){
			$text = trim($request->search); 
			$search_condition = "(
				leave_granter.id LIKE ? OR 
				portfolio.name LIKE ? OR 
				leave_granter.leave_type LIKE ? OR 
				leave_granter.portfolio_id LIKE ? OR 
				leave_granter.nodays LIKE ? OR 
				portfolio.pid LIKE ?
			)";
			$search_params = array(
				"%$text%","%$text%","%$text%","%$text%","%$text%","%$text%"
			);
			//setting search conditions
			$db->where($search_condition, $search_params);
			 //template to use when ajax search
			$this->view->search_template = "leave_granter/search.php";
		}
		$db->join("portfolio", "leave_granter.portfolio_id = portfolio.id", "LEFT");
		if(!empty($request->orderby)){
			$orderby = $request->orderby;
			$ordertype = (!empty($request->ordertype) ? $request->ordertype : ORDER_TYPE);
			$db->orderBy($orderby, $ordertype);
		}
		else{
			$db->orderBy("leave_granter.id", ORDER_TYPE);
		}
		if($fieldname){
			$db->where($fieldname , $fieldvalue); //filter by a single field name
		}
		$tc = $db->withTotalCount();
		$records = $db->get($tablename, $pagination, $fields);
		$records_count = count($records);
		$total_records = intval($tc->totalCount);
		$page_limit = $pagination[1];
		$total_pages = ceil($total_records / $page_limit);
		$data = new stdClass;
		$data->records = $records;
		$data->record_count = $records_count;
		$data->total_records = $total_records;
		$data->total_page = $total_pages;
		if($db->getLastError()){
			$this->set_page_error();
		}
		$page_title = $this->view->page_title = "Leave Granter";
		$this->view->report_filename = date('Y-m-d') . '-' . $page_title;
		$this->view->report_title = $page_title;
		$this->view->report_layout = "report_layout.php";
		$this->view->report_paper_size = "A4";
		$this->view->report_orientation = "portrait";
		$this->render_view("leave_granter/list.php", $data); //render the full page
	}
	/**
     * View record detail 
	 * @param $rec_id (select record by table primary key) 
     * @param $value value (select record by value of field name(rec_id))
     * @return BaseView
     */
	function view($rec_id = null, $value = null){
		$request = $this->request;
		$db = $this->GetModel();
		$rec_id = $this->rec_id = urldecode($rec_id);
		$tablename = $this->tablename;
		$fields = array("leave_granter.id", 
			"leave_granter.leave_type", 
			"leave_granter.portfolio_id", 
			"leave_granter.nodays", 
			"portfolio.name AS portfolio_name", 
			"portfolio.pid AS portfolio_pid");
		if($value){
			$db->where($rec_id, urldecode($value)); //select record based on field name
		}
		else{
			$db->where("leave_granter.id", $rec_id);; //select record based on primary key
		}
		$db->join("portfolio", "leave_granter.portfolio_id = portfolio.id", "LEFT ");  
		$record = $db->getOne($tablename, $fields );
		if($record){
			$page_title = $this->view->page_title = "View  Leave Granter";
		$this->view->report_filename = date('Y-m-d') . '-' . $page_title;
		$this->view->report_title = $page_title;
		$this->view->report_layout = "report_layout.php";
		$this->view->report_paper_size = "A4";
		$this->view->report_orientation = "portrait";
		}
		else{
			if($db->getLastError()){
				$this->set_page_error();
			}
			else{
				$this->set_page_error("No record found");
			}
		}
		return $this->render_view("leave_granter/view.php", $record);
	}
	/**
     * Insert new record to the database table
	 * @param $formdata array() from $_POST
     * @return BaseView
     */
	function add($formdata = null){
		if($formdata){
			$db = $this->GetModel();
			$tablename = $this->tablename;
			$request = $this->request;
			//fillable fields
			$fields = $this->fields = array("leave_type","portfolio_id","nodays");
			$postdata = $this->format_request_data($formdata);
			$this->rules_array = array(
				'leave_type' => 'required',
				'portfolio_id' => 'required',
				'nodays' => 'numeric',
			);
			$this->sanitize_array = array(
				'leave_type' => 'sanitize_string',
				'portfolio_id' => 'sanitize_string',
				'nodays' => 'sanitize_string',
			);
			$this->filter_vals = true; //set whether to remove empty fields
			$modeldata = $this->modeldata = $this->validate_form($postdata);
			if($this->validated()){
		# Statement to execute before adding record
		if(!isset($modeldata['nodays'])){
//query the database and return a single field value
$db->where("leave_type", $modeldata["leave_type"]);
$value = $db->getValue("leave_master", "default_days");
$modeldata['nodays'] = $value;
}
		# End of before add statement
				$rec_id = $this->rec_id = $db->insert($tablename, $modeldata);
				if($rec_id){
		# Statement to execute after adding record
		//query the database and return the results
$fields = array('id','employee_name');
$db->where("portfolio_id=".$modeldata["portfolio_id"] ) ;
$arr = $db->get("employee_details",9999999999, $fields);
// echo  $modeldata["portfolio_id"];
// print_r($arr);
// exit();
foreach($arr as $k){
    //query the database and return a single field value
if($modeldata['leave_type']=='Medical'){
    $entrydate = $modeldata['nodays'];
}else{
    $db->where("empid", $k["id"]);
    $db->where("leave_type != 'Medical'");/// FOR MEDICAL @@@@@@@@@@@@@ COSTOMIZ
    $value     = $db->getValue("leave_grant", "SUM(value)");
    $entrydate = $modeldata['nodays'];
    if(($value+$modeldata['nodays'])>300){
    $entrydate = ($modeldata['nodays'])-(($value+$modeldata['nodays'])-300);
    }
}
    $empid = $k['id'];
    $table_data = array(
    "leave_type" => $modeldata["leave_type"],
    "empid" => $empid,
    "value" =>  $entrydate,
    "givenby" => USER_NAME,
    "granter_id" => $rec_id 
    );
    $db->insert("leave_grant", $table_data); 
}
		# End of after add statement
					$this->set_flash_msg("Record added successfully", "success");
					return	$this->redirect("leave_granter");
				}
				else{
					$this->set_page_error();
				}
			}
		}
		$page_title = $this->view->page_title = "Add New Leave Granter";
		$this->render_view("leave_granter/add.php");
	}
	/**
     * Update table record with formdata
	 * @param $rec_id (select record by table primary key)
	 * @param $formdata array() from $_POST
     * @return array
     */
	function edit($rec_id = null, $formdata = null){
		$request = $this->request;
		$db = $this->GetModel();
		$this->rec_id = $rec_id;
		$tablename = $this->tablename;
		 //editable fields
		$fields = $this->fields = array("id","leave_type","portfolio_id","nodays");
		if($formdata){
			$postdata = $this->format_request_data($formdata);
			$this->rules_array = array(
				'leave_type' => 'required',
				'portfolio_id' => 'required',
				'nodays' => 'numeric',
			);
			$this->sanitize_array = array(
				'leave_type' => 'sanitize_string',
				'portfolio_id' => 'sanitize_string',
				'nodays' => 'sanitize_string',
			);
			$modeldata = $this->modeldata = $this->validate_form($postdata);
			if($this->validated()){
				$db->where("leave_granter.id", $rec_id);;
				$bool = $db->update($tablename, $modeldata);
				$numRows = $db->getRowCount(); //number of affected rows. 0 = no record field updated
				if($bool && $numRows){
					$this->set_flash_msg("Record updated successfully", "success");
					return $this->redirect("leave_granter");
				}
				else{
					if($db->getLastError()){
						$this->set_page_error();
					}
					elseif(!$numRows){
						//not an error, but no record was updated
						$page_error = "No record updated";
						$this->set_page_error($page_error);
						$this->set_flash_msg($page_error, "warning");
						return	$this->redirect("leave_granter");
					}
				}
			}
		}
		$db->where("leave_granter.id", $rec_id);;
		$data = $db->getOne($tablename, $fields);
		$page_title = $this->view->page_title = "Edit  Leave Granter";
		if(!$data){
			$this->set_page_error();
		}
		return $this->render_view("leave_granter/edit.php", $data);
	}
	/**
     * Delete record from the database
	 * Support multi delete by separating record id by comma.
     * @return BaseView
     */
	function delete($rec_id = null){
		Csrf::cross_check();
		$request = $this->request;
		$db = $this->GetModel();
		$tablename = $this->tablename;
		$this->rec_id = $rec_id;
		//form multiple delete, split record id separated by comma into array
		$arr_rec_id = array_map('trim', explode(",", $rec_id));
		$db->where("leave_granter.id", $arr_rec_id, "in");
		$bool = $db->delete($tablename);
		if($bool){
		#Statement to execute after delete record
$db->where("granter_id", $rec_id);
$bool = $db->delete("leave_grant");
		# End of after delete statement
			$this->set_flash_msg("Record deleted successfully", "success");
		}
		elseif($db->getLastError()){
			$page_error = $db->getLastError();
			$this->set_flash_msg($page_error, "danger");
		}
		return	$this->redirect("leave_granter");
	}
}
