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

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

/**
 * Class : Supplier Controller (supplier)
 * User Class to control all user related operations.
 * @author : Gandhimathi
 * @version : 1.1
 * @since : 12 Apr 2017
 */
class supplier extends BaseController
{
    /**
     * This is default constructor of the class
     */
	 public function __construct()
    {
        parent::__construct();
        $this->load->model('supplier_model');
		 $this->load->library('form_validation');  
        $this->load->library('pagination');	
		$this->load->library('Excel');
        $this->isLoggedIn();   
    }
	/**
     * This function used to load the first screen of the user
     */
	public function index()
    {
        $this->global['pageTitle'] = 'Siddharth : Supplier';
        
        $this->loadViews("supplierListing", $this->global, NULL , NULL);
    }
	
	/**
     * This function is used to load the Supplier list
     */
    function supplierListing()
    {
        
            $this->load->model('supplier_model');
        
                      
            $data['userRecords'] = $this->supplier_model->supplierListing();
            
            $this->global['pageTitle'] = 'Siddharth Industries : Supplier Listing';
            
            $this->loadViews("supplierListing", $this->global, $data, NULL);
        
    }
	/**
     * This function is used to load the add new supplier    */
    function addsupplier()
    {
           
            $data['payment'] = $this->supplier_model->getpayment();
            //$data['users'] = $this->purchaseorder_model->getusers();
            
            $this->global['pageTitle'] = 'siddharth : AddNew Supplier';

            $this->loadViews("addsupplier", $this->global,$data,  NULL);
        
    }
	/**
     * This function is used to check whether PAN already exist or not
    */
	 
	    function CheckPAN()
	{
		  $id = $this->input->post('id');
		
		  $query = $this->supplier_model->checkPAN($id );
			
	      $query =  $query[0]['PAN']; 				
		  
		  print_r($query);			
		 		  
	}
	 /* To Check the Pan Number is exists in the database or not for the selected Supplier */
	  function checkPanValidateSupplier()	  {   
	  
		  $SupplierID = $this->input->post('SupplierID');	
	      $PanNo = $this->input->post('panno');
		 // echo  'Sup'. $SupplierID ;
		  $query = $this->supplier_model->checkPAN($PanNo,$SupplierID);
		  if (count($query)> 0)
		  {
			 $this->form_validation->set_message('checkPanValidateSupplier', 'The Entered PAN Number is  already exists in the Database.');
			 return false;
		  }
		  else
		  {
			  return true;
		  }
	  }
	
	 /* To Check the Pan Number is exists in the database or not */
	  function checkPanValidate()
	  {   
		
	      $PanNo = $this->input->post('panno');
		 
		  $query = $this->supplier_model->checkPAN($PanNo);
		  if (count($query)> 0)
		  {
			 $this->form_validation->set_message('checkPanValidate', 'The Entered PAN Number is  already exists in the Database.');
			 return false;
		  }
		  else
		  {
			  return true;
		  }
	  }
	
	/**
     * This function is used to add new Supplier to the system
     */
    function addNewsupplier()
    {
        
        
            $this->form_validation->set_rules('SupplierName','Supplier Name','trim|required');
            $this->form_validation->set_rules('Address','Address','trim|required|');
           
            $this->form_validation->set_rules('ContactNumber','Contact Number','trim|required|numeric|max_length[10]');
            $this->form_validation->set_rules('AlternateContactNumber','Alternate Contact Number','trim|numeric|max_length[10]');
            $this->form_validation->set_rules('emailid','emailid', 'valid_email|max_length[128]|required');
        
            $this->form_validation->set_rules('TIN','TIN','trim|required|max_length[11]');
			
			$this->form_validation->set_rules('panno', 'panno', 'trim|required|max_length[10]|callback_checkPanValidate');
			
            
            if($this->form_validation->run() == FALSE)
            {
                $this->addsupplier();
            }
            else
            {
				$SupplierName = $this->input->post('SupplierName');
                $Address = $this->input->post('Address');                
                $ContactNumber = $this->input->post('ContactNumber');
                $AlternateContactNumber = $this->input->post('AlternateContactNumber');
                $EmailAddress = $this->input->post('emailid');
                $Exiseregistration = $this->input->post('Exciseregistration');
                $TIN = $this->input->post('TIN');
                $PAN = $this->input->post('panno');
                $GSTNo = $this->input->post('GSTNo');
                $GSTRange = $this->input->post('GSTRange');
                $CollectrateAddress = $this->input->post('CollectrateAddress');
                $UANumber = $this->input->post('UANumber');
                $PaymentTerms = $this->input->post('PaymentTerms');
                $Payment = $this->input->post('Payment');
                $PayableAT = $this->input->post('PayableAT');
				 $CSTNo = $this->input->post('CSTNo');
				 
				 $CSTDt = $this->input->post('dateofCST');
				 
				 if($CSTDt != '')
				{
				$CSTDate =  $this->getDateformat($CSTDt);
				}
				else
				{
					$CSTDate = null;
				}
                $Createdby = $this->session->userdata ( 'userId' );
            
                $supplier = array('SupplierName'=>$SupplierName, 'Address'=>$Address, 'ContactNumber'=>$ContactNumber, 'AlternateContactNumber'=> $AlternateContactNumber,'EmailAddress'=>$EmailAddress,'Exiseregistration'=>$Exiseregistration,'TIN'=>$TIN,'PAN'=>$PAN,'GSTNo'=>$GSTNo,'GSTRange'=>$GSTRange,'CollectrateAddress'=>$CollectrateAddress,'UANumber'=>$UANumber,'PaymentTerms'=>$PaymentTerms,'PaymentDays'=>$Payment,'PayableAT'=>$PayableAT,'CSTNo'=>$CSTNo,'CSTDate'=>$CSTDate,'Createdby'=>$Createdby);    
                
				$result = $this->supplier_model->addNewsupplier($supplier);
              
                if($result > 0)
                {
                   	 redirect('supplierListing','refresh');
					 echo "<script>alert('New Supplier Created successfully!');</script>";
                }
				
                else
                {
                   	 redirect('supplierListing','refresh');
					echo "<script>alert('Supplier Record Not Created!');</script>";
                }
            }
        
    }
	
	function getDateformat($Val)
	{
		       $date = new DateTime($Val);
				$retDate = $date->format('Y-m-d H:i:s');
				return $retDate;
	}
	/**
     * This function is used to edit the Supplier information
     */
    function editsupplier()
    {            
            $this->form_validation->set_rules('SupplierName','Supplier Name','trim|required');
            $this->form_validation->set_rules('Address','Address','trim|required|');
            $supplierID = $this->input->post('SupplierID');
			//echo 'supID' . $supplierID ;
            $this->form_validation->set_rules('ContactNumber','Contact Number','trim|required|numeric|max_length[10]');
            $this->form_validation->set_rules('AlternateContactNumber','Alternate Contact Number','trim|numeric|max_length[10]');
            $this->form_validation->set_rules('emailid','emailid','valid_email|max_length[128]|required');
        
            $this->form_validation->set_rules('TIN','TIN','trim|required|max_length[11]');
			
			$this->form_validation->set_rules('panno', 'panno', 'trim|required|max_length[10]|callback_checkPanValidateSupplier');
			
            if($this->form_validation->run() == FALSE)
            {
                $this->viewsupplier($supplierID);
            }
            else
            {
				
                $SupplierName = $this->input->post('SupplierName');
                $Address = $this->input->post('Address');                
                $ContactNumber = $this->input->post('ContactNumber');
                $AlternateContactNumber = $this->input->post('AlternateContactNumber');
                $EmailAddress = $this->input->post('emailid');
                $Exiseregistration = $this->input->post('Exciseregistration');
                $TIN = $this->input->post('TIN');
                $PAN = $this->input->post('panno');
                $GSTNo = $this->input->post('GSTNo');
                $GSTRange = $this->input->post('GSTRange');
                $CollectrateAddress = $this->input->post('CollectrateAddress');
                $UANumber = $this->input->post('UANumber');
                $PaymentTerms = $this->input->post('PaymentTerms');
                $Payment = $this->input->post('Payment');
                $PayableAT = $this->input->post('PayableAT');
                $UpdatedBy = $this->session->userdata ( 'userId' ); 							
				$chked =  $this->input->post('isactive');
				
					if( $chked != '')
					{
						$IsActive = '1';
					}
					else
					{
						$IsActive = '0';
					}
					
				 $CSTNo = $this->input->post('CSTNo');
				 
				 $CSTDt = $this->input->post('dateofCST');
				 
				 if($CSTDt != '')
				{
				$CSTDate =  $this->getDateformat($CSTDt);
				}
				else
				{
					$CSTDate = null;
				}
				$supplier = array();			
							
				$supplier = array('SupplierName'=>$SupplierName, 'Address'=>$Address, 'ContactNumber'=>$ContactNumber, 'AlternateContactNumber'=> $AlternateContactNumber,'EmailAddress'=>$EmailAddress,'Exiseregistration'=>$Exiseregistration,'TIN'=>$TIN,'PAN'=>$PAN,'GSTNo'=>$GSTNo,'GSTRange'=>$GSTRange,'CollectrateAddress'=>$CollectrateAddress,'UANumber'=>$UANumber,'PaymentTerms'=>$PaymentTerms,'PaymentDays'=>$Payment,'PayableAT'=>$PayableAT,'UpdatedBy'=>$UpdatedBy,'IsActive'=>$IsActive,'CSTNo'=>$CSTNo,'CSTDate'=>$CSTDate);    
                
                $result = $this->supplier_model->UpdateSupplier($supplier, $supplierID);
                								
               if($result == True)
                {
                  	 redirect('supplierListing','refresh');
					 echo "<script>alert('Supplier updated successfully!');</script>";
                }
				
                else
                {
                    redirect('supplierListing','refresh');
					echo "<script>alert('Supplier Record Not updated!');</script>";
                }
            }
        
    }
	
	function viewsupplier($SID = '')
    {        
			$Payment = '';    
			if($SID == '')
			{
			 $supplierID =  $_GET['SID']; 
			 $Payment   = $_GET['Payment'];  
			}
			else
			{
				
			  $supplierID  = $SID;	
			}			 
            
           
            $data['supplier'] = $this->supplier_model->getSupplierInfo($supplierID);
            $data['payment'] = $this->supplier_model->getpayment($Payment );
            $this->global['pageTitle'] = 'Siddharth : Edit Supplier'; 
			
            $this->loadViews("editSupplier", $this->global,$data, NULL);        
    }	
    
	/** this function can be use for excel report **/
	
	function export_supplierdetails(){
		
		
		$this->load->library('excel');
        $this->excel->setActiveSheetIndex(0);

        $this->excel->getActiveSheet()->setTitle('supplier details');									

        $this->excel->getActiveSheet()->setCellValue('A1', 'SupplierID');
        $this->excel->getActiveSheet()->setCellValue('B1', 'SupplierName');
        $this->excel->getActiveSheet()->setCellValue('C1', 'Address');
        $this->excel->getActiveSheet()->setCellValue('D1', 'ContactNumber');
        $this->excel->getActiveSheet()->setCellValue('E1', 'AlternateContactNumber');
        $this->excel->getActiveSheet()->setCellValue('F1', 'EmailAddress');
        $this->excel->getActiveSheet()->setCellValue('G1', 'Exiseregistration');
        $this->excel->getActiveSheet()->setCellValue('H1', 'TIN');
        $this->excel->getActiveSheet()->setCellValue('I1', 'PAN');
        $this->excel->getActiveSheet()->setCellValue('J1', 'CSTNO');
        $this->excel->getActiveSheet()->setCellValue('K1', 'CST Date');
        $this->excel->getActiveSheet()->setCellValue('L1', 'GST NO');
        $this->excel->getActiveSheet()->setCellValue('M1', 'GST Range');
        $this->excel->getActiveSheet()->setCellValue('N1', 'Collectrate Address');
        $this->excel->getActiveSheet()->setCellValue('O1', 'UANumber');
        $this->excel->getActiveSheet()->setCellValue('P1', 'PaymentTerms');
        $this->excel->getActiveSheet()->setCellValue('Q1', 'PaymentDays');
        $this->excel->getActiveSheet()->setCellValue('R1', 'PayableAT');
        $this->excel->getActiveSheet()->setCellValue('S1', 'Createdby');
        $this->excel->getActiveSheet()->setCellValue('T1', 'UpdatedBy');
        $this->excel->getActiveSheet()->setCellValue('U1', 'IsActive');
        
        


        $this->excel->getActiveSheet()->getStyle('A1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        $this->excel->getActiveSheet()->getStyle('B1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
        $this->excel->getActiveSheet()->getStyle('C1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('C1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('D1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('D1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('E1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('E1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('F1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('F1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('G1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('G1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('H1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('H1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('I1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('I1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('J1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('J1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('K1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('K1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('L1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('L1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('M1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('M1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('N1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('N1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('O1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('O1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('P1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('P1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('Q1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('Q1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('R1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('R1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('S1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('S1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('T1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('T1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('U1')->getFont()->setSize(12);
        $this->excel->getActiveSheet()->getStyle('U1')->getFont()->setBold(true);
        

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

        if ($exportData) {
            $i = 2;
            $s = 1;
            foreach ($exportData as $data) {
				
				$this->excel->getActiveSheet()->setCellValue('A' .  $i,$data['SupplierID']);
				$this->excel->getActiveSheet()->setCellValue('B' .  $i,$data['SupplierName']);
				$this->excel->getActiveSheet()->setCellValue('C' .  $i,$data['Address']);
				$this->excel->getActiveSheet()->setCellValue('D' .  $i,$data['ContactNumber']);
				$this->excel->getActiveSheet()->setCellValue('E' .  $i,$data['AlternateContactNumber']);
				$this->excel->getActiveSheet()->setCellValue('F' .  $i,$data['EmailAddress']);
				$this->excel->getActiveSheet()->setCellValue('G' .  $i,$data['Exiseregistration']);
				$this->excel->getActiveSheet()->setCellValue('H' .  $i,$data['TIN']);
				$this->excel->getActiveSheet()->setCellValue('I' .  $i,$data['PAN']);
				$this->excel->getActiveSheet()->setCellValue('J' .  $i,$data['CSTNO']);
				$this->excel->getActiveSheet()->setCellValue('K' .  $i,$data['CSTDate']);
				$this->excel->getActiveSheet()->setCellValue('L' .  $i,$data['GSTNO']);
				$this->excel->getActiveSheet()->setCellValue('M' .  $i,$data['GSTRange']);
				$this->excel->getActiveSheet()->setCellValue('N' .  $i,$data['CollectrateAddress']);
				$this->excel->getActiveSheet()->setCellValue('O' .  $i,$data['UANumber']);
				$this->excel->getActiveSheet()->setCellValue('P' .  $i,$data['PaymentTerms']);
				$this->excel->getActiveSheet()->setCellValue('Q' .  $i,$data['PaymentDays']);
				$this->excel->getActiveSheet()->setCellValue('R' .  $i,$data['PayableAT']);
				$this->excel->getActiveSheet()->setCellValue('S' .  $i,$data['firstname']);
				$this->excel->getActiveSheet()->setCellValue('T' .  $i,$data['Update_by']);
				$this->excel->getActiveSheet()->setCellValue('U' .  $i,$data['IsActive']);
              
           

               

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

        $filename = 'supplierdetails' .' '.  '.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'] = 'Siddharth : 404 - Page Not Found';
        
        $this->loadViews("404", $this->global, NULL, NULL);
    }
}

?>