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

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

/**
 * Class : Cost Center (Cost Center Controller)
 * User Class to control all user related operations.
 * @author : VenbaMail Mali
 * @version : 1.1
 * @since : 15 Feb 2016
 */
class CostCenter extends BaseController
{
    /**
     * This is default constructor of the class
     */
	 public function __construct()
    {
        parent::__construct();
        $this->load->model('costcenter_model');
		//$this->load->library('session');
	   $this->load->library('form_validation');
	   $this->load->library('pagination');
		
        $this->isLoggedIn();   
    }
	/**
     * This function used to load the first screen of the user
     */
	public function index()
    {
        $this->global['pageTitle'] = 'Siddharth : Cost';
        
        $this->loadViews("costListing", $this->global, NULL , NULL);
    }
	
	/**
     * This function is used to load the Cost list
     */
    function CostListing()
    {
                                   
                     
            $data['userRecords'] = $this->costcenter_model->CostListing();
			
			       
            $this->global['pageTitle'] = 'Siddharth : Cost List';
            
            $this->loadViews("costListing", $this->global, $data, NULL);
        
    }
	
	/**
     * This function is used to load the add new cost Center   */
    function addCostCenter()
    {
        
            $data['Department'] = $this->costcenter_model->getDepartment();  
			
			$data['BudgetType'] = $this->costcenter_model->getConfigValue('C004');   

            $data['Approver'] = $this->costcenter_model->getApproverName(); 	
            
            $this->global['pageTitle'] = 'siddharth : Add Cost Center';

            $this->loadViews("addCostCenter", $this->global,$data,  NULL);
        
	} 
	
	function  Dep_SelectedDepartment($selectValue)
{
	//echo 'select_validate  method called';
    // 'none' is the first option and the text says something like "-Choose one-"
   if(strlen($SelectedDepartment) <= 0 )
    {
        $this->form_validation->set_message('Dep_SelectedDepartment', 'Please Select Department.');
        return false;
    }
    else // user picked something
    {
        return true;
    }
}

	/**
     * This function is used to add new Cost to the system
     */
    function addNewcost()
    {
                   
           
            $this->form_validation->set_rules('CostCode','CostCode','trim|required');
            $this->form_validation->set_rules('CostName','CostName','trim|required');            
         
            if($this->form_validation->run() == FALSE)
            {
                $this->addCostCenter();
            }
            else
            {
                $CostCode = strtoupper(trim($this->input->post('CostCode')));
                $CostName = strtoupper(trim($this->input->post('CostName')));            
                $CreateBy = $this->session->userdata ( 'userId' );
				$SelectedDepartment =  $this->input->post('txtSelectedDepartment'); 
				$ApproverName =  $this->input->post('ApprovedBy'); 
				$comma_separated = explode(':', $SelectedDepartment);	
				$dt = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
				
				$createddt =  $dt->format('Y-m-d H:i:s');
				
				$CodeExists =  $this->costcenter_model->checkCostDetailsExists( $CostCode);
				
				if(count($CodeExists) == 0)
				{
				 $Cost = array('CostCenterCode'=>$CostCode, 'CostCenterName'=>$CostName,'ApprovedBy'=>$ApproverName,'CreatedBy'=>$CreateBy,'createdDate'=>$createddt); 
				 $this->costcenter_model->addNewcost($Cost);
				}
				
				for ($j = 0; $j < count($comma_separated); $j++)
					 {	
							$DeptCode = $comma_separated[$j];
						   
						     $this->costcenter_model->DeleteDepartment( $DeptCode,$CostCode);
						
							$Dept = array('CostCenterCode'=>$CostCode, 'DEPCode'=>$DeptCode,'CreatedBy'=>$CreateBy,'createdDate'=>$createddt);
							$this->costcenter_model->addCostCenterDepartment($Dept);				
									 
					}
					$RowCount = $this->input->post('txtRowCount');
			
					for ($i = 1; $i <= $RowCount; $i++)
					 {				     
					  $BudgetType = $this->input->post('BudgetType'.$i);
					  $BudgetYear = $this->input->post('BudgetYear'.$i); 
					  $BudgetAmount = $this->input->post('BudgetAmount'.$i);  
					  $Remarks = $this->input->post('Remarks'.$i);
					  $this->costcenter_model->DeleteBudget( $BudgetType,$BudgetYear,$CostCode);
						
				     $Budget = array('CostCenterCode'=>$CostCode, 'BudgetType'=>$BudgetType,'BudgetYear'=>$BudgetYear,'BudgetAmount'=>$BudgetAmount,'Remarks'=>$Remarks,'CreatedBy'=>$CreateBy,'createdDate'=>$createddt);
						$this->costcenter_model->addBudget($Budget);	
					 
					}	
					
					Print_r('Successfully Created Cost details');
          
            }
        
    }
	/**
     * This function is used load user edit information
     * @param number $userId : Optional : This is user id
     */
	function editOldcost($CostCode = NULL)
    {
        
            if($CostCode == '')
			{
			 $CostCenterID =  $_GET['CostCode']; 
			}
			else
			{
				
			 $CostCenterID  = $CostCode;		
			 }
            
            $data['CostMaster'] = $this->costcenter_model->GetCostCenterMaster($CostCenterID);
			 $data['CostDepts'] = $this->costcenter_model->GetCostCenterDepartment($CostCenterID);
			 $data['CostBudget'] = $this->costcenter_model->GetCostCenterBudget($CostCenterID);
			$data['DeptList'] = $this->costcenter_model->GetDepartmentNotinCostCenter($CostCenterID);
			$data['BudType'] = $this->costcenter_model->GetBudgetTypeNotinCostCenter($CostCenterID,'C004');
			$data['BudYear'] = $this->costcenter_model->GetBudgetYear($CostCenterID);
            //print_r(count($data['BudType']));
            
            $this->global['pageTitle'] = 'Siddharth : Edit Cost';
            
            $this->loadViews("editOldcost", $this->global, $data,NULL);
        
    }
	
	function GetBudgetForYear()
	{
		 //$id = $this->input->post('id');
		 $BudYear =  $_GET['BudYear']; 
		 $CostCenterID =  $_GET['CostCode']; 
		 $result = $this->costcenter_model->GetCostCenterBudgetByYear($CostCenterID, $BudYear);
		 $BudList = $this->costcenter_model->GetCostBudgetTypeByYear($CostCenterID,'C004', $BudYear);
		 $HTML="";
		 $HTML2="";
         $index = 1;
		 // $HTML2 =  $BudList[0]['ConfigValue'];
		 //if($BudList->num_rows() > 0){
			for ($j = 0; $j < count($BudList); $j++)
			 {
				$ConfigValue = $BudList[$j]['ConfigValue'];
				$HTML2.="<option value='".$ConfigValue."'>".$ConfigValue."</option>";
				}
				
		 for ($i = 0; $i < count($result); $i++)
			 {
					$BudgetType = $result[$i]['BudgetType'];
					$BudgetYear = $result[$i]['BudgetYear'];
					$BudgetAmount = $result[$i]['BudgetAmount'];
					$Remarks = $result[$i]['Remarks'];
					$HTML.="<tr  id='".$index."'>
							<td align='left'>". $BudgetType."</td>
							 <input type='hidden' name='BudgetType".$index."'  id='BudgetType".$index."' value='". $BudgetType."'/>
							  <input type='hidden' name='BudgetYear".$index."' id='BudgetYear".$index."' value='". $BudgetYear."'/>
							   <input type='hidden' name='BudgetAmount".$index."' id='BudgetAmount".$index."' value='". $BudgetAmount."'/>
							    <input type='hidden' name='Remarks".$index."' id='Remarks".$index."' value='". $Remarks."'/>
							                      
							<td align='left'>".$BudgetYear."</td>
							
							<td align='left'>".$BudgetAmount."</td>

							<td align='left'>".$Remarks."</td> 
							<td>
                          <a   data-target='#Edit'	data-id=".$index." data-userid=".$index." data-toggle='modal' href='#Edit'><i class='fa fa-pencil' data-toggle='tooltip' title='Click here to view/Edit the  ".$BudgetType." Budget details'></i>&nbsp;&nbsp;&nbsp;</a> </td></tr> 
						 ";

			$index =  $index + 1;
   
   } 
    $HTML.="<input type='hidden' name='txtRowCount' id='txtRowCount' value='".$index ."'/>";
     die(json_encode(array('Html' => $HTML,'BudYear' =>  $HTML2)));
  // echo $HTML2;
	}
	
	/**
     * This function is used to edit the user information
     */
    function editcost()
    {
			
            $this->form_validation->set_rules('CostCode','CostCode','trim|required');
            $this->form_validation->set_rules('CostName','CostName','trim|required');            
         
            if($this->form_validation->run() == FALSE)
            {
                $this->addCostCenter();
            }
            else
            {
                $CostCode = strtoupper(trim($this->input->post('CostCode')));
                $CostName = strtoupper(trim($this->input->post('CostName')));            
                $updatedBy = $this->session->userdata ( 'userId' );
				$SelectedDepartment =  $this->input->post('txtSelectedDepartment'); 
				$ApproverName =  $this->input->post('ApprovedBy'); 
				$comma_separated = "";
				//print_r(strlen($SelectedDepartment));
				if(strlen($SelectedDepartment)>0)
				{
					$comma_separated = explode(':', $SelectedDepartment);	
				}
				$dt = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
				
				$updateddt =  $dt->format('Y-m-d H:i:s');
				
				$CodeExists =  $this->costcenter_model->checkCostDetailsExists($CostCode);
				//print_r(count($CodeExists));
				if(count($CodeExists) > 0)
				{
				 $Cost = array( 'CostCenterName'=>$CostName,'ApprovedBy'=>$ApproverName,'UpdatedBy'=>$updatedBy,'UpdatedDate'=>$updateddt); 
				 $this->costcenter_model->EditCost($Cost,$CostCode);
				}
				//echo count($comma_separated);
					
				if(count($comma_separated)> 1)
				{
				    for ($j = 0; $j < count($comma_separated); $j++)
					  {	
							 $DeptCode = $comma_separated[$j];
						   
						     $this->costcenter_model->DeleteDepartment( $DeptCode,$CostCode);
						
							$Dept = array('CostCenterCode'=>$CostCode, 'DEPCode'=>$DeptCode,'CreatedBy'=>$updatedBy,'createdDate'=>$updateddt,'UpdatedBy'=>$updatedBy,'UpdatedDate'=>$updateddt);
							$this->costcenter_model->addCostCenterDepartment($Dept);				
									 
					}
				}
					
					$RowCount = $this->input->post('txtRowCount');
			        //$BudgetType = $this->input->post('BudgetType2');
					//echo  $BudgetType;
					for ($i = 1; $i <= $RowCount; $i++)
					 {				     
					  $BudgetType = $this->input->post('BudgetType'.$i);
					  $BudgetYear = $this->input->post('BudgetYear'.$i); 
					  $BudgetAmount = $this->input->post('BudgetAmount'.$i);  
					  $Remarks = $this->input->post('Remarks'.$i);
					  $this->costcenter_model->DeleteBudget( $BudgetType,$BudgetYear,$CostCode);
						
				     $Budget = array('CostCenterCode'=>$CostCode, 'BudgetType'=>$BudgetType,'BudgetYear'=>$BudgetYear,'BudgetAmount'=>$BudgetAmount,'Remarks'=>$Remarks,'CreatedBy'=>$updatedBy,'createdDate'=>$updateddt,'UpdatedBy'=>$updatedBy,'UpdatedDate'=>$updateddt);
					 $this->costcenter_model->addBudget($Budget);	
					 print_r( $BudgetType );
					}	
					
					echo('Successfully Updated Cost details');
          
            }
        
    }
	function viewcost($CostCenterID = NULL)
    {
        
            if($CostCenterID == null)
            {
                redirect('costListing');
            }
            
            $data['Cost'] = $this->costcenter_model->getuserinfo($CostCenterID);
            //$data['users'] = $this->purchaseorder_model->getusers();
            
            $this->global['pageTitle'] = 'Siddharth : View Cost';
            
            $this->loadViews("viewcost", $this->global, $data,NULL);
        
    }
	
	/**
     * This function is used to delete the user using userId
     * @return boolean $result : TRUE / FALSE
     */
    function deletecost()
    {
        if($this->isAdmin() == TRUE)
        {
            echo(json_encode(array('status'=>'access')));
        }
        else
        {
            $CostCenterID = $this->input->Costst('CostCentreID');
            $cost = array('CreateDate'=>date('Y-m-d H:i:sa'));
            
            $result = $this->costcenter_model->deletecost($Cost, $CostCenterID);
            
            if ($result > 0) { echo(json_encode(array('status'=>TRUE))); }
            else { echo(json_encode(array('status'=>FALSE))); }
        }
    }
    
	function export_cost(){
		
		
		$this->load->library('excel');
        $this->excel->setActiveSheetIndex(0)->mergeCells('G3:M3');
        $this->excel->setActiveSheetIndex(0)->getStyle('G3')->getAlignment()->applyFromArray(
    array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,)
);

        $this->excel->getActiveSheet()->setTitle('Cost Master');									
		





        $this->excel->getActiveSheet()->setCellValue('G3', 'SIDDHARTH INDUSTRIES Cost Master');
       $this->excel->getActiveSheet()->setCellValue('B5', 'S.No');
	   $this->excel->getActiveSheet()->setCellValue('C5', 'CostCenterCode');
        $this->excel->getActiveSheet()->setCellValue('D5', 'CostCenterName');
        $this->excel->getActiveSheet()->setCellValue('E5', 'CAPITAL');
        $this->excel->getActiveSheet()->setCellValue('F5', 'REVENUE');
        $this->excel->getActiveSheet()->setCellValue('G5', 'IMPORT');
        $this->excel->getActiveSheet()->setCellValue('H5', 'SERVICE');
        $this->excel->getActiveSheet()->setCellValue('I5', 'BudgetYear');
        $this->excel->getActiveSheet()->setCellValue('J5', 'DEPName');
        
        $this->excel->getActiveSheet()->setCellValue('K5', 'IsActive');
        $this->excel->getActiveSheet()->setCellValue('L5', 'Remarks');
        $this->excel->getActiveSheet()->setCellValue('M5', 'CreatedBy');
        $this->excel->getActiveSheet()->setCellValue('N5', 'UpdatedBy');
        $this->excel->getActiveSheet()->setCellValue('O5', 'IsApproved');
        $this->excel->getActiveSheet()->setCellValue('P5', 'ApprovedBy');
        
        


        $this->excel->getActiveSheet()->getStyle('G3')->getFont()->setSize(14);
        $this->excel->getActiveSheet()->getStyle('G3')->getFont()->setBold(true);
        $this->excel->getActiveSheet()->getStyle('B5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('B5')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('C5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('C5')->getFont()->setBold(true);
        $this->excel->getActiveSheet()->getStyle('D5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('D5')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('E5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('E5')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('F5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('F5')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('G5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('G5')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('H5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('H5')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('I5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('I5')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('J5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('J5')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('K5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('K5')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('L5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('L5')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('M5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('M5')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('N5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('N5')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('O5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('O5')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('P5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('P5')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('Q5')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('Q5')->getFont()->setBold(true);
		
		
        

       $exportData = $this->costcenter_model->export_excel();

        if ($exportData) {
            $i = 6;
            $s = 1;
            foreach ($exportData as $data) {
				
				$this->excel->getActiveSheet()->setCellValue('B'.  $i,$s);
              //$this->excel->getActiveSheet()->setCellValue('C'.  $i,$data['AssetCode']);
        $this->excel->getActiveSheet()->setCellValue('C'.  $i,$data['CostCenterCode']);
        $this->excel->getActiveSheet()->setCellValue('D'.  $i,$data['CostCenterName']);
        $this->excel->getActiveSheet()->setCellValue('E'.  $i,$data['capital']);
        $this->excel->getActiveSheet()->setCellValue('F'.  $i,$data['revenue']);
        $this->excel->getActiveSheet()->setCellValue('G'.  $i,$data['import']);
        $this->excel->getActiveSheet()->setCellValue('H'.  $i,$data['service']);
        $this->excel->getActiveSheet()->setCellValue('I'.  $i,$data['BudgetYear']);
        $this->excel->getActiveSheet()->setCellValue('J'.  $i,$data['DepartmentName']);
        
        $this->excel->getActiveSheet()->setCellValue('K'.  $i,$data['IsActive']);
        $this->excel->getActiveSheet()->setCellValue('L'.  $i,$data['Remarks']);
        $this->excel->getActiveSheet()->setCellValue('M'.  $i,$data['firstname']);
        $this->excel->getActiveSheet()->setCellValue('N'.  $i,$data['Updated_By']);
        $this->excel->getActiveSheet()->setCellValue('O'.  $i,$data['IsApproved']);
        $this->excel->getActiveSheet()->setCellValue('P'.  $i,$data['firstname']);
           

               

                $i++;
                $s++;
            }
        }

        $filename = 'Cost_Master' .' '.  '.xls'; //save our workbook as this file name
        header('Content-Type: application/vnd.ms-excel'); //mime type
        header('Content-Disposition: attachment;filename="' . $filename . '"'); //tell browser what's the file name
        header('Cache-Control: max-age=0'); //no cache
        $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
        if (ob_get_contents()) ob_end_clean();
        ob_start();
        $objWriter->save('php://output');


    }
    
    function pageNotFound()
    {
        $this->global['pageTitle'] = 'CodeInsect : 404 - Page Not Found';
        
        $this->loadViews("404", $this->global, NULL, NULL);
    }
}

?>