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

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

/**
 * Class : Employee  (Employee Controller)
 * User Class to control all user related operations.
 * @author : Gandhimathi
 * @version : 1.1
 * @since : 07 Apr 2017
 */
class payslip extends BaseController
{
     /**
     * This is default constructor of the class
     */
	 public function __construct()
    {
        parent::__construct();
        $this->load->model('payroll_model');
		 $this->load->library('form_validation');
        $this->isLoggedIn();   
    }


	/**
     * This function used to call stored procedure named with final_payroll_data()
     */
	public function callsp(){
		
		$payon = $this->input->post('payon');
		$employee = $this->input->post('employee');
		$result = $this->payroll_model->model_sp($payon,$employee);
       // $result = $this->db->last_query();
		return $result;
		//$this->db->call_function('model_sp');

}

	/**
     * This function used to load the first screen of the user
     */
	public function viewUpload()
    {
		 
        $this->global['pageTitle'] = 'Siddharth : Payroll Data Upload';
		
		        
        $this->loadViews("payslipupload", $this->global, null , NULL);
    }

    /**
    * This function used to load the first screen of the user
    */
    public function viewUpload2()
   {
        
       $this->global['pageTitle'] = 'Siddharth : Payroll Data Upload2';
        
                
       $this->loadViews("payslipupload2", $this->global, null , NULL);
   }
	
	/**
     * This function used to load the first screen of the user
     */
	public function viewGenerator()
    { 
	//echo 'inside funtion';
		$Data['Payon'] = $this->payroll_model->getPayOn();
		//$Data['Emplist'] = $this->payroll_model->getEmployeelist();
		
		
        $this->global['pageTitle'] = 'Siddharth : Payroll Generater';
		 
        $this->loadViews("payslipgenerate", $this->global, $Data , NULL);
    }
	/* Validation for Employee  Dropdown
	*/
	function  Employee_validate($selectValue)
{
	//echo 'select_validate  method called';
    // 'none' is the first option and the text says something like "-Choose one-"
    if($selectValue == '-1')
    {
        $this->form_validation->set_message('Employee_validate', 'Please Select Employee.');
        return false;
    }
    else // user picked something
    {
        return true;
    }
}

function getEmployee()
{
	   $id = $this->input->post('id1');
		
		  $result = $this->payroll_model->getEmployeelist2($id );
		  
	  $HTML="";

   if($result->num_rows() > 0){
	   
     foreach($result->result() as $list){
      
 
	   $HTML.="<option value='".$list->EmpId."'>".$list->EmpId."-".$list->Fname."</option>";
     }
   }
   echo $HTML;
}

/* Validation for PayOn  Dropdown
	*/
	function  PayOn_validate($selectValue)
{
	//echo 'select_validate  method called';
    // 'none' is the first option and the text says something like "-Choose one-"
    if($selectValue == '-1')
    {
        $this->form_validation->set_message('PayOn_validate', 'Please Select PayOn.');
        return false;
    }
    else // user picked something
    {
        return true;
    }
}
	/**
     * This function used to load the first screen of the user
     */
	public function PrintPdf()
    {
		
		    $All = $this->input->post('All');
			if($All == '')
			{
			$this->form_validation->set_rules('Employee','Employee','trim|callback_Employee_validate');
			}
			
			$this->form_validation->set_rules('PayOn','PayOn','trim|callback_PayOn_validate');
			
		   if($this->form_validation->run() == FALSE)
            {
                $this->viewGenerator();
            }
            else
            {
				$Payon = $this->input->post('PayOn');
							
				
				if($All != '')
				{
					
					$result = $this->payroll_model->getEmpAll($Payon);
					
					if($result > 0 )
					{               
						for($i=0;$i <count($result) ;$i++ )
						{
							 
							$EmpID =  $result[$i]['EmpId'];
						  
							$Data['PayDetails'] = $this->payroll_model->GetPayslipdata($Payon,$EmpID);
							$Data['Count'] = $i;
							
							$this->load->View("payslipgenerateprint", $Data );
							
						}
						
					}
				}
				else
				{
					$EmpID = $this->input->post('Employee');
					$Data['PayDetails'] = $this->payroll_model->GetPayslipdata($Payon,$EmpID);
				
					$this->load->View("payslipgenerateprint",  $Data );
					
				}
		
       
			$php  = $this->output->get_output();		
		    
			// Load library
			$this->load->library('dompdf_gen');
			
				if($All != '')
				{
					$filename = 'Payslip-'.$Payon.'.pdf' ;
				}
				else
				{
					$filename = 'Payslip-'.$EmpID . '-' .$Payon.'.pdf' ;
				}
			
			require_once(APPPATH .'third_party/dompdf/dompdf_config.inc.php');
			$dompdf = new DOMPDF();
			$dompdf->set_paper('A4', 'portrait');
			$dompdf->load_html($php);
			
			$dompdf->render();
			
			// add the header
			$canvas = $dompdf->get_canvas();
			$font = Font_Metrics::get_font("helvetica", "bold");

					// the same call as in my previous example
			$canvas->page_text(72, 18, "Page: {PAGE_NUM} of {PAGE_COUNT}",
                   $font, 6, array(0,0,0));
				   
			$dompdf->stream($filename); 
			}
	
    }
	
	
	/**
     * This function used to upload the Excel file Details
     */
	function uploadExcel(){
		  
		 
            $PayrollFileName  = ''; 
     	
            //Check whether user upload picture
            if(!empty($_FILES['userfile']['name']))
			{
				//echo 'inside if';
				$pathinfo = pathinfo($_FILES['userfile']['name']);
                $config['upload_path'] = 'uploads/files/';
                $config['allowed_types'] = 'xls|xlsx|csv';
                $config['file_name'] = $_FILES['userfile']['name'];
				 $config['overwrite'] = true;
                
                //Load upload library and initialize configuration
                $this->load->library('upload',$config);
                $this->upload->initialize($config);
				
                if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls')
					&& $_FILES['userfile']['size'] > 0 ) 
					{
						if($this->upload->do_upload('userfile'))
						{
							$uploadData = $this->upload->data();
							$PayrollFileName = $uploadData['file_name'];
							
							
						}
						else
						{
							$error = array('error' => $this->upload->display_errors());
							$PayrollFileName = '';
						}
						
						$inputFileName = $_FILES['userfile']['tmp_name'];
    
						require_once  APPPATH .'third_party/PHPExcel/IOFactory.php';
						$objTpl = PHPExcel_IOFactory::load($inputFileName);
						 
						$sheet = $objTpl->getActiveSheet(0) ;//->toArray(null, NULL, True, True);
						
						$highestRow = $sheet->getHighestRow(); 
						$highestColumn = $sheet->getHighestColumn();
						
						
						$i = 8;
						$dt = $sheet->getCell('PayOn')->getValue();
						$stringDate = PHPExcel_Style_NumberFormat::toFormattedString($dt, 'YYYY-MM-DD');
				        $date = new DateTime($stringDate);
						$PayOn = $date->format('m-Y');
						$createdby = $this->session->userdata ( 'userId' );
						$Totaldays 		= $sheet->getCell('I'.$i)->getValue();
						
						$FileExists = $this->payroll_model->checkFileDetailsExists($PayOn);
						
						 if (count($FileExists)== 0)
						 {
							 $FileDetails = array('PayOn'=>$PayOn,'TotalNoofDays'=>$Totaldays,'FileName'=>$PayrollFileName,'CreatedBy'=>$createdby);
							 $result = $this->payroll_model->UploadFileName($FileDetails);
						 }
						 else
						 {
							  $FileDetailsupdate = array('TotalNoofDays'=>$Totaldays,'FileName'=>$PayrollFileName,'CreatedBy'=>$createdby);
							  $result = $this->payroll_model->UpdateFileName($FileDetailsupdate,$PayOn);
							  $this->payroll_model->deleteFileData($PayOn);							  
						 }
						
						
						for($x=8; $x <= $highestRow; $x++) 
						{
							
							 $EmpId 			=   $sheet->getCell('C'.$x)->getValue(); 	
							 $BankAccountnumber	=   $sheet->getCell('E'.$x)->getValue(); 
							 $PFnumber	=   $sheet->getCell('F'.$x)->getValue(); 
							 $ESInumber	=   $sheet->getCell('G'.$x)->getValue(); 	
							 $UAnumber	=   $sheet->getCell('H'.$x)->getValue(); 							 
							 $NoOfWorkingdays 	=  $sheet->getCell('J'.$x)->getValue();
							 $LOP = $sheet->getCell('K'.$x)->getCalculatedValue();
							 $ActualSalary	 	= $sheet->getCell('L'.$x)->getValue();
							 $PerDaySalary	 	= $sheet->getCell('M'.$x)->getCalculatedValue();
							 $WorkedSalary	 =$sheet->getCell('N'.$x)->getCalculatedValue();
							 $BasicAndDA	 =$sheet->getCell('O'.$x)->getCalculatedValue(); 
							 $HRA			 =$sheet->getCell('P'.$x)->getCalculatedValue(); 
							 $OTWages		 = $sheet->getCell('Q'.$x)->getValue();
							 $OTPerHours	 =$sheet->getCell('R'.$x)->getValue(); 
							 $OTSalary		 =$sheet->getCell('S'.$x)->getCalculatedValue();
							 $GrosssSalary	 =$sheet->getCell('T'.$x)->getCalculatedValue(); 
							 $ESI			 = $sheet->getCell('U'.$x)->getCalculatedValue();
							 $PF			 =$sheet->getCell('V'.$x)->getCalculatedValue(); 
							 $ESIAndPF		 = $sheet->getCell('W'.$x)->getCalculatedValue();
							 $SalaryAsPerPF	 =$sheet->getCell('X'.$x)->getCalculatedValue(); 
							 $FoodAllowance	 = $sheet->getCell('Y'.$x)->getCalculatedValue();
							 $Incentive		 =$sheet->getCell('Z'.$x)->getValue(); 
							 $TotalSalary	 =  $sheet->getCell('AA'.$x)->getCalculatedValue();
							 $Advance		 =$sheet->getCell('AB'.$x)->getValue(); 
							 $BalanceAdvance = $sheet->getCell('AC'.$x)->getValue();
							 $LessAdvance	 = $sheet->getCell('AD'.$x)->getCalculatedValue();
							 $Signature		 =  $sheet->getCell('AE'.$x)->getValue();
							//echo  $EmpId ;
							 if( $EmpId != '')
							 {
							 
								 $FileData = array('PayOn'=>$PayOn,'EmpID'=>$EmpId,'NoofDaysWorked'=>$NoOfWorkingdays,'ActualSalary'=>$ActualSalary,'PerDaySalary'=>$PerDaySalary,'WorkedSalary'=>$WorkedSalary,'BasicPlusDA'=>$BasicAndDA,'HRA'=>$HRA,'OTWages'=>$OTWages,'OTperHours'=>$OTPerHours,'OTSalary'=>$OTSalary,'ESIGrossSalary'=>$GrosssSalary,'EmployeeESI'=>$ESI,'PF'=>$PF,'TotalDeduction'=>$ESIAndPF,'SalaryAsPerPF'=>$SalaryAsPerPF,'FoodAllowance'=>$FoodAllowance,'Incentive'=>$Incentive,'TotalSalary'=>$TotalSalary,'Advance'=>$Advance,'BalanceAdvance'=>$BalanceAdvance,'LessAdvance'=>$LessAdvance,'Remarks'=>$Signature,'BankAccountNumber'=>$BankAccountnumber,'PFNumber'=>$PFnumber,'ESINumber'=>$ESInumber,'UANNO'=>$UAnumber,'LOP'=>$LOP);								 
								 $result = $this->payroll_model->UploadFileData($FileData);				 
							
							 }													
						}
						
					    $data['Success']	=  "<script>alert('File Uploaded Successfully!');</script>";
						
						$this->global['pageTitle'] = 'Siddharth : Payroll Data Upload';
        
						$this->loadViews("payslipupload", $this->global, $data , NULL);
					}
					else
					{
						 $data['Fail']    = "<script>alert('Please select valid Excel file to Upload!');</script>";
						//echo "<script>alert('Please select valid Excel file to Upload!');</script>";
						 
					    $this->global['pageTitle'] = 'Siddharth : Payroll Data Upload';
        
						$this->loadViews("payslipupload", $this->global, $data , NULL);
					}
            }
			else
			{
				 $data['Fail']  = "<script>alert('Please select  Excel file to Upload!');</script>";
				//echo "<script>alert('Please select  Excel file to Upload!');</script>";
                $PayrollFileName = '';
				
				$this->global['pageTitle'] = 'Siddharth : Payroll Data Upload';
        
				$this->loadViews("payslipupload", $this->global, NULL , NULL);
            }
            
           
    }

    /**
     * This function used to upload the Excel file Details2
     */
    function uploadExcel2(){
          
         
            $PayrollFileName  = ''; 
        
            //Check whether user upload picture
            if(!empty($_FILES['userfile']['name']))
            {
                //echo 'inside if';
                $pathinfo = pathinfo($_FILES['userfile']['name']);
                $config['upload_path'] = 'uploads/files/';
                $config['allowed_types'] = 'xls|xlsx|csv';
                $config['file_name'] = $_FILES['userfile']['name'];
                 $config['overwrite'] = true;
                
                //Load upload library and initialize configuration
                $this->load->library('upload',$config);
                $this->upload->initialize($config);
                
                if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls')
                    && $_FILES['userfile']['size'] > 0 ) 
                    {
                        if($this->upload->do_upload('userfile'))
                        {
                            $uploadData = $this->upload->data();
                            $PayrollFileName = $uploadData['file_name'];
                            
                            
                        }
                        else
                        {
                            $error = array('error' => $this->upload->display_errors());
                            $PayrollFileName = '';
                        }
                        
                        $inputFileName = $_FILES['userfile']['tmp_name'];
    
                        require_once  APPPATH .'third_party/PHPExcel/IOFactory.php';
                        $objTpl = PHPExcel_IOFactory::load($inputFileName);
                         
                        $sheet = $objTpl->getActiveSheet(0) ;//->toArray(null, NULL, True, True);
                        
                        $highestRow = $sheet->getHighestRow(); 
                        $highestColumn = $sheet->getHighestColumn();
                        
                        
                        $x = 8;
                        $month=$this->input->post('mon');
                        $year=$this->input->post('yr');
                        $PayOn= $month . "-" . $year;
                        $createdby = $this->session->userdata ( 'userId' );


                        if($month=='01' || $month=='03' || $month=='05' || $month=='07' || $month=='08' || $month=='10' || $month=='12')
                        {
                        	$Totaldays      = 31;
                        }
                        else if($month=='04' || $month=='06' || $month=='09' || $month=='11'){
                        $Totaldays      = 30;	
                        }
                        else{
                        $Totaldays      = 28;	
                        }


                       // $Totaldays      = 0;
                        //echo $highestRow;
                        $FileDetails = array('PayOn'=>$PayOn,'TotalNoofDays'=>$Totaldays,'FileName'=> $config['file_name'],'CreatedBy'=>$createdby);
						$result = $this->payroll_model->UploadFileName($FileDetails);
                       $emplid=$this->payroll_model->getEmpID($q='');
					    
						
                        $Unknowncount=0;
						$Unknown="";
						$row="";
						$d=array("-1"=>"");
                        $fail=0;
                        $success=0;
                        for($x=8;$x<=$highestRow;$x++){
                            
                            $EmpId  =   $sheet->getCell('A'.$x)->getValue(); 
                            //echo $EmpId;
							
							$flag=0;
						     foreach($emplid as $e){
	
						    if(strtoupper($EmpId) == $e->EmpID){
	
						    $flag++;
						   // echo "<br>".$myvar.":- is valid empid";
							}
							 }
							if($flag==0){
								//echo "<br>".$myvar.":- not a valid empid";
								$Unknowncount++;
								$Unknown.='-'.$EmpId;
								$row.='-'.$x;
								//$d.=$EmpId;
								}
                            
                            $FileDataExists = $this->payroll_model->checkFileDetailsExists2($PayOn,$EmpId);
                            //echo $FileExists;
                        
                            //die();            
                         
                         //echo $FileDataExists;
                        //die();
                           if ($FileDataExists=='' || $FileDataExists==0)
                           {
                             //$FileDetails = array('PayOn'=>$PayOn,'TotalNoofDays'=>$Totaldays,'FileName'=>$PayrollFileName,'CreatedBy'=>$createdby);
                             
                            
                             
                            // $result = $this->payroll_model->UploadFileName($FileDetails);
                             
                            
                            
                          
                        
                        //for($x=8; $x <= $highestRow; $x++) 
                        //{
                            
                             
                             $EmpId  =   $sheet->getCell('A'.$x)->getValue();    
							 $EmpId=strtoupper($EmpId);							 
                             $LOPDays = $sheet->getCell('B'.$x)->getValue();
                             $OTHoursWorked  =$sheet->getCell('C'.$x)->getValue(); 
                             $loanRecovered=$sheet->getCell('D'.$x)->getValue(); 
                             $loanBalance=$sheet->getCell('E'.$x)->getValue(); 
                             $Incentive =$sheet->getCell('F'.$x)->getValue(); 
                             $Other_Deductions =$sheet->getCell('G'.$x)->getValue();  
                            
                             if( $EmpId != '')
                             {
								 
								 
								 foreach($emplid as $e){
	
						    if($EmpId == $e->EmpID){
	
                             
                                 $FileData = array('Month_Year'=>$PayOn,'EmpID'=>$EmpId,'LOP_Days'=>$LOPDays,'OT_Hrs_Worked'=>$OTHoursWorked,'Loan_Recovered'=>$loanRecovered,'Loan_Balance'=>$loanBalance,'Incentives'=>$Incentive,'Other_Deductions'=>$Other_Deductions,'Created_By'=>$createdby,'Created_Time'=>date("Y-m-d h:i:sa"));                                
                                 $result = $this->payroll_model->UploadFileData2($FileData);               
                                 $success++;
                             }                                                  
                        
								 }
                        
                        // $data['Success'] =  "<script>alert('File Uploaded Successfully!');</script>";
                        
                        // $this->global['pageTitle'] = 'Siddharth : Payroll Data Upload';
        
                        // $this->loadViews("payslipupload2", $this->global, $data , NULL);
                          
            
                    }
                    else{
                        
                        $fail++;
                        
                        // $data['Fail']    =  "<script>alert('Duplicate Data Found!');</script>";
                        
                        // $this->global['pageTitle'] = 'Siddharth : Payroll Data Upload';
        
                        // $this->loadViews("payslipupload2", $this->global, $data , NULL);
                    
                    }
					}
                        
                    
                    
            } //End of For Loop 
            
                      //  echo $success;
                        //echo $fail;
            
                        //$data['success']  =  "<script>alert($fail + 'Duplicate Data Found!');</script>";
                        echo "<script> alert($success +'  Data Uploaded sucessfully and  ' + $fail + '  Duplicate Data Found'); </script>";
                        echo "<script>alert($Unknowncount+'-data invalid, and data are'+'$Unknown'+'found at rows'+'$row');</script>";
                        $this->global['pageTitle'] = 'Siddharth : Payroll Data Upload';
        
                        $this->loadViews("payslipupload2", $this->global , NULL);
                        //redirect('monthlyListings');
                        
            
                    
        }        else
                    {
                         $data['Fail']    = "<script>alert('Please select valid Excel file to Upload!');</script>";
                        //echo "<script>alert('Please select valid Excel file to Upload!');</script>";
                         
                        $this->global['pageTitle'] = 'Siddharth : Payroll Data Upload2';
        
                        //$this->loadViews("payslipupload2", $this->global, $data , NULL);
                    }
            }
            else
            {
                 $data['Fail']  = "<script>alert('Please select  Excel file to Upload!');</script>";
                //echo "<script>alert('Please select  Excel file to Upload!');</script>";
                $PayrollFileName = '';
                
                $this->global['pageTitle'] = 'Siddharth : Payroll Data Upload2';
        
                $this->loadViews("payslipupload2", $this->global, NULL , NULL);
            }
            
           
    }
	function updatepayroll()
	{
		$this->global['pageTitle'] = 'Update Payroll';
		
		$this->loadViews("payslipeditable", $this->global, NULL , NULL);
	}
   
    function pageNotFound()
    {
        $this->global['pageTitle'] = 'CodeInsect : 404 - Page Not Found';
        
        $this->loadViews("404", $this->global, NULL, NULL);
    }
}

?>