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

require APPPATH . '/libraries/BaseController.php';

/**
 * Class : requisitionform (requisitionformController)
 * User Class to control all user related operations.
 * @author : VenbaMail Mali
 * @version : 1.1
 * @since : 15 Feb 2016
 */
class requisitionform extends BaseController
{
    /**
     * This is default constructor of the class
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->model('requistion_model');
		
       $this->load->library('session');
	     $this->load->library('form_validation');
		
        $this->isLoggedIn();   
    }
     /**
     * This function used to load the first screen of the Requistion
     */
    function requisitionlisting()
     {
		 $this->global['pageTitle'] = 'Siddharth : Requisition Listing';
		 
		  $userID =  $this->session->userdata ( 'userId' );
		 
		 // $data['ReqList'] = $this->requistion_model->getRequistListUserID($userID);  	  
		  $data['Status'] = $this->requistion_model->CheckDraftStatus($userID);
		
          $data['TotNoOfLine'] =$this->requistion_model->getRequistionList($userID);


         $this->loadViews("requisitionlisting", $this->global, $data, NULL);
     }
    /**
     * This function used to load the first screen of the requisition Form
     */   
       
	 function requisition()
	 {
		 $this->global['pageTitle'] = 'Siddharth : Raise Requisition';
		 
		 $data['RequestType'] = $this->requistion_model->getConfigValue('C004');  
		 
		 $data['EmpList'] = $this->requistion_model->getAllEmployees();  
		 
		 $userID =  $this->session->userdata ( 'userId' );
		 
		 $data['Emp'] = $this->requistion_model->getEmpIdByUserID($userID);
		   	 
         $data['CostCenter'] = $this->requistion_model->getCostCenterUserID($userID);		 
            
         $this->loadViews("requisitionform", $this->global,  $data,null);
	 }
	 
	  /**
     * This function used to load the first screen of the Requistion List Approval Screen
	 */
    function requisitionlistApproval()
     {
		  $this->global['pageTitle'] = 'Siddharth : Requisition Approval';
		  
		   $data['Status']= $this->requistion_model->getStatus();
		 
		   $userID =  $this->session->userdata ( 'userId' );
		 
		   $data['AppList'] = $this->requistion_model->getApproverRequistList($userID);  	  
		
		
           
         $this->loadViews("requisitionlistapproval", $this->global, $data, NULL);
     }
	 
	 
	 /**
     * This function used to load the Edit Requistion Form
	 */
    function EditRequistionForm()
     {
		   $this->global['pageTitle'] = 'Siddharth : Edit Requisition';
		
 		   $ReqNo=  $_GET['ReqNo'];
		   $ReqType=  $_GET['ReqType'];
		 
		   $userID =  $this->session->userdata ( 'userId' );
		 
		   $data['ReqDetails'] = $this->requistion_model->getRequistDetails($ReqNo,'Yes');
		  
		   
		   $data['LineItem'] = $this->requistion_model->getEditRequistItemList($ReqNo);   
		   //print_r( $data['LineItem']);
		   
		   $data['CostCenter'] = $this->requistion_model->getCostCenterUserID($userID);  
		   $data['MaterialCode'] = $this->requistion_model->EditMaterialCode($ReqNo, $ReqType);
           
         $this->loadViews("editrequisitionform", $this->global, $data, NULL);
     }
	 
	 /**
     * This function used to load the Delete the Requistion Items
	 */
    function DeleteRequistionForm()
     {
		   	  
 		   $ReqList=  $this->input->post('id');
		    $ReqNo ='';
		    $MaterialCode = '';
		   if(count($ReqList) > 0) 
		   {
			   $ReqNo =  $ReqList[0];
			    $MaterialCode =  $ReqList[1];
		   }
		 	   
		   $this->requistion_model->DeleteRequistionLineItem( $ReqNo,$MaterialCode);
		   
           echo "Successfully Deleted the Line item".$ReqNo;		  
        
     }
	 
	  /**
     * This function used to load the Delete the Requistion Items
	 */
    function DeleteReqNo()
     {
		   	  
 		   $ReqNo=  $this->input->post('id');
		  $dt = new DateTime('now', new DateTimeZone('Asia/Kolkata'));				
				$updateddt =  $dt->format('Y-m-d H:i:s');
		   $Request = array('Status'=>REQ_DELETED,'updatedOn'=>$updateddt);
					 
		   $this->requistion_model->UpdateRequistion( $Request,$ReqNo);
		   
           echo "Successfully Deleted the ".$ReqNo;		  
        
     }
	 
	 function SearchRequistList()
	 {
		  $userID =  $this->session->userdata ( 'userId' );
		  $ReqValue = $this->input->post('SearchDate');
       
		  $Dt =  explode("-",$ReqValue);
		
		  $FromDate ='';
		  $ToDate = '';
		  $Status= ''; 
		  if(count( $Dt)>1)
		  {
			   $FDate = $Dt[0]."-".$Dt[1]."-".$Dt[2];
				$TDate = $Dt[3]."-".$Dt[4]."-".$Dt[5];
			    $FromDate =  $this->getDateformat($FDate);
				$ToDate =  $this->getDateformat($TDate);
		   } 
		  
		   $St =  $this->input->post('RequisitionStatus');
		  
		   if($St == "-1")
		   {
			   $Status = '';
		   }
		   else
		   {
			   $Status = $St; 
		   }		  
        
		    $data['AppList'] = $this->requistion_model->getApproverRequistList($userID,$Status,$FromDate, $ToDate);
			
			$this->global['pageTitle'] = 'Siddharth : Requisition Approval';
		  
			$data['Status']= $this->requistion_model->getStatus();	  		
           
			$this->loadViews("requisitionlistapproval", $this->global, $data, NULL);
			
	 }
	 
	 
	 
	 function getDateformat($Val)
	{
		       $date = new DateTime($Val);
				$retDate = $date->format('Y-m-d H:i:s');
				return $retDate;
	}
	 /**
     * This function used to load the Employee details based on the EmpID selection
     */
	 function GetSelectedEmpDetails()
	 {
		   $ReqType =  $_GET['ReqType'];
		   $EmpID =  $this->input->post('id');		  
		   $empDetails = $this->requistion_model->GetEmployeeDetails( $EmpID );  
		   $DeptCode =  $empDetails[0]['DEPCode'];
		   $CostList = $this->requistion_model->GetCostCenterByDept( $DeptCode);
		   $HTML = "<option value='-1'>Select Cost center</option>";
		    $BudAmount = "";
		   if(count($CostList) > 0)
		   {
             for ($j = 0; $j < count($CostList); $j++)
			  {
				$Code = $CostList[$j]['CostCenterCode'];
				$Name = $CostList[$j]['CostCenterName'];
				$HTML .="<option value='".$Code."'>".$Code."-".$Name."</option>";
				}	
		   }	
           if(count($CostList) == 1)
		   {
			    $dt = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
				
				$Year =  $dt->format('Y');
				$CostCode = $CostList[0]['CostCenterCode'];
				
			   $Cost = $this->requistion_model->GetAvailableBudgetAmount( $CostCode,$Year,$ReqType);
			   if(count($Cost) >0)
			   {
				$BudAmount = $Cost[0]['BudgetAmount'];
			   }
		   }			   
		   die(json_encode(array('emp' => $empDetails,'Cost' => $HTML,'AvlAmount'  => $BudAmount)));
	 }
	 
	 function getAvailableBudAmount()
	 {		 
		   $ReqType =  $_GET['ReqType'];
		   $CostCode=  $this->input->post('id');
		   $dt = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
				
			$Year =  $dt->format('Y');
			
		   $Cost = $this->requistion_model->GetAvailableBudgetAmount( $CostCode,$Year,$ReqType);
		
			die(json_encode(array('Cost' =>$Cost)));
	 }
	// To get the Material code based on the Request type
	function getMaterialCode()
	 {		 
		  
		    $ReqType=  $this->input->post('id');	  
			
		    $MaterialCode = $this->requistion_model->GetMaterialCode( $ReqType);
			$MaterialName = "";
			$UOM = "";
		    $HTML = "<option value='-1'>Select Material Type</option>";
		   
		   if(count($MaterialCode) > 0)
		   {
             for ($j = 0; $j < count($MaterialCode); $j++)
			  {
				$Code = $MaterialCode[$j]['MaterialCode'];
				$Name = $MaterialCode[$j]['MaterialName'];
				$HTML .="<option value='".$Code."'>".$Code."-".$Name."</option>";
				
				}
				$MaterialName = $MaterialCode[0]['MaterialName'];
				$UOM = $MaterialCode[0]['UOM'];					
		   }   
		   
			die(json_encode(array('Material' =>$HTML,'MaterialName'=>$MaterialName,'UOM'=>$UOM)));
	 }
	
	// To get the Material value based on the MaterialCode
	function getMaterialDetails()
	 {		 
		  
		   $Material=  $this->input->post('id');	  
			
		   $MaterialDetails = $this->requistion_model->getRawMaterialList($Material);   
		  
			   
		   die(json_encode(array('MatDetail' =>$MaterialDetails)));
	 }
	 
	 /*
	 To Insert the Requistion Details to Database	 
	 */
	 /**
     * This function is used to add new Cost to the system
     */
    function addNewRequistion()
    {                   
           
            $this->form_validation->set_rules('RequestType','RequestType','trim|required');
            $this->form_validation->set_rules('EmpID','EmpID','trim|required');            
         
            if($this->form_validation->run() == FALSE)
            {
                $this->requisition();
            }
            else
            {
				$Status= $_GET['ID'];
                $RequestType = strtoupper(trim($this->input->post('RequestType')));
                $Requestedby = strtoupper(trim($this->input->post('EmpID'))); 
				$CostCenter = $this->input->post('CostCenter'); 		
                $CreateBy = $this->session->userdata ( 'userId' );
				$dt = new DateTime('now', new DateTimeZone('Asia/Kolkata'));				
				$createddt =  $dt->format('Y-m-d H:i:s');
				
				$DeletedRow =  $this->input->post('txtDeletedRow'); 
				$RowCount =  $this->input->post('txtRowCount'); 
				
				$comma_separated = explode(':', $DeletedRow);	
				
				
				 $IsExists = $this->requistion_model->RequistionIsExists($Requestedby);
				// print_r($IsExists);
				 
				 if(count( $IsExists) == 0)
				 {		
			        //echo 'Not Exists';
					$Request = array('ReqType'=>$RequestType, 'Requestedby'=>$Requestedby,'ReqDate'=>$createddt,'CostCenterCode'=>$CostCenter,'Status'=>$Status,'CreatedDate'=>$createddt,'CreatedBy'=>$CreateBy);
					
					print_r($Request);
					
					$Req  = $this->requistion_model->addRequistion($Request);
				 }
				 else
				 {
					   //echo 'Exists';
					 $Request = array('ReqType'=>$RequestType, 'Requestedby'=>$Requestedby,'ReqDate'=>$createddt,'Status'=>$Status,'CreatedDate'=>$createddt,'CreatedBy'=>$CreateBy,'CostCenterCode'=>$CostCenter);
					 $UpdateReq  = $this->requistion_model->UpdateRequistion($Request,$IsExists[0]['ReqNo']);
				 }
				 $ReqNumber = '';
				if(count($Req)>0)
				{
					 $ReqNumber =  $Req[0]['ReqNo'];
				}
				else
				{
					 $ReqNumber = $IsExists[0]['ReqNo'];
				}
							
			       $SkipInsert = False;
					for ($i = 1; $i <= $RowCount; $i++)
					 {	
						$SkipInsert = "False";				 
                       if( count($comma_separated) > 0)
					   {
					   for($j = 1; $j < count($comma_separated); $j++)
					   {	
                          $deletedRow = 	$comma_separated[$j]	;
						
						  if($deletedRow == $i  )
						  {
							  $SkipInsert = "True";
							  break;
						  }						 
                          
						}
					   }
					 
					    if($SkipInsert == "False")
						   {
							$MaterialCode = $this->input->post('MaterialCode'.$i);
							$Quantity = $this->input->post('Quantity'.$i); 
					 
							$ReqDetails = array('ReqNo'=>$ReqNumber, 'MaterialCode'=>$MaterialCode,'Quantity'=>$Quantity);
								$this->requistion_model->addRequistionDetails($ReqDetails);
						   } 								
					 
					}	
					if($Status == REQ_DRAFT)
					{
					    echo 'Successfully Saved the Requistion details';
					}
					else
					{
						echo 'Successfully Created the Requistion details';
					} 
          
            }
        
    }
	function EditRequistion()
    {            
                $Status = $this->input->post('txtStatus');	
                $ReqNumber = $this->input->post('txtReqNo');
				//echo    $ReqNumber;    
                $UpdatedBy = $this->session->userdata ( 'userId' );
				$dt = new DateTime('now', new DateTimeZone('Asia/Kolkata'));				
				$updatedDate =  $dt->format('Y-m-d H:i:s');
				
				$DeletedRow =  $this->input->post('txtDeletedRow'); 
				$RowCount =  $this->input->post('txtRowCount'); 
				
				if(strlen($Status) > 1)
				{
					$Request = array( 'Status'=>$Status,'CreatedDate'=>$updatedDate,'CreatedBy'=>$UpdatedBy);
					 $UpdateReq  = $this->requistion_model->UpdateRequistion($Request, $ReqNumber);
				}
				else
				{
						$Request = array( 'Status'=>REQ_PENDING_APPROVAL,'updatedOn'=>$updatedDate);
					 $UpdateReq  = $this->requistion_model->UpdateRequistion($Request, $ReqNumber);
				}
				
				
				$comma_separated = explode(':', $DeletedRow);	
								 
					/* Table value update and Insert in the table */			
							
			       $SkipInsert = False;
					for ($i = 1; $i <= $RowCount; $i++)
					 {	
						$SkipInsert = "False";				 
                       if( count($comma_separated) > 0)
					   {
					   for($j = 1; $j < count($comma_separated); $j++)
					   {	
                          $deletedRow = 	$comma_separated[$j]	;
						
						  if($deletedRow == $i  )
						  {
							  $SkipInsert = "True";
							  break;
						  }						 
                          
						}
					   }
					 
					    if($SkipInsert == "False")
						   {
							$MaterialCode = $this->input->post('MaterialCode'.$i);
							$Quantity = $this->input->post('Quantity'.$i); 
					        $IsExists = $this->requistion_model->LineItemIsExists($ReqNumber,$MaterialCode);
							if(count( $IsExists) == 0)
							{	
						       $ReqDetails = array('ReqNo'=>$ReqNumber, 'MaterialCode'=>$MaterialCode,'Quantity'=>$Quantity,'UpdatedBy'=>$UpdatedBy,'UpdatedOn'=>$updatedDate);
								$this->requistion_model->addRequistionDetails($ReqDetails);
							}
							else
							{
								$ReqDetails = array('ReqNo'=>$ReqNumber, 'MaterialCode'=>$MaterialCode,'Quantity'=>$Quantity,'UpdatedBy'=>$UpdatedBy,'UpdatedOn'=>$updatedDate);
								$this->requistion_model->UpdateRequistionLineItem($ReqDetails,$ReqNumber,$MaterialCode);
							}								
							
							
						   } 								
					 
					}						
						 echo 'Successfully updated the Requistion details';
					    // $this->requisitionlisting();
						
                     
            
        
    }
/* To Edit the request*/	
	 function ViewRequest()
     {
		 
		 $ReqNo= $this->input->post('id');
         $result =  $this->requistion_model->getRequistItemList($ReqNo);
		 $ReqList = $this->requistion_model->getRequistDetails($ReqNo);
		 $DepNo = $ReqList[0]['DEPCode'];
		 //$CostList = $this->requistion_model->GetCostCenterByDept($DepNo);
		  $HTML="";	
   		  for ($i = 0; $i < count($result); $i++)
			 {
					$SNo = $i + 1;
					$MaterialCode = $result[$i]['MaterialCode'];
					$MaterialName = $result[$i]['MaterialName'];
					$UOM = $result[$i]['UOM'];					
					$Quantity = $result[$i]['Quantity'];
					$Quantity = $result[$i]['Quantity'];
					$POQTY = $result[$i]['POQTY'];
					$StatusName= $result[$i]['StatusName'];
					$HTML.="<tr  id='".$i."'>
							<td align='left'>".$SNo."</td>
							<td align='left'>". $MaterialCode."</td>
													                      
							<td align='left'>".$MaterialName."</td>
							
							<td align='left'>".$UOM."</td>	
								<td align='left'>".$Quantity."</td>	
							<td	align='left'>".$POQTY."</td>
							<td align='left'>".$StatusName."</td>								
							</tr>";

					//$index =  $index + 1;
   
			}
			$CostCode = '';
			$ReqType = '';
			$dt = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
				
			$Year =  $dt->format('Y');
			if(count($ReqList)>0)
			{
			
				$ReqType = $ReqList[0]['ReqType'];
				
				$CostCode = $ReqList[0]['CostCenterCode'];	
			}
			$this->load->model('purchaseorder_model');
		    $AvlBudget = $this->purchaseorder_model->GetAvailableBudgetAmount($CostCode,$Year,$ReqType);
			 //print_r($result);
		    $AvilBudAmt = '0';
			if(count($AvlBudget)>0)
			{
         		$AvilBudAmt = $AvlBudget[0]['BudgetAmount'] -  $AvlBudget[0]['Totalvalue'];
			}
           //echo 	$AvilBudAmt;		
			die(json_encode(array('Items' =>$HTML,'Requist'=>$ReqList,'AvilBudAmount'=>number_format($AvilBudAmt,2))));	
     }
	 
	function ApproveRequest()
	{
		  $Status= Trim($_GET['Status']);
		  
		  $ReqNo= $_GET['ReqNo'];
		  $Remarks = trim($this->input->post('id'));
		  $ApprovedBy = $this->session->userdata ( 'userId' );
				$dt = new DateTime('now', new DateTimeZone('Asia/Kolkata'));				
				$ApprovedDate =  $dt->format('Y-m-d H:i:s');
		  $Request = array('Status'=>$Status,'Comments'=>$Remarks,'ApprovedOn'=>$ApprovedDate,'Approvedby'=>$ApprovedBy);
		  $this->requistion_model->UpdateRequistion($Request,$ReqNo); 
		 echo "Successfully Updated the Requistion No: ".$ReqNo;
		 
  }	
	 
    function pageNotFound()
    {
        $this->global['pageTitle'] = 'CodeInsect : 404 - Page Not Found';
        
        $this->loadViews("404", $this->global, NULL, NULL);
    }
}

?>