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

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

/**
 * Class : purchaseorder (PurchaseorderController)
 * User Class to control all user related operations.
 * @author : VenbaMail Mali
 * @version : 1.1
 * @since : 15 Feb 2016
 */
class servicepurchaseorder extends BaseController
{
    /**
     * This is default constructor of the class
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->model('purchaseorder_model');
		
       $this->load->library('session');
	     $this->load->library('form_validation');
		$this->load->model('requistion_model');
        $this->isLoggedIn();   
    }
    
   
	// To get the available Budget Amount
	function AvilBudgetAmount()
	 {		
          // echo 'Controller called';	 
		   $CostCode = $this->input->post('id');
		   $ReqType =  $_GET['ReqType']; 
		   
		
		   $dt = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
				
			$Year =  $dt->format('Y');
			$this->load->model('purchaseorder_model');
		    $result = $this->purchaseorder_model->GetAvailableBudgetAmount($CostCode,$Year,$ReqType);
			 //print_r($result);
		    $AvilBudAmt = '0';
			if(count($result)>0)
			{
         		$AvilBudAmt = $result[0]['BudgetAmount'] -  $result[0]['Totalvalue'];
			}				
		   
		  //  echo 'Test';
		   print_r($AvilBudAmt);
			//die(json_encode(array('Cost' => $AvilBudAmt)));
	 }
	 
	 
	 function getDateformat($Val)
	{
		       $date = new DateTime($Val,new DateTimeZone('Asia/Kolkata'));
			 //  print_r($date);
				$retDate = $date->format('Y-m-d H:i:s');
				return $retDate;
	}
	
	//This used to Create Service Purchase Order
	function addNewServicePurchaseOrder()
	{
				$POdt =$this->input->post('PODate');
				$PODate =  $this->getDateformat($POdt);
                $SupplierID = $this->input->post('drpSupplier');  
				$DeliveryAddr = $this->input->post('DeliveryAddr');
				$dt = $this->input->post('Deliverydt');
				$Deliverydt = $this->getDateformat($dt);
$DeliveryOption = $this->input->post('DateRange');
        if($DeliveryOption==1){
         $Deliverydt = '';
        $DeliverySchedule = $this->input->post('Scheduleby');
        }
         else{
         $Deliverydt = $this->getDateformat($dt);
        $DeliverySchedule = '';
        }
				$POType = $this->input->post('POType');
								
				$SpcialInstruction = $this->input->post('txtSpcialInstruction');
				$TotalOrderValueSummary = $this->input->post('txtTotalOrderValueSummary');
			    $POStatus = $this->input->post('txtStatus');

                $CreateBy = $this->session->userdata ( 'userId' );
				$RowCount =  $this->input->post('txtRowCount'); 
				$DeletedRow =  $this->input->post('txtDeletedRow'); 
				
				$comma_separated = explode(':', $DeletedRow);	
				
				$dt = new DateTime('now', new DateTimeZone('Asia/Kolkata'));				
				$createddt =  $dt->format('Y-m-d H:i:s');
				// PO Master
								$POList = array('SupplierID'=>$SupplierID, 'TotalOrderValue'=>$TotalOrderValueSummary,'PODate'=>$PODate,'Status'=>$POStatus,'DeliverySchedule'=>$DeliverySchedule,'DeliveryOption'=>$DeliveryOption,Delivery'ServiceDescription'=>$SpcialInstruction,'CreatedBy'=>$CreateBy,'DeliveryAddress'=>$DeliveryAddr,'DeliveryDate'=>$Deliverydt,'CreatedDate'=>$createddt );

					
					$POMaster  = $this->purchaseorder_model->addPOMaster($POList);
					
					 $PONO = '';
					if(count($POMaster)>0)
					{
					 $PONO =  $POMaster[0]['PONO'];
					}
					
					// PO Line Items
					$LineItemStatus = REQITEM_NEW;
					
						for ($i = 1; $i <= $RowCount; $i++)
							{	
							
								$MaterialCode = $this->input->post('materialCode'.$i);
								$Quantity = $this->input->post('quantity'.$i); 
								$Reqnumber = $this->input->post('Reqnumber'.$i);
								$itemRate = $this->input->post('itemRate'.$i);
								$ServiceTax = $this->input->post('ServiceTax'.$i);
								$EduCess = $this->input->post('EduCess'.$i);
								$SecHighTax = $this->input->post('SecHighTax'.$i);
								$KrishiTax = $this->input->post('KrishiTax'.$i);
								$SwachhTax = $this->input->post('SwachhTax'.$i);
								$CostCenter	= $this->input->post('costCode'.$i);
								
								$TotalOrderValue = $this->input->post('TotalOrderValue'.$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")
									{
								
								$POLineItemList = array('PONO'=>$PONO, 'ReqNo'=>$Reqnumber,'MaterialCode'=>$MaterialCode,'Quantity'=>$Quantity,'Rate'=>$itemRate,'Status'=>$LineItemStatus,'CreatedBy'=>$CreateBy,'CreatedDate'=>$createddt,'CostCenterCode'=>$CostCenter);
					
								$POLineItem = $this->purchaseorder_model->addPOLineItem($POLineItemList);
					
								$LineItemNo = '';
								
								if(count($POLineItem)>0)
								{
									$LineItemNo =  $POLineItem[0]['LineItemNo'];
								}
								//echo $LineItemNo; 
								
								if(trim($POType) == SERVICE )
								{
								//	echo 'Success';
								$ServiceTaxList = array('LineItemNo'=>$LineItemNo, 'ServiceTax'=>$ServiceTax,'EducessTax'=>$EduCess,'SecHigherEducessTax'=>$SecHighTax,'KrishiKalyantax'=>$KrishiTax,'SwachhBharattax'=>$SwachhTax,'TotalValue'=>$TotalOrderValue, 'CreatedBy'=>$CreateBy,'CreatedDate'=>$createddt);
								
								$ServiceTax = $this->purchaseorder_model->addServiceTax($ServiceTaxList);
								
								}
									}
								
							}							
					echo 'Service Purchase Order Created Successfully!The PO NO Is: '.$PONO;
					
	}
	function UpdateServicePurchaseOrder()
	{
				$PONO =$this->input->post('txtPONO');
				//echo $PONO;
				$POdt =$this->input->post('PODate');
				$PODate =  $this->getDateformat($POdt);
				
                $SupplierID = $this->input->post('drpSupplier');  
				$DeliveryAddr = $this->input->post('txtDeliveryAddress');
				$dt = $this->input->post('Deliverydt');
				$Deliverydt = $this->getDateformat($dt);
				
				$POType = $this->input->post('POType');
								
				$SpcialInstruction = $this->input->post('SpcialInstruction');
				$TotalOrderValueSummary = $this->input->post('txtTotalOrderValueSummary');
			    $POStatus = $this->input->post('txtStatus');

                $updatedBy = $this->session->userdata ( 'userId' );
				$RowCount =  $this->input->post('txtRowCount'); 
				$DeletedRow =  $this->input->post('txtDeletedRow'); 
				
				$comma_separated = explode(':', $DeletedRow);
				$dt = new DateTime('now', new DateTimeZone('Asia/Kolkata'));				
				$updateddt =  $dt->format('Y-m-d H:i:s');
				
				
				// PO Master
				$POList = array('SupplierID'=>$SupplierID, 'TotalOrderValue'=>$TotalOrderValueSummary,'PODate'=>$PODate,'Status'=>$POStatus,'ServiceDescription'=>$SpcialInstruction,'UpdateBY'=>$updatedBy,'DeliveryAddress'=>$DeliveryAddr,'DeliveryDate'=>$Deliverydt,'UpdatedOn'=>$updateddt );

				$POMaster  = $this->purchaseorder_model->updatePOMaster($PONO,$POList);				
				
				$LineItemStatus = REQITEM_NEW;
				
				for ($i = 1; $i <= $RowCount; $i++)
				{								
					$MaterialCode = $this->input->post('materialCode'.$i);
					$Quantity = $this->input->post('quantity'.$i); 
					$Reqnumber = $this->input->post('Reqnumber'.$i);
					$itemRate = $this->input->post('itemRate'.$i);
					$ServiceTax = $this->input->post('ServiceTax'.$i);
					$EduCess = $this->input->post('EduCess'.$i);
					$SecHighTax = $this->input->post('SecHighTax'.$i);
					$KrishiTax = $this->input->post('KrishiTax'.$i);
					$SwachhTax = $this->input->post('SwachhTax'.$i);
					$CostCenter	= $this->input->post('costCode'.$i);
					$POLineItemNo = $this->input->post('LineItemNo'.$i);
					$TotalOrderValue = $this->input->post('TotalOrderValue'.$i);							
					
					$POLineItem = array();
					$LineItemNo = '';
					$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")
				{
					if(strlen($POLineItemNo) == 0)
					{
						$POLineItemList = array('PONO'=>$PONO, 'ReqNo'=>$Reqnumber,'MaterialCode'=>$MaterialCode,'Quantity'=>$Quantity,'Rate'=>$itemRate,'Status'=>$LineItemStatus,'CreatedBy'=>$updatedBy,'CreatedDate'=>$updateddt,'CostCenterCode'=>$CostCenter);
						$POLineItem = $this->purchaseorder_model->addPOLineItem($POLineItemList);
						if(count($POLineItem)>0)
						{
							$LineItemNo =  $POLineItem[0]['LineItemNo'];
						}
					
					}
					else
					{
						$LineItemNo = $POLineItemNo;	
						
						$POLineItemList = array('PONO'=>$PONO, 'ReqNo'=>$Reqnumber,'MaterialCode'=>$MaterialCode,'Quantity'=>$Quantity,'Rate'=>$itemRate,'Status'=>$LineItemStatus,'UpdateBY'=>$updatedBy,'UpdatedOn'=>$updateddt,'CostCenterCode'=>$CostCenter);
						$POLineItem = $this->purchaseorder_model->updatePOLineItem($PONO,$POLineItemNo,$POLineItemList);					
						
					}

					
					
					if(trim($POType) == SERVICE )
					{
					$isExists = $this->purchaseorder_model->LineItemExists($LineItemNo); 
					
					if(count($isExists) == 0)
					{
					$ServiceTaxList = array('LineItemNo'=>$LineItemNo, 'ServiceTax'=>$ServiceTax,'EducessTax'=>$EduCess,'SecHigherEducessTax'=>$SecHighTax,'KrishiKalyantax'=>$KrishiTax,'SwachhBharattax'=>$SwachhTax,'TotalValue'=>$TotalOrderValue, 'CreatedBy'=>$updatedBy,'CreatedDate'=>$updateddt);
					
					  $this->purchaseorder_model->addServiceTax($ServiceTaxList);
					
					}
					else
					{
						$ServiceTaxList1 = array('ServiceTax'=>$ServiceTax,'EducessTax'=>$EduCess,'SecHigherEducessTax'=>$SecHighTax,'KrishiKalyantax'=>$KrishiTax,'SwachhBharattax'=>$SwachhTax,'TotalValue'=>$TotalOrderValue, 'UpdateBY'=>$updatedBy,'UpdatedOn'=>$updateddt);
						
						$this->purchaseorder_model->updateServiceTax($LineItemNo,$ServiceTaxList1); 
						
					}
					
					}
					
				} 				
				}
				echo 'Successfully updated the Service Purchase Order';	
	}
    function pageNotFound()
    {
        $this->global['pageTitle'] = 'CodeInsect : 404 - Page Not Found';
        
        $this->loadViews("404", $this->global, NULL, NULL);
    }
}

?>
